Parsing & Syntax Analysis



Answer & solution
Answer: E→TR; R→−TR|−(S)R|ε; S→T−TR|T−(S)R; T→idU|(S)/FU; U→/FU|ε; F→id|(S)|(T/F)|((S)/F). (no official key was published)
First notice the indirect cycle E→S→E−T or E−(S). Removing only the obvious T→T/F recursion is insufficient. Substitute S’s alternatives into E to obtain E→T | E−T | E−(S). Its recursive suffixes are −T and −(S); its base is T. Introduce a tail R:
E→T R
R→−T R | −(S) R | ε.
S must still mean a subtraction-rooted expression, not an arbitrary E. Substituting E=T R into S initially gives S→T R−T | T R−(S). This is valid, but an equivalent clearer form selects the first subtraction and then any remaining subtraction tail:
S→T−T R | T−(S) R.
Both describe a T followed by a nonempty sequence of subtraction suffixes. Their ordering is preserved; the rewrite is about syntax, not commuting arithmetic operations.
Remove T’s immediate recursion T→T/F | id | (S)/F using a new tail U:
T→id U | (S)/F U
U→/F U | ε.
Keep F→id | (S) | (T/F) | ((S)/F).
The complete grammar is the six displayed groups E,R,S,T,U,F. Every nonempty derivation of T begins with id or “(”. E and S begin through T; F directly begins with id or “(”; R begins with “−” or ε, and U with “/” or ε. No nonterminal can derive itself as the leftmost symbol, so neither direct nor indirect left recursion remains. The language is unchanged by the standard tail transformation. When constructing semantic actions, fold each R or U sequence leftward to retain the original left-associative parse: right-recursive grammar tails must not accidentally change subtraction or division evaluation order. The at-most-one-extra-production restriction belongs to part (b); part (c) requires the additional tail nonterminals.