Adding line Nubers to Listener

19 views
Skip to first unread message

Bill Dickenson

unread,
Mar 20, 2019, 10:14:06 AM3/20/19
to antlr-discussion
I have read the documentation on how to add the scope to the listener and I am wondering if I can do the same thing for line number. I am working on a project that requires traceability back to the line number, not just the artifact !

Has anyone done this and would be willing to share.

Thanks

David Whitten

unread,
Mar 20, 2019, 11:51:58 AM3/20/19
to antlr-di...@googlegroups.com
Doesn't ANTLR already have a way to access the line number and the column number ?
Maybe its in the lexer ?

Thanks,
Dave Whitten

--
You received this message because you are subscribed to the Google Groups "antlr-discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to antlr-discussi...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Norman Dunbar

unread,
Mar 21, 2019, 3:37:44 AM3/21/19
to antlr-di...@googlegroups.com
Hi Bill,

I might have misunderstood your question, but the following is what I
did in an old app of mine - but it works to give me the line numbers and
column numbers for the input file correctly.

It might not be the best or most efficient way, but, from an old posting
of mine on this list ...


I've done this in my utility to parse an Oracle tnsnames.ora file. The
source is on GitHub here
https://github.com/NormanDunbar/Tnsnames_checker the relevant part being:

//----------------------------------------------------------------
// EVERY RULE
//----------------------------------------------------------------
// As we enter every rule, extract the line and column positions.
// Use them to build a location string for the start of this rule.
//----------------------------------------------------------------
@Override
public void enterEveryRule(ParserRuleContext ctx)
{
Token startToken = ctx.getStart();
if (startToken != null)
{
// Lines number from 1.
this.lineNumber = startToken.getLine();

// Characters from zero. Adjust.
this.charPosition = 1 + startToken.getCharPositionInLine();
}
else
{
// Just in case Token can ever be null.
this.lineNumber = 0;
this.charPosition = 0;
}

// Build a location string for error messages etc.
this.whereAmI = "\tLine " + lineNumber + ":" + charPosition + " ";
}

Apologies for the Java - I'm not a Java developer! Formatting might also
have been "amended" by the posting process.

Lines count from 1 but characters on the line count from 0 with ANTLR
(or is it Java?)

HTH

Disclaimer: I'm not a compiler writer, nor do I play one on TV.


Cheers,
Norm.
Reply all
Reply to author
Forward
0 new messages