>>> p = parser2.Parser()
>>> p.traceme = True
>>> p.parse('5 + 4 * 2')
[+]
...5
...[*]
......4
......2
13
When this tree is evaluated, the apply method recursively evaluates subtrees and applies
root operators to their results. Here, is evaluated before +, since it’s lower in the tree.
The Factor method consumes the substring before returning a right subtree to Expr.
The next tree takes a different shape:
>>> p.parse('5 * 4 - 2')
[-]
...[*]
......5
......4
...2
18
In this example, is evaluated before -. The Factor method loops through a substring
of and / expressions before returning the resulting left subtree to Expr. The next
example is more complex, but follows the same rules:
>>> p.parse('1 + 3 * (2 * 3 + 4)')
[+]
...1
...[*]
......3
......[+]
.........[*]
............2
............3
.........4
31
Trees are made of nested class instances. From an OOP perspective, it’s another way
to use composition. Since tree nodes are just class instances, this tree could be created
and evaluated manually, too:
PlusNode( NumNode(1),
TimesNode( NumNode(3),
PlusNode( TimesNode(NumNode(2), NumNode(3)),
NumNode(4) ))).apply({})
But we might as well let the parser build it for us (Python is not that much like Lisp,
despite what you may have heard).
Custom Language Parsers| 1455