next up previous
Next: A starting point for the Up: Compiler Theory: Assignment 3 Previous: The factorial

Implementing translation schemes with YACC

WRITING TRANSLATION SCHEMES WITH YACC.

In all our previous examples with YACC we were

This works because a YACC parser is a bottom-up parser. But in fact YACC can do more.


HOW YACC HANDLES PRODUCTIONS EMBEDDED WITH ACTIONS? An action occurring inside the right side of a production

For instance the following translation scheme fragment
A $ \longmapsto$ B1 {e1B2 {e2B3 {e3}
is equivalent to
A $ \longmapsto$ B1 C1 B2 C2 B3 C3
C1 $ \longmapsto$ $ \varepsilon$ {e1}
C2 $ \longmapsto$ $ \varepsilon$ {e2}
C3 $ \longmapsto$ $ \varepsilon$ {e3}
In YACC


PASSING IDENTIFIER TYPES Consider the following translation scheme.

D $ \longmapsto$ T {L.in := T.typeL
T $ \longmapsto$ $ \bf int$ {T.type := $ \bf int$}
T $ \longmapsto$ $ \bf real$ {T.type := $ \bf real$}
L $ \longmapsto$ { L1.in := L.in } L1$ \bf ,$$ \bf id$
    { addtype ($ \bf id$.entry, L.in) }
L $ \longmapsto$ $ \bf id$ { addtype ($ \bf id$.entry, L.in) }
Consider the following sentence generated by the above grammar.
real p, q, r
A bottom-up parse of this sentence will result in applying backwards the rules below in this order:
  1. T $ \longmapsto$ $ \bf real$
  2. L $ \longmapsto$ $ \bf id$
  3. L $ \longmapsto$ L,$ \bf id$
  4. L $ \longmapsto$ L,$ \bf id$
  5. D $ \longmapsto$ TL
When one needs the inherited attribute L.in. Observe that


PASSING INHERITED ATTRIBUTES. In a situation like

S $ \longmapsto$ aA {C.i := A.sC
S $ \longmapsto$ bAB {C.i := A.sC
C $ \longmapsto$ c {C.s := g(C.i)}
In a YACC program for this translation scheme how to access to C.i The solution is to use a dummy nonterminal, called a marker. We change the above translation scheme to
S $ \longmapsto$ aA {C.i := A.sC
S $ \longmapsto$ bAB {M.i := A.sM {C.i := M.sC
M $ \longmapsto$ $ \varepsilon$ {M.s := M.i}
C $ \longmapsto$ c {C.s := g(C.i)}
Then a YACC program for the above translation scheme will look like:
S     : a A C 
      | b A B M C
      ;
M     :   /* empty */  {$$ = $-2}
      ;
C     :  c {$$ = g($-1)} ;


next up previous
Next: A starting point for the Up: Compiler Theory: Assignment 3 Previous: The factorial
Marc Moreno Maza
2004-12-01