Question

I'm using Treetop to generate a parser for a small programming language.

Upon successful parsing, I'd like to do some semantic analysis on the syntax tree. Ideally, whenever I encounter a piece of (semantically) invalid code, I would like to print out an error message that includes the line where the error occurred. I know this is possible because if I do

parser = MyParser.new
tree = parser.parse("foobar")
p tree

I get something like

SyntaxNode offset=0, "foobar":
    SyntaxNode offset=0, "f"
    SyntaxNode offset=1, "o"
    SyntaxNode offset=2, "o"
    SyntaxNode offset=3, "b"
    SyntaxNode offset=4, "a"
    SyntaxNode offset=5, "r"

Essentially, I'd like a way to access the offset attribute of a given SyntaxNode object (or subclass thereof). Unfortunately, according to http://treetop.rubyforge.org/semantic_interpretation.html the only methods available on Treetop::Runtime::SyntaxNode are terminal?, nonterminal?, text_value and elements, so there doesn't seem to be a built-in way of doing this.

Was it helpful?

Solution

Each SyntaxNode has an "interval" method which is a Ruby Range object. Offset is interval.start.

Treetop's support mailing list is at http://groups.google.com/group/treetop-dev

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top