The HWK2 grammar for Bash is similar to the following grammar
for expressions involving variables, the operators + and * and
parentheses. (Noet that * has higher precedence than +.)
= VARIABLE / ()
= / *
= / +
An operator precedence parser for this grammar could be written
as three functions each returning either a parse tree or ERROR.
At the top level, the parser calls expression() and returns
its value, or ERROR if any tokens remain.
factor():
if the next token is of type VARIABLE
consume the next token and let V be its name
return a one-node tree of type VARIABLE containing V
else if the next token is a "("
consume the next token and set E = expression()
if E == ERROR or the next token is not a ")"
return ERROR
else
consume the next token and return E
else
return ERROR
term():
T = factor()
while T != ERROR and the next token is a "*"
consume the next token
F = factor()
if F == ERROR
return ERROR
else
T = tree of type "*" with left child T and right child F
return T
expression():
E = term()
while E != ERROR and the next token is a "+"
consume the next token
T = term()
if T == ERROR
return ERROR
else
E = tree of type "+" with left child E and right child T
return E