Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting token start character position relative to the beginning of file

Tags:

token

antlr4

Is there any reliable way with antlr4 API to get Token start character position relative to the beginning of file, not line? After doing some research the only way I found is to use some custom implementation of IntStream, that does not treat '\n' as line terminators, but perhaps I'm missing some easier way? I'm using Visitor API if it matters.

The application I'm working on parses source files and provides insertion coordinates for another application that uses provided coordinates to insert additional code. It would be much more convenient if that another application got symbol position in file, rather than line:positionInLine pair.

like image 725
user2592325 Avatar asked Jul 17 '13 17:07

user2592325


1 Answers

You can use any of the following, depending on whether you have a Token or a TerminalNode.

  • Token.getStartIndex()
  • TerminalNode.getSourceInterval().a Edit: This will return the token index, not the character position.
  • TerminalNode.getSymbol().getStartIndex()
like image 185
Sam Harwell Avatar answered Nov 02 '22 07:11

Sam Harwell