-
Notifications
You must be signed in to change notification settings - Fork 66
Parse Result
Here is the parse tree resulting from the main page grammar:
The grammar is the same as pegged.examples.arithmetic
.
// writeln(Arithmetic("1 + 2 - (3*x-5)*6"));
Arithmetic [0, 17]["1", "+", "2", "-", "(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Term [0, 17]["1", "+", "2", "-", "(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Factor [0, 2]["1"]
| +-Arithmetic.Primary [0, 1]["1"]
| +-Arithmetic.Number [0, 1]["1"]
+-Arithmetic.Add [2, 6]["+", "2"]
| +-Arithmetic.Factor [4, 6]["2"]
| +-Arithmetic.Primary [4, 5]["2"]
| +-Arithmetic.Number [4, 5]["2"]
+-Arithmetic.Sub [6, 17]["-", "(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Factor [8, 17]["(", "3", "*", "x", "-", "5", ")", "*", "6"]
+-Arithmetic.Primary [8, 15]["(", "3", "*", "x", "-", "5", ")"]
| +-Arithmetic.Parens [8, 15]["(", "3", "*", "x", "-", "5", ")"]
| +-Arithmetic.Term [9, 14]["3", "*", "x", "-", "5"]
| +-Arithmetic.Factor [9, 12]["3", "*", "x"]
| | +-Arithmetic.Primary [9, 10]["3"]
| | | +-Arithmetic.Number [9, 10]["3"]
| | +-Arithmetic.Mul [10, 12]["*", "x"]
| | +-Arithmetic.Primary [11, 12]["x"]
| | +-Arithmetic.Variable [11, 12]["x"]
| +-Arithmetic.Sub [12, 14]["-", "5"]
| +-Arithmetic.Factor [13, 14]["5"]
| +-Arithmetic.Primary [13, 14]["5"]
| +-Arithmetic.Number [13, 14]["5"]
+-Arithmetic.Mul [15, 17]["*", "6"]
+-Arithmetic.Primary [16, 17]["6"]
+-Arithmetic.Number [16, 17]["6"]
As you can see, even with a simple grammar, a parse tree can become a big beast quite rapidly. See Extended PEG Syntax to learn how to tell Pegged to drop branches from the tree.
In addition to dumping a parse tree to a string as shown above, you can generate an HTML file containing an expandable tree view. This makes inspecting large parse trees a lot easier. For example:
toHTML(Arithmetic("1 + 2 - (3*x-5)*6"), "output");
will generate the file output.html
in your working directory. Make sure to open it in a browser that supports the HTML5 details
tag.
By default the details are always collapsed. To expand them fully use the Expand.ifMatch
value as template parameter:
import pegged.tohtml;
ParseTree tree = Arithmetic("1 + 2 - (3*x-5)*6");
toHTML!(Expand.ifMatch)(tree, "output.html");
To expand only certain details, specify sub strings that are contained in the name of the matching rules:
import pegged.tohtml;
ParseTree tree = Arithmetic("1 + 2 - (3*x-5)*6");
toHTML!(Expand.ifMatch, ".Primary", ".Term")(tree, "output.html");
To expand everything but certain details, use the Expand.ifNotMatch
value instead
import pegged.tohtml;
ParseTree tree = Arithmetic("1 + 2 - (3*x-5)*6");
toHTML!(Expand.ifNotMatch, ".Number")(tree, "output.html");
Any failed rules are indicated in red, and the complete section of the input that is matched by a rule shows on mouse-over. To see an example of this, have a look at pegged/examples/extended_pascal/example.html.