GATE / CS ARCHIVE

SIMILAR QUESTIONS / COMPILER DESIGN

Execute embedded translation actions in order

2 questions solved the same way, newest first. Back to Compiler Design

How these are solved

Trace grammar expansion/recognition and execute each embedded action at its exact position. Different grammars and output strings; end-of-reduction-only actions kept separate.

2 marks · MCQ
Report issue

Translation scheme with nonstandard precedence

Semantic Analysis & Type Checking

Question 59, GATE 2006: A syntax-directed translation has productions:
S→ER
R→*E {print('*')} R | ε
E→F+E {print('+')} | F
F→(S) | id {print(id.value)}
Here id denotes an integer. What is printed on input 2*3+4?
Options:
(A) 2*3+4
(B) 2*+34
(C) 23*4+
(D) 234+*
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. S→ER and R→*E{print(*)}R|ε put multiplication below the expression E; E→F+E{print(+)}|F groups the addition on the right. For 2*3+4, first print 2, then parse E for 3+4, printing 3,4,+, then print * when that E finishes.

2. The output is 234+*, option D. Applying ordinary arithmetic precedence would incorrectly give 23*4+.

3. Teaching check: Semantic print actions fire at their positions in the grammar, not according to the usual arithmetic-precedence rules. The E nonterminal consumes the whole 3+4 before R’s multiplication-print action runs. The result is therefore postfix for 2*(3+4).

Original paper, page 9

2 marks · MCQ
Report issue

Output order of embedded translation actions

Semantic Analysis & Type Checking

Question 58, GATE 2003: A translation scheme is S→TR; R→+ T {print('+');} R | ε; T→num {print(num.val);}. Token num represents an integer, and num.val is its value. For input 9+5+2, what is printed?
A. 9+5+2
B. 95+2+
C. 952++
D. ++952
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step through it (19 steps)

1. Expand S→TR. The initial T consumes 9 and immediately prints 9.
2. The first R consumes + and invokes T on 5, printing 5. Its following action prints + before the recursive R begins.
3. That recursive R consumes +, invokes T on 2 and prints 2, then prints +. Its final R chooses ε and prints nothing.
4. Concatenating the actions yields 9,5,+,2,+, or 95+2+, B. Moving the plus action to after the recursive R would change the result, but that is not this scheme.

Solution: The initial T prints 9. Each R expansion reads +, processes T (which prints the next number), prints +, and only then processes the remaining R. Hence the execution order is 9,5,+,2,+, yielding 95+2+, option B. The action is before the recursive R, so it does not postpone both plus signs to the end.

Original paper, page 8