简体   繁体   English

Antlr4 - 获取令牌名称

[英]Antlr4 - Get token name

I have following (reduced) grammar:我有以下(简化的)语法:

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;

And following program:和以下程序:

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

To differentiate complexType and builtinType , I can look, which is not-null.为了区分complexTypebuiltinType ,我可以看一下,它不是空的。 But, if I want to distinguish between bool and u8 , how can I do that?但是,如果我想区分boolu8 ,我该怎么做呢? This question would answer my question, but it is for Antlr3.这个问题会回答我的问题,但它是针对 Antlr3 的。

Either use alternative labels :要么使用替代标签

builtinType
 : 'bool' #builtinTypeBool
 | 'u8'   #builtinTypeU8
 ;

and/or define these tokens in the lexer:和/或在词法分析器中定义这些标记:

builtinType
 : BOOL
 | U8
 ;

BOOL : 'bool';
U8   : 'u8';

so that you can more easily inspect the token's type in a visitor/listener:这样您就可以更轻松地在访问者/侦听器中检查令牌的类型:

YourParser.BuiltinTypeContext ctx = ...
        
if (ctx.start.getType() == YourLexer.BOOL) {
  // it's a BOOL token
}

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

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