[antlr-interest] Need help with rewrite rules

Chrobot, Stefan Stefan.Chrobot at sabre.com
Mon Mar 22 07:57:06 PDT 2010


Hello,

 

I need help with rewriting rules in ANTLR.

 

I'm writing a translator between different dialects of a programming
language. My task is to replace function calls from one dialect to
function calls of the other dialect (this involved choosing the right
function, probably reordering, removing or adding parameters, etc.). The
rest of the source code is not to be altered much. My idea is that when
I come across a function call, I build an object model, call my function
to convert that call to a string representing a call in the target
language and replace the source string - that solves the problem of
nested calls and the fact that function calls can appear "everywhere".
In the topmost rule I just want to call print-like function with the
whole parsed (and replaced) text.

 

How to solve this problem the easiest way possible?

 

 

The simplified grammar looks like this (I omitted the tokens):

 

grammar Test;

 

options {

                language = CSharp2;

                output = AST;

}

 

start_rule

                :               functions {
System.Console.WriteLine($functions.text); }

                ;

 

functions

                :               function+

                ;

 

function

@init {

                var function = new Function(); // build the object

}

                :               ID
{ /*...*/ }

                                '('

                                (

                                arg1 = expression
{ /*...*/ }

                                (',' arg2 = expression
{ /*...*/ }

                                )*

                                )?                            

                                ')'

                                // doesn't work: the attribute is read
only

                                // { $function.text =
Tools.Convert(function); }

                                // doesn't work: printing tokens from
TokenRewriteStream gives the source input

                                //-> { new CommonTree(new CommonToken(0,
Tools.Convert(function))) }

                ;

                

expression

                :               (ID | INT )

                                (

                                                ('+' | '-') (ID | INT)

                                )?

                                |              function

                ;



More information about the antlr-interest mailing list