[antlr-interest] Elusive rewrite rule

Grzegorz Cieslewski cieslewski at hcs.ufl.edu
Mon Apr 14 06:08:13 PDT 2008


Dan,

One way to achieve such effect is to pass the name of the function
token down to the pathExpr function as an input and move the
construction of the FUNCTION subtree into a pathExpr rule.  I
rewritten your grammar a little to yield the AST that you want.

grammar a;

options {
   backtrack=true;
   output=AST;
}

tokens {
 FUNCTION;
 TAG;
}

functionExpr
scope{
	CommonTree path;	
}
 : NAME '(' pathExpr[$NAME] ')' -> pathExpr
 ;

pathExpr[Token fname]
	:NAME ('/' pathExpr[fname]) -> ^(TAG NAME pathExpr?)
  	|NAME (',' args+=ARG)* -> ^(TAG NAME ^(FUNCTION NAME[fname] $args*))
 ;

NAME : ('a'..'z')+ ;

ARG : '\'' (~'\'')* '\'';
WS  :  (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;};

There might be a cleaner way of rewriting the pathExpr rule but this
should get you started.

Greg


On Sat, Apr 12, 2008 at 4:00 PM, Dan <th30dan at gmail.com> wrote:
>
>
> Hello everyone.
>
> I'm trying to figure out how to write the rewrite rule for a parser rule
> named "functionExpr".  I already have rewrite rules for my other parser
> rules.  Here's a simplified version of my grammar:
>
> =======================================================
> tokens {
>  FUNCTION;
>  TAG;
> }
>
> functionExpr
>  : NAME '(' pathExpr (',' ARG)* ')' -> ??????????
>  ;
>
> pathExpr
>  : NAME ('/' pathExpr)? -> ^(TAG NAME pathExpr?)
>  ;
>
> NAME : (a-z)+ ;
> ARG : '\'' (~'\'')* '\'' ;
> =======================================================
>
> My requirements dictate that for this input:
>  foo(a/b/c, '1', '2')
>
> I need to generate this AST:
>  (TAG a (TAG b (TAG c (FUNCTION foo '1' '2'))))
>
> Any ideas what should be the rewrite rule for "functionExpr" to satisfy this
> requirement?
>
>
>
> The basic problem I see is that I need to attach the FUNCTION subtree to the
> 'c' TAG subtree, but I haven't finished processing the entire functionExpr
> input (i.e. the ARGs) at the time I parse the 'c' TAG subtree.
>
> So is there some way to save a "reference" to the 'c' TAG subtree, so that
> when I finish processing the functionExpr ARGs, I can create the FUNCTION
> subtree and attach it to the 'c' TAG subtree via the reference, and have the
> entire structure (starting with the 'a' TAG subtree at the top) become the
> returned subtree of the entire functionExpr rule?
>
> Many thanks,
> -Dan



-- 
=====================================================
Grzegorz Cieslewski
Research Assistant
High-performance Computing & Simulation (HCS) Research Laboratory
University of Florida, Dept. of Electrical and Computer Engineering
330 Benton Hall, Gainesville, FL, 32611-6200
Phone: (352) 392-9041
Email: cieslewski at hcs.ufl.edu
Web: www.hcs.ufl.edu
=====================================================


More information about the antlr-interest mailing list