Re: Noob parser question



On Feb 28, 12:05 am, imissfloppydi...@xxxxxxxxx wrote:
This is a CFG listed in the Aho (dragon) compiler text:

expr -> expr + term | expr - term | term
term -> term * factor | term / factor | factor
factor -> digit | (expr)
digit -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

It is intended to parse simple arithmetic expressions taking into
account the precedence of operators. What I don't understand is why
you parse the operators with lower precedence first. I have worked
through several examples by hand and it works but I don't understand
why it works. Perhaps I should be content with that but I am a
perfectionist.

Here's rough intuition.

Think about the parse tree you want to finish with when parsing, say a
* b + c * d. The expr should have a + node at the top of the tree,
with equal or higher precedence operations (in this case *) or else
terminals as the operands. To get the + at the top, it must be in the
production for expr itself. The higher precedence operators are
"lower" in the grammar.

.



Relevant Pages

  • misc: my effort, and a new ambiguity...
    ... today I actually got around to writing most of the new parser. ... the final x in 'tx;' would need to change the relative precedence ... ordering after parsing 't' in order to parse as expected. ...
    (comp.lang.misc)
  • Re: Coding standards
    ... there's only one possible way to parse it ... They don't have separate precedence and associativity, ...
    (comp.lang.c)
  • Re: Coding standards
    ... >> additive which has precedence over logical will do. ... Yes, I know there are no precedence levels in C, ... > all fine apart from the ternary operator, as far as I could determine ... there's only one possible way to parse it ...
    (comp.lang.c)
  • Re: [QUIZ] Dice Roller (#61)
    ... > I would appreciate the full BNF, ... precedence and associativity. ... expr: fact ... term rules and handling of the optional arg). ...
    (comp.lang.ruby)
  • Re: Dangling else
    ... assignment-expression. ... by "aren't expressible as precedence". ... how to resolve a shift/reduce conflict. ... expr: - expr ...
    (comp.compilers)