tags:

views:

278

answers:

2

I'm using ANTLR 3 to create an AST. I want to have two AST analysers, one to use in production code and one to use in the Eclipse plugin we already have. However, the plugin doesn't require all information in the tree. What I'm looking for is a way to parse the tree without specifying all branches in the grammar. Is there a way to do so?

+1  A: 

I don't know what exactly you want to do though, but I set up a boolean flag in the tree walker when I encountered this problem last time. For example:

@members
{
    boolean executeAction = true;
}
...

equation:
@init{
    if(executeAction){
     //do your things
    }
}
@after{
    if(executeAction){
     //do your things
    }
}
    exp { if(executeAction){/* Do your things */} } EQU exp
;
exp:
@init{
    if(executeAction){
     //do your things
    }
}
@after{
    if(executeAction){
     //do your things
    }
}
    integer OPE integer
;

...

This way, you can easily switch the execution on or off. You just have to wrap all the codes into an if statement.

The thing is that in Antlr, there is no such kind of thing called skipping the subsequent rules. They are to be walked through anyway. So we can only do it manually.

Winston Chen
That's not what I want to do. What I need is to simply skip a branch in the tree, without specifying the way that branch looks exactly.
Jorn
Do you mean that you would like to define a rule without specifying how it is composed in its lexer and parser? If this is the case, then it is impossible in antlr.But if you are talking about creating a walker that only contains the rules you want it to appear, you can always rewrite the tree to forge the tree you want.
Winston Chen
How would you go about rewriting that tree? Creating another grammar, that turns the first tree into another? Maybe changing the ANTLRInputStream to only show only the tokens I need?
Jorn
+2  A: 

You may have figured this out already, but I've used . or .* in my tree grammars to skip either a given node or any number of nodes.

For example, I have a DSL that allows function declarations, and one of my tree grammars just cares about names and arguments, but not the contents (which could be arbitrarily long). I skip the processing of the code block using .* as a placeholder:

^(Function type_specifier? variable_name formal_parameters implemented_by? .*)

I don't know about the runtime performance hit, if any, but I'm not using this construct in any areas where performance is an issue for my application.

CapnNefarious