[antlr-interest] seeking advice for a good approach

Geoff hendrey geoff_hendrey at yahoo.com
Sat Oct 20 16:45:07 PDT 2007


Hi,

I am building an AST using the "->" functionality in the grammar file.

The AST contains various types of operator nodes that operate against two operands (child operand nodes).

For example, a logical AND operation, which has a left-hand-side operand and a right-hand-side operand.

I want to examine each AST node, and insure that both the child nodes (the operands) are compatible with the operation being performed on them. 

Here is the approach I am going to take, but maybe some ANTLR genius knows a better way.

So my plan is to extend CommonTree, to say TypeCheckingTree. When  new TypeCheckingTree is constructed, I'll record the type of the operator, if the node is an operator. Then when addChild is called, I will throw an Exception if the child (operand) is incompatible. For example if the node is 'AND' and a child is the literal  '3.14159', an Exception will be thrown since floating point numbers are not acceptable operands to a boolean 'AND' function.

Right now, the only way I can think of to record the operator type, is to make some function like this, which would be called from the constructor of TypeCheckingTree. This will allow the node to know it's type, and to check the type of child nodes (operands) for compatibility :

public String getType(Token t){
    String astNodeName = t.toString();
    if(astNodeName.equals("AND")){
       return "BOOLEAN"
    }else if(astNodeName.equals("OR")){
       return "BOOLEAN"
    }else if(astNodeName.equals("FLOAT")){
       return "NUMERIC";
    }//etc,etc.
}

The above seems really flaky. Especially since "etc, etc" is a really long list, and has to be maintained. It would be better if somehow I could assign a  type  (or somehow attach meta data) to an AST node, from inside the grammar file. Relying on String comparisons against the node's name is pretty weak. 

I'm hoping I am an ignorant newbie and someone will slap me straight!!!

-g
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20071020/713bb604/attachment.html 


More information about the antlr-interest mailing list