Manual:Results:Trees

まんま

>>> from lepl import *
>>> class Term(Node): pass
...
>>> class Factor(Node): pass
...
>>> class Expression(Node): pass
...
>>> expr   = Delayed()
>>> number = Digit()[1:,...]                        > 'number'
>>> with Separator(r'\s*'):
...     term    = number | '(' & expr & ')'         > Term
...     muldiv  = Any('*/')                         > 'operator'
...     factor  = term & (muldiv & term)[:]         > Factor
...     addsub  = Any('+-')                         > 'operator'
...     expr   += factor & (addsub & factor)[:]     > Expression
...     line    = expr & Eos()
...
>>> ast = line.parse_string('1 + 2 * (3 + 4 - 5)')[0]
>>> ast
Expression(...)
>>> print(ast)
Expression
 +- Factor
 |   +- Term
 |   |   `- number '1'
 |   `- ' '
 +- ''
 +- operator '+'
 +- ' '
 `- Factor
     +- Term
     |   `- number '2'
     +- ' '
     +- operator '*'
     +- ' '
     `- Term
         +- '('
         +- ''
         +- Expression
         |   +- Factor
         |   |   +- Term
         |   |   |   `- number '3'
         |   |   `- ' '
         |   +- ''
         |   +- operator '+'
         |   +- ' '
         |   +- Factor
         |   |   +- Term
         |   |   |   `- number '4'
         |   |   `- ' '
         |   +- ''
         |   +- operator '-'
         |   +- ' '
         |   `- Factor
         |       +- Term
         |       |   `- number '5'
         |       `- ''
         +- ''
         `- ')'
>>> [child for child in ast]
[Factor(...), '', '+', ' ', Factor(...)]
>>> print([child for child in ast])
[Factor(...), '', '+', ' ', Factor(...)]
>>> [ast[i] for i in range(len(ast))]
[Factor(...), '', '+', ' ', Factor(...)]
>>> [(name, getattr(ast, name)) for name in dir(ast)]
[('Factor', [Factor(...), Factor(...)]), ('operator', ['+'])]
>>> ast.Factor[1].Term[0].number[0]
'2'