java - Antlr4 - 获取令牌名称
问题描述
我有以下(简化的)语法:
grammar Test;
IDENTIFIER: [a-z]+ [a-zA-Z0-9]*;
WS: [ \t\n] -> skip;
compilationUnit:
field* EOF;
field:
type IDENTIFIER;
type:
(builtinType|complexType) ('[' ']')*;
builtinType:
'bool' | 'u8';
complexType:
IDENTIFIER;
和以下程序:
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
public class Main{
public static void main(String[] args){
TestLexer tl=new TestLexer(CharStreams.fromString("u8 foo bool bar complex baz complex[][] baz2"));
TestParser tp=new TestParser(new CommonTokenStream(tl));
TestParser.CompilationUnitContext cuc=tp.compilationUnit();
System.out.println("CompilationUnit:"+cuc);
for(var field:cuc.field()){
System.out.println("Field: "+field);
System.out.println("Field.type: "+ field.type());
System.out.println("Field.type.builtinType: "+field.type().builtinType());
System.out.println("Field.type.complexType: "+field.type().complexType());
if(field.type().complexType()!=null)
System.out.println("Field.type.complexType.IDENTIFIER: "+field.type().complexType().IDENTIFIER());
}
}
}
为了区分complexType
and builtinType
,我可以看一下,它不是空的。但是,如果我想区分bool
and u8
,我该怎么做呢?
这个问题会回答我的问题,但它是针对 Antlr3 的。
解决方案
要么使用替代标签:
builtinType
: 'bool' #builtinTypeBool
| 'u8' #builtinTypeU8
;
和/或在词法分析器中定义这些标记:
builtinType
: BOOL
| U8
;
BOOL : 'bool';
U8 : 'u8';
这样您就可以更轻松地在访问者/侦听器中检查令牌的类型:
YourParser.BuiltinTypeContext ctx = ...
if (ctx.start.getType() == YourLexer.BOOL) {
// it's a BOOL token
}
推荐阅读
- .htaccess - Mod 重写规则以重写整个站点的 URL 参数
- javascript - Chart.js 折线图未显示在 Google Chrome 画布中(仅在 Microsoft Edge 中)
- mips - MIPS 从 EX/MEM 转发到分支依赖的 IF/ID
- android - android ViewModelProverders.of 似乎没有
- python - Python 系列重复值
- r - 固定效应回归无法将汉字识别为个体固定效应
- python - 没有模块名称'kivy'
- python - 启动 Django 项目并使用批处理文件打开 Visual Studio Code
- r - R 错误:我在尝试使用带有 if 语句的 for 循环时收到此错误消息(在 R 中),缺少需要 TRUE/FALSE 的值
- python-3.x - 当使用 PushButton、LineEdit 和 .