check previous/left token in lexer
Asked Answered
T

2

2

how can I find the previous/left token in lexer
for example

lexer grammar TLexer;

ID     : [a-zA-Z] [a-zA-Z0-9]*;
CARET  : '^';
RTN    : {someCond1}? CARET ID; // CARET not include this token
GLB    : {someCond2}? CARET ID; // CARET not include this token

etc

Tafia answered 9/1, 2013 at 20:4 Comment(2)
What are you trying to do ? What input do you want to parse ? Why lexer only ? Which version of ANTLR ?Semitone
tag antlr4 and version antlr 4 for syntax highlightingTafia
T
5

thanks, I did it this way

lexer grammar TLexer;

@lexer::members {
    int lastTokenType = 0;
public void emit(Token token) {
    super.emit(token);
    lastTokenType = token.getType();
}
}

CARET  : '^';
RTN    : {someCond1&&(lastTokenType==CARET)}? ID;
GLB    : {someCond2&&(lastTokenType==CARET)}? ID;
ID     : [a-zA-Z] [a-zA-Z0-9]*;
Tafia answered 12/1, 2013 at 17:1 Comment(0)
S
0

I had a look at the Lexer source. The Lexer answers to nextToken() calls (from the parser). I haven't found that it keeps track of previous tokens. And there is no direct access to CARET. Given this input :

xyz ^abc

and this grammar :

lexer grammar TLexer;

ID     : [a-zA-Z] [a-zA-Z0-9]* {System.out.println("ID ");} ;
CARET  : '^'                   {System.out.println("CARET ");} ;
WS     : [ \r\n] ;
RTN    : CARET ID {System.out.println("RTN " + _tokenStartCharIndex);} ;

the output is :

$ antlr4 TLexer.g4 
$ javac TLexer.java 
$ grun TLexer tokens -tokens -diagnostics -trace input.txt 
ID 
RTN 4
[@0,0:2='xyz',<1>,1:0]
[@1,3:3=' ',<3>,1:3]
[@2,4:7='^abc',<4>,1:4]
[@3,8:8='\n',<3>,1:8]
[@4,9:8='<EOF>',<-1>,2:9]

The lexer gives you a single token of type <4> (RTN) for the input ^abc.

Semitone answered 11/1, 2013 at 10:10 Comment(2)
I know this, but I need another. i need CARET and RTN as two tokensTafia
@Semitone Link is dead, but the WaybackMachine has a copy, which looks a lot like this wiki page.Meneses

© 2022 - 2024 — McMap. All rights reserved.