Treetop: getting the offset of a node
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 bui开发者_StackOverflowlt-in way of doing this.
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
精彩评论