[antlr-interest] ClassCastException with custom node type

Stefan Mätje Stefan.Maetje at esd-electronics.com
Thu Jul 5 00:57:43 PDT 2012


Am 04.07.2012 20:52, schrieb Ale Strooisma:
> Hello,
>
> I get this error:
> java.lang.ClassCastException: org.antlr.runtime.tree.CommonTree cannot
> be cast to wc.util.ASTNode
>       at wc.compiler.WcChecker.expr(WcChecker.java:1290)
>       at wc.compiler.WcChecker.statement(WcChecker.java:928)
>       at
> wc.compiler.WcChecker.nonOpeningCompoundStatement(WcChecker.java:814)
>       at wc.compiler.WcChecker.function(WcChecker.java:755)
>       at wc.compiler.WcChecker.program(WcChecker.java:289)
>       at wc.Driver.compile(Driver.java:95)
>       at wc.Driver.main(Driver.java:67)
> on the line: t=(ASTNode)match(input,BECOMES,FOLLOW_BECOMES_in_expr445);
>
> I created a node and errornode class and an factory for it. The weird
> thing is that when I replace the line with:
>
> Object ct = match(input,BECOMES,FOLLOW_BECOMES_in_expr445);
> System.out.println(ct.getClass());
> t=(ASTNode)ct;
>
> then, with a certain test-file first two times the type
> "wc.util.ASTNode" is outputted, and after that
> "org.antlr.runtime.tree.CommonTree".

Hi,

I had a similar problem when I used a tree parser (Pearl90Sym) to 
examine my generated AST again. Please see the attached Java code 
excerpt to see what you have to do to set the customized tree adapter 
early enough.

Some error accounting and other stuff has been cut away marked there 
with "SNIP-SNAP". The interesting line is marked with "This line fixed 
crash on spurious CommonToken insertions."

I'm not quite sure if my solution fits to your needs but I believe the 
crucial point is to set the *Adapter early enough because some nodes 
(like UP and DOWN nodes) are generated at the instantiation time / first 
call of the CommonTreeNodeStream() class and then always reused. At this 
point the TreeAdapter must already be set to have them instantiated as 
object of your custom tree node class. Without a custom tree adapter the 
objects will be created with the default adapter building CommonTree nodes.

I hope that may give you a clue whats going wrong.

Regards,
	Stefan

PS.: My classes are
	Pearl90Tree		a tree node
	Pearl90TreeAdaptor	the node factory?
	Pearl90ErrorNode	the error node object





More information about the antlr-interest mailing list