简体   繁体   English

如何访问 ANTLR 词法分析器令牌

[英]How to access ANTLR lexer tokens

I have specified the following ANTLR grammar:我指定了以下 ANTLR 语法:

expression: ...
          | extractor=EXTRACTOR '(' setElementDefinition ',' expression ')' #setExtractorExp
          | ... ;

EXTRACTOR: 'select'
         | 'choose' ;

I would like to know which type of extraction I am dealing with when parsing this expression.我想知道在解析这个表达式时我正在处理哪种类型的提取。 One way of doing it is by comparing the extractor field with a string containing the extractor type, like this:一种方法是将提取器字段与包含提取器类型的字符串进行比较,如下所示:

@Override
public Expression visitSetExtractorExp(MyParser.SetExtractorExpContext ctx) {
    if(ctx.extractor.getText().equals("select")) { ... }
}

But I don't like to duplicate the names of the extractors here, in case I choose to change the names of the extractors later.但是我不喜欢在这里重复提取器的名称,以防我以后选择更改提取器的名称。 So is there a way to access the lexer tokens?那么有没有办法访问词法分析器令牌?

I am imagining something like if(ctx.extractor == MyLexer.EXTRACTOR.choose) .我在想象类似if(ctx.extractor == MyLexer.EXTRACTOR.choose)

Right now, your EXTRACTOR has just a single type, making "select" and "choose" pretty much the same.现在,您的EXTRACTOR只有一种类型,使"select""choose"几乎相同。 The only way to make a distinction is to to string comparison like you're already doing.区分的唯一方法是像您已经在做的那样进行字符串比较。 If you don't want that, do something like this:如果您不想要那样,请执行以下操作:

expression
 : ...
 | extractor '(' setElementDefinition ',' expression ')' #setExtractorExp
 | ... 
 ;

extractor
 : SELECT
 | CHOOSE
 ;

SELECT : 'select';
CHOOSE : 'choose';

and in your visitor:在您的访客中:

@Override
public Expression visitSetExtractorExp(MyParser.SetExtractorExpContext ctx) {
  if(ctx.extractor().start.getType() == MyLexer.SELECT) { ... }
  else if(ctx.extractor().start.getType() == MyLexer.CHOOSE) { ... }
}

That way you don't have to duplicate (magic) strings.这样您就不必复制(魔术)字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM