Cs 606
Cs 606
Assignment
Student Name:Kainat
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.
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 ? ?
...
Solution:
Non-Terminals:
Program,
StmtList,
Stmt,
Decl,
Assign,
IfStmt,
Expr,
Cond,
Op,
Var,
Num
Terminals:
int,
if,
(, ),
=,
+,
>,
;,
identifiers (like x), numbers (like 5)
CFG Rules:
ebnf
CopyEdit
1. Program → StmtList
2. StmtList → Stmt StmtList | ε
3. Stmt → Decl | Assign | IfStmt
4. Decl → int Var = Expr ;
5. Assign → Var = Expr ;
6. IfStmt → if ( Cond ) Stmt
7. Cond → Expr > Expr
8. Expr → Expr + Expr | Var | Num
9. Var → x | y | z | ... // Simplified set
10. Num → 0 | 1 | 2 | ... // Simplified set
b) Derivation Table
Code Snippet:
c
CopyEdit
int x = 5;
if (x > 0)
x = x + 1;
Derivation Table:
c
CopyEdit
int x = 5;
if (x > 0)
x = x + 1;