Ok, here's a basic pseudocode example, with a simple grammer which contains the following tokens: +, -, *, /, IDENTIFIER, (, )
Where * and / are at the same precedence level.
Where + and - are at the same precedence level.
And (*, /) are higher precedence than (+, -)
code:<HR>
Code:
def parse():
return parse_addsub()
def parse_addsub():
expr = parse_muldiv()
while not done:
tok = next_token()
if tok is EOF:
done = true
elif tok is + or -:
expr2 = parse_muldiv()
expr = new Node(tok, expr, expr2)
else:
push_back(tok)
done = true
return expr
def parse_muldiv():
expr = parse_atom()
while not done:
tok = next_token()
if tok is EOF:
done = true
elif tok is * or /:
expr2 = parse_atom()
expr = new Node(tok, expr, expr2)
else:
push_back(tok)
done = true
return expr
def parse_atom():
tok = next_token()
if tok is IDENTIFIER:
return new Node(IDENTIFIER, tok)
elif tok is (:
expr = parse_addsub()
tok = next_token()
if tok is not ):
ERROR
else:
return expr
else:
ERROR
next_token() returns the next token
push_back() pushes a token back onto the token stream, so the next time you call next_token() the token you pushed back will be read.
Anyway, the idea with this example is this, given an expression 'expr', you assume that it is an addition/subtraction expression, with 0 or more additions/subtractions.
addsubexpr = muldivexpr1 (+,-) muldivexpr2 (+,-) .... (+,-) muldivexprN
and you split up each muldivexpr into:
muldivexprI = atomexpr1 (*,/) atomexpr2 (*,/) ... (*,/) atomexprN
and each atomexpr can be:
atomexprI = ( addsubexpr ) OR identifier
That's the general idea. You'll have to modify it for your grammar. Good luck.
Edit:
Cobalt, that's exactly what I was thinking.
-EB