antlr4 - 如何在声明ANTLR中获取变量的类型
问题描述
我正在使用 ANTLR 开发 DSL,在赋值规则中我想知道这里的变量类型是我的语法。
assign: name = ID '=' value = ( INT |STRING | DATE )
{
// get type here
parameters.add(new java.util.AbstractMap.SimpleImmutableEntry($name.text, $value.text));
};
解决方案
I suggest to not litter your grammar with code, but rather do this inside a listener:
@Override
public void enterAssign(StudyParserParser.AssignContext ctx) {
String id = ctx.name.getText();
String value = ctx.value.getText();
switch (ctx.value.getType()) {
case StudyParserLexer.INT:
System.out.println(id + " is an INT: " + value);
break;
case StudyParserLexer.STRING:
System.out.println(id + " is a STRING: " + value);
break;
case StudyParserLexer.DATE:
System.out.println(id + " is a DATE: " + value);
break;
default:
throw new RuntimeException("Unknown type: " + ctx.value.getType() + ", value: " + value);
}
}
推荐阅读
- php - 使用 die() 返回数组?
- javascript - 如何重构和映射数组以适应 React 中的指定数据结构
- python - 生成一个随机样本,其中第 i 个分量的方差为 1/i
- mysql - MySQL 中的子查询
- javascript - 在反应和打字稿中使用相同的功能验证 ssn 编号、参考编号、名字、姓氏
- python - 在 meta 中设置 https 代理的正确方法是什么?
- javascript - 如何使用模板元素在 HTML 中显示对象数组
- javascript - 尝试添加时出错
React 组件的包装器:(类型“{ children: Element;}”中缺少属性“onDragEnd”) - amazon-web-services - 使用 AWS IoT 管理多个客户
- go - 在 golang 中启用 Cors 策略