Chapter 3 Syntax Analyzer
Chapter 3 Syntax Analyzer
Syntax Analysis
Example 1
• Grammar: G = { N, T, S, P }; N = { S, A, B }; T = { a, b, d };
S={S}
Example 2
Grammar: = {N, T, S, P }; N = { E }; T = { +, -, *, /, (, ), id }; S = { E }
• P: E -> E+E / E-E / E*E / E/E / (E) / id.
a. String: id + id.
Solution: E -> E + E
Compiler Design-Woldia University by:- Michael W.
7
id +E Accept.
id + id.
Acce
pt.
b.
String:
( id +
id ).
Solutio
n: E ->
(E)
( Example 3
• Grammar:E G = { N, T, S, P }; over the alphabet
{a,b}. +
• P (Production Rules) : S -> aSb | ε
E
Compiler Design-Woldia University by:- Michael W.
8
)
Generate the context-free (and non-regular) language.
L = {anbn | n>=0}.
• The example derivation
S → aSb → aaSbb → aabb.
Derivation
• Derivation is a sequence of replacements by using production
rules from the starting symbols to get a given string.
• There are two types:
a. E → (E) → ( E * E ) →( ( E ) * E ) → ( ( E + E ) * E ) → ( ( id + E )
* E ) → ( ( id + id ) * E ) → ( ( id + id ) * E / E ) → ( ( id + id ) * id /
E ) → ( ( id + id ) * id / id ). Leftmost Derivation
b. E → (E) → ( E / E ) → ( E / id ) → ( E * E / id )→ ( E * id / id ) →
( ( E ) * id / id ) → ( ( E + E ) * id / id ) → ( ( E + id ) * id / id ) →
( ( id + id ) * id / id ). Rightmost Derivation
Exercise
1. Show a left-most derivation for each of the following strings,
using the given grammar.
Expr → Expr + Expr | Expr Expr | ( Expr ) | var | const
(a) var + const (b) var11 + var var
Compiler Design-Woldia University by:- Michael W.
(c) (var) (d) ( var + var ) var
Solution:
Expr → Expr * Expr (b)
Expr → Expr + Expr → Expr + Expr * Expr
→ var + Expr → var + Expr * Expr
→ var + var → var + var * Expr
→ var + var * var
Parse Trees
A labeled tree which in the interior nodes are labeled by non-terminals
Bottom-Up Parsing
Start from leaves and work their way up to the root.
Input to parser scanned from left to right one symbol at a time.
bottom-up parsingmethodis called ― shift-reduce
(SR)‖ parsing.
An operator-precedence parser is one kind of
shift-reduce parser.
Also called as LR parsing: Compiler Design-Woldia
24
University by:- Michael W.
– L means that tokens are read left to right.
– R means that it constructs a rightmost derivation.
• Bottom-up parsing, however, can handle a larger class of
grammars and translation schemes, so software tools
for generating parsers directly from grammars often use
bottom-up methods.
Example
SR Parsing: Example
• Example: Consider the following grammar :
1. E -> E + E, 2. E -> E * E 3. E -> ( E ), 4. E -> id,
and the input string id1 + id2 + id3. The following sequence
of reductions reduces id1 + id2 + id3 to the start symbol E: