[antlr-interest] Calling a tree parser rule manually (a number of
times)
Ric Klaren
ric.klaren at gmail.com
Wed Jun 22 01:57:43 PDT 2005
On 6/21/05, Akhilesh Mritunjai <virtualaspirin at yahoo.com> wrote:
> Here is a small problem. I'm processing a language
> that has compile time macros for generating code. My
> parser builds AST and then I have a tree parser to
> process the uber-macros macros look like this
>
> // loop variable can only be an 'integer'
> for(i = 0; i < 3; i++)
> blah(a[i]);
>
> This should generate:
>
> blah(a[0]);
> blah(a[1]);
> blah(a[2]);
>
> So the input tree looks like something like this:
> #(MAIN
> #(FOR #(FOR_BODY ...ast of (i = 0....) ...)
> #(MACRO_FOR_ITEM
> #(FUNCTION_CALL
> #(IDENTIFIER "blah:)
> ....))))
>
> my processor should convert it to 3 instances of
> FUNCTION_CALL as a list. My treeparser rule looks like
> this:
>
> macro_for:
> // n is number of iterations computed through an
> // involving code, which is omitted
> #(FOR n=macro_for_body mi:MACRO_FOR_ITEM)
> {
> for(int i = 0; i < n; i++)
> {
> // Looks disgusting, no ?
> // manually call the rule
> macro_for_item(#mi, i);
>
> // black magic
> ## = #(null, ##, returnAST);
> }
> }
> ;
Not sure without antlr at hand but.... If you have automatic tree
construction turned on I would disable tree construction for the
macro_for rule ( ! suffix)
> macro_for_item[int valueOfLoopVariable]:
> FUNCTION_CALL
> blah
> {
> search_and_replace loop variable with value
> }
> ;
Return the modified copy of the original tree by returning it from the
macro_for_item rule:
macro_for_item[int valueOfLoopVariable] returns AST:
FUNCTION_CALL
blah
{
search_and_replace loop variable with value
return ##;
}
;
Then the for contents in macro_for:
..
AST modified_tree = macro_for_item(#mi, i);
// black magic
## = #(null, ##, modified_tree);
..
> To summarise: I want to tree-parse the same subtree a
> number of times and add the resulting ast to
> constructed tree.
>
> Is there a better way to accomplish this task than
> outlined above ? I don't like using 'currentAST'
> variable!
The above approach should be cleaner than touching
returnAST/currentAST. Actually it's a quite powerfull thing that you
can call rules directly it's sometimes *very* convenient.
Hope this helps,
Ric
More information about the antlr-interest
mailing list