Compilers Derivations Alex Aiken
Derivations A derivation is a sequence of productions S … … … … … A derivation can be drawn as a tree – Start symbol is the tree’s root – For a production X Y 1 … Y n add children Y 1 … Y n to node X Alex Aiken
Derivations • Grammar E E + E | E E | (E) | id • String id id + id Alex Aiken
Derivations E E E+E E + E E E+E E * E id id E + E id id + E id id id id + id Alex Aiken
Derivations E E Alex Aiken
Derivations E E + E E E+E Alex Aiken
Derivations E E + E E E+E E * E E E E + Alex Aiken
Derivations E E E + E E+E E * E E E+E id E + E id Alex Aiken
Derivations E E E + E E+E E E+E E * E id E + E id id id id + E Alex Aiken
Derivations E E E+E E + E E E+E E * E id id E + E id id + E id id id id + id Alex Aiken
Derivations • A parse tree has – Terminals at the leaves – Non-terminals at the interior nodes • An in-order traversal of the leaves is the original input • The parse tree shows the association of operations, the input string does not Alex Aiken
Derivations • The example is a left-most E derivation E+E – At each step, replace the left- most non-terminal E+id E E + id • There is an equivalent E id + id notion of a right-most derivation id id + id Alex Aiken
Derivations E E Alex Aiken
Derivations E E + E E E+E Alex Aiken
Derivations E E + E E E+E id E+ id Alex Aiken
Derivations E E E + E E+E E * E id E+id E E + id Alex Aiken
Derivations E E E + E E+E E+id E * E id E E + id id E id + id Alex Aiken
Derivations E E E+E E + E E+id E * E id E E + id E id + id id id id id + id Alex Aiken
Derivations Note that right-most and left-most derivations have the same parse tree Alex Aiken
Derivations Which of the following is a valid S aXa derivation of the given grammar? X | bY S Y | cXc | d aXa S abYa aa acXca acca S S aXa aXa abYa abYa abcXca abcXcda abcbYca abccda abcbdca
Derivations Which of the following is a valid S aXa parse tree for the given grammar? X | bY S a X a Y | cXc | d S b Y a X a c X c d b Y S S a X a a X a b Y b Y c X c c X c d
Derivations • We are not just interested in whether s L(G) – We need a parse tree for s • A derivation defines a parse tree – But one parse tree may have many derivations • Left-most and right-most derivations are important in parser implementation Alex Aiken
Recommend
More recommend