Professional Documents
Culture Documents
Prepared by
Replaces call to X.
case Next_Token of
begin SL end id := E; SL S S }
T_begin : Read(T_begin); S; Write (SL S); while Next_Token in {T_begin,T_id} do S; Write (SL SL S); od Read(T_end); Write (S begin SL end);
Construction of Derivation Tree for the Original Grammar (Bottom Up) (contd)
T_id :
end end;
Read(T_id); Read (T_:=); E; Read (T_;); Write (S id :=E ;); otherwise Error;
Construction of Derivation Tree for the Original Grammar (Bottom Up) (contd)
proc E; {(1)E TY (2) E E+T Y +TY T } T; Write (E T); while Next_Token = T_+ do Read (T_+); T; Write (E E+T); od end
Construction of Derivation Tree for the Original Grammar (Bottom Up) (contd)
proc T; {(1)T PX (2) T P*T X *T P } P; if Next_Token = T_* then Read (T_*); T; Write (T P*T) else Write (T P); end;
Construction of Derivation Tree for the Original Grammar (Bottom Up) (contd)
proc P;{(1)P (E) (2)P (E) id id }
//
end;
SAME AS BEFORE
Example
Input String: begin id := (id + id) * id; end Output:
P T E P T E P P T
id P T id P E+T (E) id P
Generating the Abstract Syntax Tree, Bottom Up, for the Original Grammar
proc S; { S begin S+ end 'block' id := E; 'assign' var N:integer; case Next_Token of T_begin : Read(T_begin); S; Build Tree (x,n) N:=1; pops n trees from while Next_Token in {T_begin,T_id} do S; the stack, builds an N:=N+1; x node as their od parent, and pushes Read(T_end); the resulting tree. Build Tree ('block',N); T_id : Read(T_id); Assume this Read (T_:=); E; builds a node. Read (T_;); Build Tree ('assign',2); otherwise Error end end;
Generating the Abstract Syntax Tree, Bottom Up, for the Original Grammar (contd)
proc E; {E E+T '+' T }
T; while Next_Token = T_+ do Read (T_+) T; Build Tree ('+',2); od end; Left branching in tree!
Generating the Abstract Syntax Tree, Bottom Up, for the Original Grammar (contd)
proc T; {T P*T '*' P }
Generating the Abstract Syntax Tree, Bottom Up, for the Original Grammar (contd)
proc P;{P (E) id } // SAME AS BEFORE, // i.e.,no trees built end;
Example
Input String: begin id1 := (id2 + id3) * id4; end Sequence of events: id1 id2 id3 id4 BT('*',2) BT('assign',2) BT('block',1)
BT('+',2)
Summary
Bottom-up or top-down tree construction. Original or modified grammar. Derivation Tree or Abstract Syntax Tree. Technique of choice (Hint: project) Top-down, recursive descent parser. Bottom-up tree construction for the original grammar.
AST Generation
Programming Language Principles Lecture 6
Prepared by