[antlr-interest] Exploit ambiguity in tree rewriter

Benjamin S Wolf jokeserver at gmail.com
Tue Jun 12 20:34:22 PDT 2012


The best way to accomplish this is likely to be an arbitrary action, eg.:

a : INT -> { new CommonTree(new CommonToken(FLOAT, $INT.text + ".0")) } ;

This takes an INT and returns a Tree with one node, a FLOAT token with
text that is the int plus ".0".

You'll want to make a tree via CommonTree() and add a list of children
that excludes all tokens that have IDENTITY (or add each child if it
doesn't have the identity). This means you'll be looping over all the
nodes in the MULT subtree within the action.

On Mon, Jun 11, 2012 at 2:01 AM, nafur <nafur42 at gmail.com> wrote:
> Hi,
>
> I asked about this ambiguity quite a while ago. Does nobody has any idea
> how to do this?
>
> Gereon
>
> On 05/29/2012 12:48 PM, nafur wrote:
>> Hi,
>>
>> I'm using tree rewriters to manipulate formulas that are represented as
>> ASTs. One operation I'd like to do is: "remove any identity from a
>> multiplication".
>>
>> The replacement rule I'm currently working with is the following:
>>
>> topdown :
>>       ^( MULT (before += .)* x=. (after += .)* )
>>       { $x.has("IDENTITY") }?
>>       -> ^( MULT $before* $after* )
>> ;
>>
>> As you probably see, we have some ambiguity here: before and after can
>> both take arbitrarily many elements. If I take an AST like
>> ^( MULT A I x ), the replacement will not match. printing some debug
>> output reveals, that ANTLR will only check $x.has("IDENTITY"), i.e. will
>> only try to match the last element in a multiplication.
>> (That is actually not a surprise, as ANTLR issues a warning...)
>>
>> Is there any way to resolve this ambiguity in a way, such that I can
>> match all occurrences?
>>
>> Thanks,
>> Gereon
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address


More information about the antlr-interest mailing list