Syntax analyzer� (Parser)�second phase of Compiler��Top-Down Parsing [ LL Parser ]�Bottom Up Parsing [ LR , SLR , LALR, CLR ]�
1
Syntax analyzer (Parsing)
COMPILER M.H.NAJI
2
Parsing
Top-down X Bottom-up
What to reduce
When to reduce
COMPILER M.H.NAJI
3
Parsing
Top–Down Parsing Bottom–Up Parsing
COMPILER M.H.NAJI
4
Parsing
Backtracking: Try different structures and backtrack if it does not matched the input
Predictive: Guess the structure of the parse tree from the next input
Parse Trees and Derivations
E ⇒ E + E
⇒ id + E
⇒ id + E * E
⇒ id + id * E
⇒ id + id * id
E ⇒ E + E
⇒ E + E * E
⇒ E + E * id
⇒ E + id * id
⇒ id + id * id
COMPILER M.H.NAJI
5
Parsing
Top-down parsing
Bottom-up parsing
id
E
*
E
id
id
+
E
E
E
E
E
E
E
+
*
id
id
id
E
Backus-Naur Form
COMPILER M.H.NAJI
6
Parsing
<expression> | ::= <term> { + <term> | - <term> } |
<term> | ::= <factor> { × <factor> } |
<factor> | ::= <constant> | ( <expression> ) |
<constant> | ::= <digit> { <digit> } |
<digit> | ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Recursive-Descent Parser
COMPILER M.H.NAJI
7
Parsing
لغرض بناء محلل اللغة Recursive Descent Parser نقوم بما يلي
Recursive-Descent Parser
Suppose the grammar is
COMPILER M.H.NAJI
8
Parsing
E( )
{ If ( L== ”d”)
{
match(“d”);
E’( );
}
}
E’( )
{ If ( L== ”+”)
{ match(“d”);
match(“+”);
E’( );
}
Else return
}
match(char c)
{ If ( L== c)
L=getchar()
Else
Print(“Error”)
}
main( )
{
E( );
If ( L== $)
Print(“Accepted”)
}
Recursive-Descent Parser
Suppose the grammar is
COMPILER M.H.NAJI
9
Parsing
main | E( ) | E’( ) | Match(c) |
| E🡪dE’ | | d |
| | E’🡪+dE’ | + |
| | E’🡪+ d | d |
| | E’🡪Ɛ | $ |
| | | d + d $ |
LL(1) Parsing
COMPILER M.H.NAJI
10
Parsing
Concept of LL(1) Parsing
COMPILER M.H.NAJI
11
Parsing
FIRST & FOLLOW
COMPILER M.H.NAJI
12
Parsing
FIRST is a function find all terminals that can appear at the beginning of each non-terminal (variable). Epsilon (neither a terminal nor a non-terminal) may also be included in this FIRST function
FOLLOW function shows us the terminals that can come after a derived non-terminal. The follow of non-terminal is the first of the next non-terminal
S -> aABb
A -> aAc | Ɛ
B -> bB | c
COMPILER M.H.NAJI
13
Parsing
EX: construct FIRST and FOLLOW function for the following grammar
S -> ABCDE
A -> a| Ɛ
B -> b| Ɛ
C -> c
D -> d| Ɛ
E -> e| Ɛ
| FIRST | FOLLOW |
S | { a, b , c } | { $ } |
A | { a , Ɛ } | { b , c } |
B | { b , Ɛ } | {c} |
C | { c } | {d,e,$} |
D | { d ,e, Ɛ } | {e , $} |
E | { e , Ɛ } | {$} |
Construct parsing LL table
COMPILER M.H.NAJI
14
Parsing
E -> E + T | T
T -> T * F | F
F -> (E) | id
Suppose the following grammar
Remove LR
A--- > Aα|β
A--- > βA'
A'---> αA'|Ɛ
نستخدم القانون
Left recursion grammar
E 🡪 T E‘
E' 🡪 + T E'| Ɛ
T 🡪 F T‘
T' 🡪 * F T'| Ɛ
F 🡪 (E) | id
grammar After remove recursion
COMPILER M.H.NAJI
15
Parsing
First & Follow
Construct LL table