[antlr-interest] Newbie Rule Rewrite

David Holroyd dave at badgers-in-foil.co.uk
Tue Apr 17 13:16:33 PDT 2007


On Tue, Apr 17, 2007 at 03:37:00PM -0400, xkrebstarx wrote:
> >What do you want thhe output to look like?
> 
> I am using ANTLR v3 and I would like the rule to look like this...
> 
> rule      ( identifier | b | c | d ) ( '[' subscript ']' | f | g )*
>        ;
> 
> 
> and the input tokens a[i][j] would give me something like
> 
> 
> sub
>    sub
>        a
>        i
>    j
> 
> 
> The tough part is figuring out how the first set ( a,b,c,d ) and the
> second set ( e,f,g ) would be represented in the rewrite. That sounds
> a big vague, let me try to explain a little more.
> 
> If I do something this
> 
>      rule     ( a | b | c | d )
>                       ( e  -> ^('sub' a e)
>                         | f  -> rewrite
>                         | g -> rewrite
>                       }*
> 
> 
> how do I know what a,b,c or d was used. I get an error.

How about simplifying the rule by extracting the prefix set?

rule
	:	p=rule_prefix
	(	e -> ^(SUB $p e)
	|	f -> rewrite
	|	g -> rewrite
	)*

rule_prefix
	:	a | b | c | d


The problem then is that it still doesn't handle the (..)* so that
recursive SUB trees are built, so you need the rewrites specified not in
terms of the prefix ($p, above), but in terms of the existing result
tree, which you can do like this,

rule
	:	rule_prefix -> rule_prefix
	(	'[' subscript ']' -> ^(SUB $rule e)
	|	f -> rewrite
	|	g -> rewrite
	)*

The trick above is the 'rule_prefix -> rule_prefix', as without that
construction, $rule will be a null tree at the point when the parser
enters the (..)*.

Hope that helps, and the examples I gave are actually correct :)


ta,
dave

-- 
http://david.holroyd.me.uk/


More information about the antlr-interest mailing list