英文:
How to access ANTLR lexer tokens
问题
我已经指定了以下的ANTLR语法:
expression: ...
| extractor=EXTRACTOR '(' setElementDefinition ',' expression ')' #setExtractorExp
| ... ;
EXTRACTOR: 'select'
| 'choose' ;
我想知道在解析这个表达式时我正在处理哪种类型的提取。一种方法是将提取器字段与包含提取器类型的字符串进行比较,就像这样:
@Override
public Expression visitSetExtractorExp(MyParser.SetExtractorExpContext ctx) {
if(ctx.extractor.getText().equals("select")) { ... }
}
但我不想在这里重复提取器的名称,以防以后选择更改提取器的名称。所以有没有一种方法可以访问词法分析器的标记?
我想象中的写法类似于 if(ctx.extractor == MyLexer.EXTRACTOR.choose)
。
英文:
I have specified the following ANTLR grammar:
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)
.
答案1
得分: 2
目前,您的 EXTRACTOR
只有一种类型,使得 "select"
和 "choose"
几乎是相同的。唯一区分它们的方式是像您已经在做的那样进行字符串比较。如果您不想这样做,可以像这样进行处理:
expression
: ...
| extractor '(' setElementDefinition ',' expression ')' #setExtractorExp
| ...
;
extractor
: SELECT
| CHOOSE
;
SELECT : 'select';
CHOOSE : 'choose';
并在您的访问者中:
@Override
public Expression visitSetExtractorExp(MyParser.SetExtractorExpContext ctx) {
if(ctx.extractor().start.getType() == MyLexer.SELECT) { ... }
else if(ctx.extractor().start.getType() == MyLexer.CHOOSE) { ... }
}
这样您就不需要复制(魔术)字符串。
英文:
Right now, your EXTRACTOR
has just a single type, making "select"
and "choose"
pretty much the same. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论