java - ANTLR parser node type + Tree Adopter? -
i have developed small antlr grammar. contains 3 files.
- glexer.g : lexer
- gparser.g : parser of tpye ast
- gwalker.g : tree parser
also have custom tree node gtree (extends commontree) , tree adoptergadaptor ( extends commontreeadaptor ). see sample code below.
lexer : glexer.g
lexer grammar glexer; .. 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* ) ;
tree node
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 handler
try { //lexer splits input 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 , 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 never thrown, declared."); }
when run handle code above , giving casting exception. know why casting exception when nodes in generated ast should of type gtree custom tree adopter gtreeadaptor create tree node of type gtree.
help me understandinmg , getting resoved.
casting exception
java.lang.classcastexception: org.antlr.runtime.tree.commontree cannot cast driver.antlr.model.gtree @ driver.antlr.lexerparser.gwalker.statement(gwalker.java:119)
i able resolved adding method dupnode() in class gtreeadaptor
link : https://theantlrguy.atlassian.net/wiki/pages/viewpage.action?pageid=2687038
changed adopter definition :
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); } }
Comments
Post a Comment