Spring 2025 - CS606 - 1
Spring 2025 - CS606 - 1
Total Marks: 20
Assignment No. 01
Due Date: May 12, 2025
Semester: Spring 2025
Suppose that you are developing a simplified compiler for a small scripting language. The language
supports variable declarations, arithmetic operations, and if statements.
[a)] Design a CFG that incorporates these features using appropriate non-terminals and terminals.
Answer:
Non-Terminals
Program: The entire program.
StmtList: A list of statements.
Stmt: A single statement (declaration, assignment, or if statement).
Decl: A variable declaration.
Assign: An assignment statement.
IfStmt: An if statement.
Expr: An arithmetic or relational expression.
Term: A term in an arithmetic expression.
Factor: A factor in an arithmetic expression.
RelOp: A relational operator (for conditions in if statements).
Type: The type of a variable (e.g., Int).
Terminals:
int: Keyword for integer type.
if: Keyword for if statement.
id: Identifier (variable name, e.g., x).
num: Numeric literal (e.g., 5, 0, 1).
=: Assignment operator.
+: Addition operator.
>: Greater-than operator (for simplicity, we include only > for relational operations),
(: Left parenthesis.
): Right parenthesis,
;: Semicolon (statement terminator).
{: Left brace (for if statement body, assuming a block structure).
}: Right brace.
1
CS606 – Compiler Construction
Total Marks: 20
Assignment No. 01
Due Date: May 12, 2025
Semester: Spring 2025
CFG RULES:
1. Program → StmtList
2. StmtList → Stmt StmtList | ε
3. Stmt → DeclStmt | AssignStmt | IfStmt
4. DeclStmt → Type ID = Expr ;
5. AssignStmt → ID = Expr ;
6. IfStmt → if ( Expr ) {StmtList}
7. Expr → Term RelOp Term
8. Term → Term + Factor
9. Term → Factor
10. Factor → id
11. RelOp → > | < | == | != | >= | <=
12. Type → int
a)[b)] Provide a derivation of a short code snippet using your CFG in a tabular form, as given below:
Code Snippet:
int x = 5;
if (x > 0)
x = x + 1;
1 Program Program
2 1 StmtList
3 ? ?
2
CS606 – Compiler Construction
Total Marks: 20
Assignment No. 01
Due Date: May 12, 2025
Semester: Spring 2025
Answer:
1 1 Program
3 2 Stmt StmtList
4 4 Decl StmtList