Search code examples
pythonparsingyaccbnfply

Does ply's YACC support the Extended Backus-Naur Form?


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?


Solution

  • 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).