check previous/left token in lexer

2019-08-03 17:54发布

问题:

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

回答1:

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]*;


回答2:

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.



标签: antlr4