-
Notifications
You must be signed in to change notification settings - Fork 66
Using the Parse Tree
Pegged parse trees are described here: Parse Trees.
As you could see, there are a deliberately simple structure. There are not multiple types to encode AST nodes and whatnots. Since D has wonderful compile-time evaluation capabilities and code can be mixed-in, Pegged has all the power it needs:
Since parse trees are structs, they are easy to use at compile-time (classes are a bit trickier for now, so I chose structs): you can iterate on them, search for specific nodes, delete nodes or simplify them, etc.
See Semantic Actions, User-Defined Parsers and Compile-Time Parsing for more on this.
An Output
contains a ParseTree
member called parseTree
. Since Output
uses alias this
, the parse tree is directly accessible:
auto p = Expr.parse(input);
writeln(p.capture); // really p.parseTree.capture
foreach(ref child; p.children) // in truth, we are iterating on p.parseTree.children
doSomething(child);
Since parse trees are run-of-the-mill N-ary trees, I didn't add tree-walking algorithms in Pegged, but I may do so to group useful tree functions with the related structure:
- searching for all nodes with a particular name
- getting the leaves (parse trees with no children)
- filtering a tree: cutting the nodes that do not obey a particular predicate.
- modifying a tree.
I'll see. You can find tree-related algorithms in another Github project of mine: https://github.com/PhilippeSigaud/dranges (see for example https://github.com/PhilippeSigaud/dranges/blob/master/treerange.d)