[antlr-interest] Getting line and column numbers from a CommonTreeNodeStream

Damien Cassou damien.cassou at gmail.com
Tue Jun 9 10:33:29 PDT 2009


Hi,

my compiler is made of two grammars: one combined grammar parses the
language and constructs a tree while the second pass verifies the
tree. I would like to print error messages when there are semantic
errors in the second pass. For example, referencing a variable that is
not defined should result in:

line 12:9 No defined variable 'foo'

However, there is no easy way to get line and column numbers from a
CommonTreeNodeStream.
What I did was to subclass CommonTreeNodeStream and override consume()
as follows:

@Override
public void consume() {
	sync(1);
	Tree tree = (Tree) remove();
	if (tree.getLine() > 0) {
		line = tree.getLine();
		charPositionInLine = tree.getCharPositionInLine();
	}
}

(overriden implementation is
public void consume() {sync(1); remove();}
)

With line and charPositionInLine two fields of my subclass.

What do you think of that solution? Is there something simpler to
print semantic errors during a tree grammar parsing?

-- 
Damien Cassou
http://damiencassou.seasidehosting.st

"Lambdas are relegated to relative obscurity until Java makes them
popular by not having them." James Iry


More information about the antlr-interest mailing list