0

The examples I've seen always use the "simple" BNF. Here's an example of a part of my silly development:

def p_expression(p):
    """expression : NUMBER
                | NAME
                | NEGATION
                | INCREMENT
                | DECREMENT
                | expression operator expression"""

if __name__ == "__main__":
    lex.lex()
    yacc.yacc()
    data = "32 <+> 10 |"
    result = yacc.parse(data)

What if I want to parse a math expression with parenthesis and the whole recursive hell of it just like in this answer that uses the extended one? Is it possible?

Community
  • 1
  • 1
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • See my SO answer on how to build a recursive descent parser given a BNF: http://stackoverflow.com/questions/2245962/is-there-an-alternative-for-flex-bison-that-is-usable-on-8-bit-embedded-systems/2336769#2336769 – Ira Baxter Aug 06 '16 at 08:17

1 Answers1

1

No, PLY (like yacc) does not support extended BNF.

The page you refer to provides a strategy for constructing top-down parsers, while the parsers built by yacc (as well as Bison, PLY and other derivatives) build bottom-up parsers. The advantage of a bottom-up parser is that the grammar used to parse bears a closer correspondence to the actual grammatical structure of the language, and thus can be used directly to build an AST (abstract syntax tree).

Arithmetic expression grammars in BNF are generally quite simple (although not quite as simple as the ambiguous grammar in your question), particularly if you use the operator precedence declarations provided by yacc (and PLY).

rici
  • 234,347
  • 28
  • 237
  • 341
  • I'm considering cheating, defining a "p_python_expression" and using eval(). In that way, any expression from Python would work. I'm quite the beginner in "compilers", so that's why I chose Python AND lex + yacc in the first place. – Ericson Willians Aug 03 '16 at 19:28
  • @EricsonWillians: You'll learn more if you actually build an AST. It's not difficult and there are lots of examples to guide you. None of that stops you from concatenating the string representation back together and calling eval, but walking an AST to evaluate is really easy, too, maybe even easier. – rici Aug 03 '16 at 19:30