Compiler Construction Unit 3 Part-4 LR Parser Predictive Parsing CSE
Compiler Construction Unit 3 Part-4 LR Parser Predictive Parsing CSE
Compiler Construction
Unit 3 Part-4 LR Parser
Predictive parsing
CSE
By Himanshu Swarnkar
Engineering College Banswara
Parser
Brute force
Method Recursive Descent Non Recursive LR(0) SLR(1) LNR(1) CLR(1)
Descent(LL(1))
Bottom Up Parse Tree S
Bottom Up Parsing
Bottom up parsing stars with the input string and tries to construct the parse tree
up to the start symbol
Means Starts from the terminals and ends on the start Symbol
A B
Note: Bottom Up parser follows Reverse right most derivation and if focus on
what to reduce. Right Most Derivation
Example Given Grammar G(VTPS), S→aABe
Production are S→aABe →aAde A
A →Abc/b →aAbcde
B →d →abbcde
String w= abbcde a b b c d e
Shift-Reduce Parsing
Shift-reduce parsing uses two unique steps for bottom-up parsing.
These steps are known as shift-step and reduce-step.
Shift step:
The shift step refers to the advancement of the input pointer to the next input symbol, which is called the shifted symbol.
This symbol is pushed onto the stack.
The shifted symbol is treated as a single node of the parse tree.
Reduce step :
When the parser finds a complete grammar rule (RHS) and replaces it to (LHS), it is known as reduce-step.
This occurs when the top of the stack contains a handle.
To reduce, a POP function is performed on the stack which pops off the handle and replaces it with LHS non-terminal symbol.
LR Parser
A general shift reduce parsing is LR parsing. The L stands for scanning the input from left to right and R stands for constructing
a rightmost derivation in reverse.
Benefits of LR parsing:
Many programming languages using some variations of an LR parser. It should be noted that C++ and Perl are exceptions to it.
LR Parser can be implemented very efficiently.
LR Parsers detect syntactic errors, as soon as possible.
LR Parser
(Scanning from L to R, Reverse of Right most derivation)
A → aA.
Note: Apply first Goto than closure
Final Item: Dot at the end of RHS
I5 r1 r1 r1
I6 r2 r2 r2
S’ → S Action
S Goto
S → AA P1 (for Terminals) (for Variables)
A → aA P2
A A → b P3 a b $ A S
Input string: aabb I0 S3 S4 I2 I1
I1 Accept
A
I2 S3 S4 I5
A A I3 S3 S4 I6
Accept
I4 r3 r3 r3
Note: In reduce we
actually reduce the aabb$ I5 r1 r1 r1
previous symbol
I6 r2 r2 r2
Apply the reduce: See the number of symbol of RHS and reduce twice of it and push LHS in TOP of stack