Compiler - Top Downcompiler
Compiler - Top Downcompiler
Grammar:
S -> aB
B -> b
Input String:
ab
1. Procedure S():
2. Procedure B():
Parsing Process:
o Consume 'a'.
o Call B().
2. B() is called:
o Consume 'b'.
|\
a B
The Grammar:
S -> ab | ac
o This grammar says that the symbol 'S' can be replaced by either the
sequence 'ab' OR the sequence 'ac'. This "OR" is the key to needing
backtracking.
The Input:
ac
o We want to see if this input string can be derived from the starting
symbol 'S' according to our grammar.
o It looks at the first symbol in the input, which is 'a'. This matches the
'a' in 'ab', so that's good.
o However, the next input symbol is 'c'. This doesn't match 'b', so the
parser has hit a dead end.
o It looks at the first input symbol, which is 'a'. This matches the 'a' in
'ac', so that's good.
o It looks at the next input symbol, which is 'c'. This matches the 'c' in
'ac', so that's also good.
Why Backtracking?
It had to try one option, see if it worked, and if not, try another.
Left recursion:
Left recursion occurs when a non-terminal symbol (a symbol representing a
grammar rule) can derive a string that begins with itself. Think of it as a circular
dependency in the grammar rules.
o Example: A -> Aa | b
o Example:
A -> Bc
B -> Ad
Solution:
o Rewrite it as:
A -> bA'
Explanation:
o We make A start with the part that doesn't cause recursion (b).
Problem: A chain of rules causes recursion (e.g., A -> Bc, B -> Ad).
Solution:
o Substitute:
o Eliminate direct left recursion: Now, if you have direct left recursion,
use the method from step 1.
Explanation:
A top-down parser gets confused! It sees "apple" and doesn't know which rule to
pick.
Rewrite it as:
Now, the parser sees "apple", knows to go to A', and then decides between "pie" or
"cake".
It removes ambiguity for top-down parsers when multiple rules start the
same way.
o S -> aB
o B -> b
o Input:
o "ab"
How it Works :
o The parser checks the input; the first symbol is indeed "a".
o So, the parser "consumes" the "a" (moves on to the next input
symbol).
o Move to "B":
o Success:
Since the parser successfully matched all the rules of the grammar with
the input string, the parse is successful.