[antlr-interest] Choosing AST rewrite based on test
Kirby Bohling
kirby.bohling at gmail.com
Tue Oct 13 09:10:54 PDT 2009
On Tue, Oct 13, 2009 at 10:39 AM, Bill Andersen
<andersen at ontologyworks.com> wrote:
> Hi All
>
> I have the following rule in a tree grammar (BTW, rewrite = true
> here). Both AS_TEXT and AS_NAME are imaginary tokens.
>
> text_block
> : ^(AS_TEXT text_option* name? phrase+ )
> -> ?????
> ;
>
> what I want for the ????? part is the rewrite
<snip...>
Bill couldn't you do that "the other way"? I mean by write a rule like this:
text_block: ^(AS_TEXT text_option* optional_or_gen_name phrase+)
;
optional_or_gen_name:
(
name -> ^(NAME_NODE name)
|
-> ^(GEN_NAME_NODE)
)
;
I threw together a quick example that shows the syntax works in a
parser (I'd assume it'd work in a tree grammar). I think this will
accomplish what you want. Not sure if you wanted the name to be it's
own subtree, but I generally make rooted trees because it eliminates
backtracking.
Cheers,
Kirby
// Sample grammar that compiles in ANTLRWorks 1.3 for me.
grammar foo;
options {
rewrite=true;
output=AST;
}
tokens {
NAME;
GEN_NAME;
}
text_block:
(text_option* name? phrase+ )
;
text_option
: '(' TEXT ')'
;
TEXT: 'a'..'z'
;
// after GEN_NAME add a { } block to attach the generated name to the token.
gen_or_name
: (name -> ^(NAME name) | -> ^(GEN_NAME) )
;
name: '{' TEXT '}'
;
phrase
: TEXT
;
More information about the antlr-interest
mailing list