CSDS337 - 2024 PS3 Solution
CSDS337 - 2024 PS3 Solution
Problem 1 - 10 points
Design grammar for the following language:
• The set of all strings of 0s and 1s such that every 0 is immediately followed by at least one 1.
Problem 2 - 20 points
The following is a grammar for regular expressions over symbols a and b only, using + in place of | for
union, to avoid conflict with the use of vertical bar as a metasymbol in grammars:
b Does left factoring make the grammar suitable for top-down parsing?
c In addition to left factoring, eliminate left recursion from the original grammar.
a No left-factoring is required.
c rexpr → rterm A
A → + rterm A |
rterm → rf actor B
B → rf actor B |
rf actor → rprimary C
C→ ∗ C |
rprimary → a|b
d Yes, it is.
Problem 3 - 20 points
Consider the grammar for S −→ S + S|SS|(S)|S ∗ |a and the string (a + a) ∗ a.
a Devise a predictive parser and show the parsing tables. You may use left-factor and/or eliminate
left-recursion from your grammar first.
1
b Compute FIRST and FOLLOW for your grammar.
Solution:
a S −→ SA|(S)|a
A −→ +S|S|∗
which leads to
S −→ SA|T
A −→ +S|S|∗
T −→ (S)|a
b i=1
S −→ T B
B −→ AB|
i=2
j=1
A −→ +S|T B|∗
i=2
j=1
j=2
S −→ T B
B −→ AB|
A −→ +S|T B|∗
T −→ (S)|a
c FIRST(T) = [(, a]
FIRST(A) = [+, ∗]+ FIRST(T) = [+, ∗, (, a]
FIRST(B) = + FIRST(A) = [, +, ∗, (, a]
FIRST(S) = FIRST(T) = [(, a]
FOLLOW(T) = [$, +, ∗, (, a]
FOLLOW(A) = [$, +, ∗, (, ), a]
FOLLOW(B) = [$]
FOLLOW(S) = [$, +, ∗, (, ), a]
d Look at Table 1.
Nonterminal ( ) + * a $
S S → TB S →TB
B B → AB B → AB B → AB B → AB B→
A A → TB A → +S A→ A → TB
T T → (S) T→a
2
Problem 4 - 10 points
Give the bottom-up parses for the following input string and grammar: aaa ∗ a + + and S −→
SS + |SS ∗ |a.
Solution:
S → aaa ∗ a + + → Saa ∗ a + + → SSa ∗ a + + → SSS∗a + + → SSa + + → SSS++ → SS+ → S
Problem 5 - 20 points
Construct the SLR sets of items for the (augmented) grammar S −→ SS + |SS ∗ |a. Compute the
GOTO function for these sets of items. Show the parsing table for this grammar. Is this grammar
SLR?
Solution:
• FOLLOW(S) = [$]
FOLLOW(A) = [a, $]
FOLLOW(B) = [+, * ,$]
• Left-factor and left recursion elimination gives you the following grammar:
S’ → S
S→|aB
B→aBAB|
A→+|*
• Figure 1 shows the LR0 items and GOTO function for the grammar S −→ SS + |SS ∗ |a
Figure 1: The LR0 items and GOTO function for the grammar S −→ SS + |SS ∗ |a
3
• The parsing table 2 has no conflicts so this is an SLR grammar.
State a + * $ S A B
0 s2 s1
1 acc
2 s4 r3 r3 r3 s3
3 r1
4 s4 r3 r3 r3 s5
5 s7 s8 s6
6 s4 r3 r3 r3 s9
7 r4 r4
8 r5 r5
9 r2 r2 r2
Problem 6 - 20 points
Construct the canonical parsing table for the following augmented grammar:
S 0 −→ S
S −→ AA
A −→ aA|b
4
Figure 2: *
5
6
Figure 4: Canonical Parsing Table