[antlr-interest] About tree duplication ?

Ric Klaren ric.klaren at gmail.com
Thu Nov 17 03:09:59 PST 2005


Hi,

Mathieu Clabaut wrote:
>   In a tree parser, I can not reference twice the same tree when
> constructing a new tree. I have to call astFactory->create().
>   Is there a way to only use antlr notation ? Is this a feature or a bug ?

Keep in mind that the antlr tree objects are references or reference
counted objects. Basically they behave like pointers.

>  For example, the following creation rules
>   	    ##= #([OR_SERVICE,"||"],
> 		     #([TWOWAY,"<>"],#s3,
> 			#([SOURCE,":<"], #f3),
> 			#([DESTINATION,":>"],#t3)
> 		     ),
> 		     #([TWOWAY,"<>"],#s3,
> 			#([SOURCE,":<"], #t3),
> 			#([DESTINATION,":>"],#f3)
> 		     )

This is really bad practice since you link a node into the tree at
multiple spots, potentially creating loops in the tree that will hang
the normal tree traversal functions.

Before you stick the nodes in the tree you have to duplicate them using
ASTFactory->dup() or dupTree() in case it's a subtree you're dealing
with. Another option is to use the clone method of the nodes.

> Whereas the following creation rules:
> 	    ##= #([OR_SERVICE,"||"],
> 		     #([TWOWAY,"<>"],#s3,
> 			#([TWOCOLON,"::"] , #b3),
> 			#([SOURCE,":<"], #f3),
> 			#([DESTINATION,":>"],#t3)
> 		     ),
> 		     #([TWOWAY,"<>"],astFactory->create(#s3),
> 			#([TWOCOLON,"::"] , #b3),
> 			#([SOURCE,":<"], #t3),
> 			#([DESTINATION,":>"],#f3)
> 		     )
> Gives the expected results :
> ||
>  <>
>   s3 :<f3 :> t3
>  <>
>   s3 :<t3 :>f3

This is better but you should dup/clone all the nodes you put in twice.
Safest practice is to clone everything but if you're sure the
s3/b3/f3/t3 are only used once then it suffices to only do it once.

Cheers,

Ric


More information about the antlr-interest mailing list