Reputation: 134
Ok, I thought there would be enough CS majors on here to check my pseudo code for my recursive descent parser. I developed it from this BNF
EXP ::= EXP + TERM | EXP - TERM | TERM
TERM ::= TERM * FACTOR | TERM/FACTOR | FACTOR
FACTOR ::= (EXP) | DIGIT
DIGIT ::= 0|1|2|3
Here's the pseudo code:
procedure exp()
term()
if token == ‘+’
match(‘+’)
term()
elseif token == ‘-‘
match(‘-‘)
term()
else
break
procedure term()
factor()
if token == ‘*’
match(‘*’)
factor()
elseif token == ‘/’
match(‘/’)
factor()
else
break
procedure factor()
if token == ‘(‘
match(‘(‘)
exp()
match(‘)’)
else
digit()
procedure digit()
if token == ‘0’
match(‘0’)
elseif token == ‘1’
match(‘1’)
elseif token == ‘2’
match(‘2’)
else
match(‘3’)
match(t)
if token == t
advancetokenpointer
else
error
Is this correct? I was thinking I may need to have a return in each procedure, and I'm not sure of my procedure correctness either. Maybe include end procedure too? Anyways, thanks a lot! :-)
Upvotes: 3
Views: 3390
Reputation: 759
You are half way there. Especifically, you are not accounting for the left-recursive parts of the grammar, as in "EXP ::= EXP...", or "TERM ::= TERM...".
Recursive descent is not well suited for left-recursion anyway, but fortunatelly there are standard transformations you can perform in the grammar that will eliminate this kind of left recursion. As an example, the following grammar:
A ::= A x B | B
could be coded like this:
procedure A()
B()
repeat
if token == 'x'
match('x')
B()
else
break
Moreover, the code for factor is not following the grammar correctly. Notice that in the first alternative, EXP is called recursivelly (this is a kind of recursion that Recursive Descent has no problem with) and you are calling factor instead. Also, you are matching the right parenthesis as if it was optional, while it is actually required. This same problem exists in the code for DIGIT. If neither 0, 1 or 2 match, 3 must match.
Upvotes: 1