Compilerchapter 4
Compilerchapter 4
1 $ Input String$
... ... ... ...
N $ Start symbol $ Accept
Example: Use the shift-reduce to parse the string
id1+id2*id3 using the grammar
E E E
E E*E
E (E)
E id
n(steps) Parsing stack Input buffer Action
1
$ $ Shift
2
$ $ Reduce
3
$ $ Shift
4
$ $ Shift
5
$ $ Reduce
6
$ $ Shift
7
$ $ Shift
8
$ $ Reduce
9
$ $ Reduce
10
$ $ Reduce
11
$ $ Accept
Example Use the shift-reduce to parse the string
id1*id2 using the grammar
Exercise : Apply shift-reduce to the following input: 000111
and the following productions:
S-> 0S1 | 01
LR Parser
It is a class of bottom-up methods for parsing that accept a
much larger class of grammars than LL(1) parsing, though
still not all grammars.
LR(1) – LR Parser:
o Works on complete set of LR(1) Grammar
o Generates large table and large number of states
o Slow construction
The most powerful, and the most expensive
LALR(1) – Look-Ahead LR Parser:
o Works on intermediate size of grammar
o Number of states are same as in SLR(1)
LR parsers are table-driven bottom-up parsers and use two kinds of
“actions” involving the input stream and a stack:
-Shift
-Reduce
LR parsers are also called shift-reduce parsers.
Semantic attributes
-may be assigned to their values from their domain at
the time of parsing and
-evaluated at the time of assignment or conditions.
Categories of Attributes:
-synthesized attributes and
-inherited attributes.
Synthesized Attributes
These attributes get values from the attribute
values of their child nodes.
-never take values from their parent nodes or
any sibling nodes.
A SDD that uses synthesized attributes exclusively is
said to be an S- attributed definition.
A parse tree for an S-attributed definition can always
be annotated by evaluating the semantic rules for the
attributes at each node bottom-up, from the leaves to
the root.
pr int( E.val )
E.val E1.val T .val
E.val T .val
T .val T1.val * F .val
T .val F .val
F .val E.val
F .val digit.lexval
L.in T .type
T .type int eger
T .type real
L1.in L.in, addtype(id .entry, L.in)
L-attributed SDT
- uses both synthesized and inherited
attributes with restriction of not taking
values from right siblings.