0% found this document useful (0 votes)
5 views3 pages

Cs 606

it is assignment solution of cs606

Uploaded by

aryanmadadali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Cs 606

it is assignment solution of cs606

Uploaded by

aryanmadadali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Cs606

Assignment

Student Name:Kainat

Student Id: Bc210423985

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;

Step Rule Applied Sentential Form

1 Program Program

2 1 StmtList

3 ? ?

...

Solution:

a) Context-Free Grammar (CFG) Design


We are designing a CFG for a simple scripting language with:

 Variable declarations (int x = 5;)


 Arithmetic operations (x = x + 1;)
 if statements (if (x > 0) x = x + 1;)

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:

Step Rule Applied Sentential Form


1 1 Program
2 Program → StmtList StmtList
3 2 Stmt StmtList
4 4 (Decl) Decl StmtList
5 4 int Var = Expr ; StmtList
6 9, 10 int x = Num ; StmtList
7 Num → 5 int x = 5 ; StmtList
8 2 Stmt StmtList
9 6 (IfStmt) if ( Cond ) Stmt
10 7 if ( Expr > Expr ) Stmt
11 8, 9, 10 if ( x > 0 ) Stmt
12 5 (Assign) if ( x > 0 ) Var = Expr ;
13 9 if ( x > 0 ) x = Expr ;
14 8 → Expr + Expr if ( x > 0 ) x = Expr + Expr ;
15 9, 9 if ( x > 0 ) x = x + x ;
16 Replace final x with 1 if ( x > 0 ) x = x + 1 ;

Final sentential form:

c
CopyEdit
int x = 5;
if (x > 0)
x = x + 1;

You might also like