|RE: [antlr-interest] Tree construction from rules

Bryan Ewbank ewbank at synopsys.com
Tue Sep 28 07:45:27 PDT 2004


> Hello,
> I'm trying to construct trees from my grammar and have run into
> two problems:
>
> a) rule: leftExpr ( ( operator1 | operator2 | operator3 ) rightExpr )?
>
> I want to construct a tree from this with whatever results from operator
> being the root node of the subtree. Note that operator1-3 are rules, so I
> can't write "operator1^". Is there a simple way of solving this? I've
> somewhat succeeded with declaring a local variable within the rule and
> writing "(o1:operator1 { opnode = #o1; } | o2:operator2 { opnode = #o2 }
> ...)" and constructing the tree manually afterwards. But this doesn't seem
> very clean to me. Is there a better solution?

I've done this processing the operator<N> in the scanner, rather than
the parser:

	// parser
	rule : left ( OPER_RULE^ rightExpr )?

	// scanner
	protected OPERATOR_1: .... ;
	protected OPERATOR_2: .... ;
	protected OPERATOR_3: .... ;

	OPER_RULE : OPERATOR_1 | OPERATOR_2 | OPERATOR_3 ;

This does require a string comparison to sort out OPERATOR_<N> in the tree,
rather than keying on the type - the tokens returned from the scanner are
all of type OPER_RULE.

Perhaps there are other ways?

> Both of these problems could be easily solved by allowing the caret (^)
> operator not only on tokens but also on grammar rules. Is there a specific
> reason for not doing this?

I'm guessing here, but I think it's because you don't know the shape of the
tree
for a grammar rule - and therefore you would not know where to attach the
children
if the grammar rule produced a tree rather than a single token.



 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
    antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 



More information about the antlr-interest mailing list