Lab Compilers
Lab Compilers
Lab Compilers
I. OBJECTIVE:
We can think of using CFGs to parse various language constructs in the token streams
freed from simple syntactic and semantic errors, as it is easier to describe the
constructs with CFGs. But CFGs are hard to apply practically. In this session, we
implement a simple recursive descent parser to parse a number of types of statements
after exercising with simpler CFGs. We note that a recursive descent parser can be
constructed from a CFG with reduced left recursion and ambiguity.
S → b | AB
A →a | aA Language generated: {b, ab, aab, aaab, …..}
B →b
** Find if there is any logical error in the sample code shown above.
2. A CFG to describe the syntax of simple arithmetic expressions may look like the one
that follows:
Non-terminal symbols:
<Exp>→<Term> + <Term> | <Term> - <Term> | <Term> <Exp>, <Term>, <Factor>
Page | 14
III. LAB EXERCISE:
A → aXd
X → bbX
X → bcX
X→
2. Implement the CFG shown above for generating simple arithmetic expressions.
<stat>→<asgn_stat><dscn_stat><loop_stat>
<asgn_stat>→id = <expn>
<expn>→<smpl_expn> <extn>
<extn>→<relop> <smpl_expn> |
<relop>→ ==!=<=>=><
Page | 15
Session 6: Predictive Parsing
I. OBJECTIVES:
Manual implementation of LL(1) and LR(1) parsing algorithms.
❖ To compute FOLLOW(A) for all non-terminals A, apply the following rules until
nothing can be added to any FOLLOW set.
i. Place $ in FOLLOW(S), where S is the start symbol and $ is the right end-marker
of an input.
ii. If there is a production A →B, then everything in FIRST() except is in
FOLLOW(B).
iii. If there is a production A →B, then everything in FOLLOW(A) is in FOLLOW(B).
iv. If there is a production A →B where FIRST() contains , then everything in
FOLLOW(A) is in FOLLOW(B).
Page | 16
Sample input and corresponding output:
Table for LL(1) non-recursive predictive parsing with the given grammar:
3 5
A
a
ACTION GOTO
State FOLLOW(S) = {$}
a b $ S A
0 s3 1 2 FOLLOW(A) = {b, $}
1 acc
2 s4
3 s3 r3 r3 5
4 s3 6 FIRST(S) = FIRST(A) ={a}
5 r2 r2
6 r1
If A →• is in Ii, then set ACTION(i, a) to “Reduce by A →” for all a in FOLLOW(A).
Page | 17
IV. LAB EXERCISE:
Perform the tasks1, 2, and 3 of the Assignment #6 which is described below.
V. ASSIGNMENT #6:
Suppose, you are given the following grammar and the input string abcd.
S →aXd
X → YZ
Y→b
Y →
Z →cX
Z →
Page | 18