首页 > 解决方案 > 如何在声明ANTLR中获取变量的类型

问题描述

我正在使用 ANTLR 开发 DSL,在赋值规则中我想知道这里的变量类型是我的语法。

assign: name = ID '=' value = ( INT  |STRING | DATE )
            {
                // get type here
                parameters.add(new java.util.AbstractMap.SimpleImmutableEntry($name.text, $value.text));
            };

标签: antlr4

解决方案


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);
    }
}

推荐阅读