ANTLR解析器节点类型+ Tree Adopter?

时间:2016-01-28 13:03:29

标签: java antlr antlr3

我开发了小型ANTLR语法。其中包含三个文件。

  • GLexer.g:lexer
  • GParser.g:tpye AST的解析器
  • GWalker.g:树解析器

此外,我还有自定义树节点GTree(扩展CommonTree)和tree adopterGAdaptor(扩展了CommonTreeAdaptor)。请参阅下面的示例代码

lexer:GLexer.g

lexer grammar GLexer;
..
some lexer rule
..

** Parser GParser.g **

parser grammar GParser;
options {
    output          = AST;
    tokenVocab      = GLexer;
}
statement 
  : 
     rule* 
       -> ^(STATEMENTS rules* )
  ;

Tree Grammar:GWalker.g

tree grammar GWalker;
options {
  tokenVocab      = GParser;
  ASTLabelType    = GTree;
}
statement returns [String node]
  : 
     ^(STATEMENTS rules* )
  ;

树节点

public class GTree extends CommonTree {
    public String text;
    public HashMap<String, Object> params = new HashMap<String, Object>();
    public GTree(Token t) {
        super(t);
        text = (t != null ? t.getText() : "[]");
    }
}

Tree Adopter

public class GTreeAdaptor extends CommonTreeAdaptor {
    public GTree create(Token payload) {
        GTree c = new GTree(payload);
        return c;
    }
}

ANTLR处理程序

try {
    //lexer splits input into tokens
    ANTLRStringStream input = new ANTLRStringStream("input String");
    TokenStream tokens = new CommonTokenStream( new GLexer( input ) );

    //parser generates abstract syntax tree
    GParser parser = new GParser(tokens);
    // Initiate Custom Adopter and set in parser
    TreeAdaptor adaptor = new GTreeAdaptor();
    parser.setTreeAdaptor(adaptor);
    GParser.statement_return st = parser.statement();

    CommonTreeNodeStream gTreeNodeStream = new CommonTreeNodeStream(
            st.getTree());

    GWalker gwalker = new GWalker(gTreeNodeStream);
    String returnValue = gwalker.statement();
    // print returnValue
} catch (RecognitionException e) {
    throw new IllegalStateException("Recognition exception is never thrown, only declared.");
}

当我运行上面的句柄代码时,它会给出转换异常。我知道为什么当生成AST中的所有节点都应该是 GTree 类型时,这个转换异常,因为我的自定义树采用者GTreeAdaptor将只创建GTree类型的树节点。

帮助我理解这一点并让它得到改善。

投射例外

java.lang.ClassCastException: org.antlr.runtime.tree.CommonTree cannot be cast to driver.antlr.model.GTree       
at driver.antlr.lexerparser.GWalker.statement(GWalker.java:119)   

1 个答案:

答案 0 :(得分:0)

我可以通过在课程 GTreeAdaptor

中添加方法 dupNode()来解决

链接: https://theantlrguy.atlassian.net/wiki/pages/viewpage.action?pageId=2687038

更改了采用者定义:

public class GTreeAdaptor extends CommonTreeAdaptor {
   public GTree create(Token payload) {
       GTree c = new GTree(payload);
       return c;
   }
   public Object dupNode(Object t) {
       if ( t==null ) return null;
       return create(((GTree )t).token);
   }
}