Вы находитесь на странице: 1из 22

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 trees root For a production X Y1Yn add children Y1Yn 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 id E + E id id + E id id + id

E
id

E
id

id

Alex Aiken

Derivations E

Alex Aiken

Derivations E
E E+E

Alex Aiken

Derivations E
E E+E E E+E

Alex Aiken

Derivations E
E E+E E E+E id E + E

E
id

Alex Aiken

Derivations E E + E

E E+E E E+E id E + E id id + E

E
id

E
id
Alex Aiken

Derivations E E + E

E E+E E E+E id E + E id id + E id id + id

E
id

E
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 derivation
At each step, replace the leftmost non-terminal

E E+E E+id E E + id E id + id id id + id
Alex Aiken

There is an equivalent notion of a right-most derivation

Derivations E

Alex Aiken

Derivations E
E E+E

Alex Aiken

Derivations E
E E+E E+id

id

Alex Aiken

Derivations E
E E+E E+id E E + id

id

Alex Aiken

Derivations E E + E

E E+E E+id E E + id E id + id

E
id

id

Alex Aiken

Derivations E E + E

E E+E E+id E E + id E id + id id id + id

E
id

E
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 derivation of the given grammar?


S aXa abYa acXca acca S aa

S aXa X | bY Y | cXc | d

S aXa abYa abcXca abcbYca abcbdca

S aXa abYa abcXcda abccda

Derivations Which of the following is a valid parse tree for the given grammar?
S a b c X X Y c d a a b S a a Y X c d X a S X Y a

S aXa X | bY Y | cXc | d

S a c X b

b
c

Y
X c

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

Вам также может понравиться