Getting original value of a node from the parse tree?

Hello, so I have a string like Foo Bar; being given to the parser and built a parse tree off of. Where Foo and Bar are tokens defined in the grammar. While the semi-colon is defined as SMC in the grammar,

SMC { ";" }

is the definition in the grammar. Now, when traversing the parse tree, I do get Foo and Bar as intended. But, I also want to print SMC from the parse tree as an actual semi-colon, not as SMC (which is what I get when I print the node name/value). I’m not sure how I can go about that. What would be a good way to do that?

You can either add more logic to your print function, add an SMC[@name=";"] name prop to the grammar rule, or, if that’s what you need, read the range covered by the node from your document and print that.

1 Like

The @name approach worked. Thanks a lot! : )

A quick follow-up question, for printing Identifiers as their original values (from the tree), I’m using the reading-the-range approach and slicing the document according to ranges. Is that a good way to go?

Yes – the tree doesn’t store content strings. If you need to do this for lots of nodes, it may be more efficient to create a cursor into the document and advance that as you iterate the tree, but for most cases that is probably overkill.

2 Likes