Search code examples
pythontreeabstract-syntax-treeply

How can I get a constructed tree in ply using the documentation example?


In the documentation they show this example to build a tree:

 def p_expression_binop(p):
     '''expression : expression PLUS expression
                   | expression MINUS expression
                   | expression TIMES expression
                   | expression DIVIDE expression'''

     p[0] = ('binary-expression',p[2],p[1],p[3])

 def p_expression_group(p):
     'expression : LPAREN expression RPAREN'
     p[0] = ('group-expression',p[2])

 def p_expression_number(p):
     'expression : NUMBER'
     p[0] = ('number-expression',p[1])

But my question is, once the tree is created, where does those nodes goes? or how do I access them from p[0]?


Solution

  • As long as you make sure that the node is passed through all the way to the top (that is, the action for the start symbol), you just use the return value of the call to parse.

    From the documentation:

    Whenever the starting rule is reduced by the parser and no more input is available, parsing stops and the final value is returned (this value will be whatever the top-most rule placed in p[0]).