[antlr-interest] Semantic Analysis via TreeWalker

Tilman Bender tbender at stud.hs-heilbronn.de
Wed May 6 14:05:09 PDT 2009


Hi folks,

I am still struggling with the semantic analysis in my little  
compiler. First of all here is what I have so far.

* On the parser level I allow operators to be used on all kinds   
operands e.g:
   "true + false " would be accepted by my parser an converted to ^(+  
true false)

* To still catch such errors I introduced an extra compiler stage in  
the form of a TreeWalker containing rules like the following:

expression returns [String returntype]
:
^(PLUS a=expression b=expression)
{
   if($a.returntype.equals("int")&& $b.returntype.equals("int"))
   {
     $returntype="int";
   }
   else if ($a.returntype.equals("int")&& $b.returntype.equals("float"))
   {
     //TODO convert all ints in the left subtree to float
     $returntype="float";
   }
   else if ($a.returntype.equals("float")&& $b.returntype.equals("int"))
   {
     //TODO convert all ints in the right subtree to float
     $returntype="float";
   }
   else if ($a.returntype.equals("float")&&  
$b.returntype.equals("float"))
   {
     $returntype="float";
   }else
   {
      throw new InvalidTypeException();
   }

}
-> ^(PLUS $a $b)

Unfortunately I still have two problems with this:

1. How can I throw a detailed Error Message saying something like "The  
operator + is invald for the types of "+ $a.returntype + " and "+ 
$b.returntype

2. How can I modifiy the tree returned by $a so that I can replace  
every token like INT:3 with a token of FLOAT:3.0.  So that (+ 3 4.0)  
becomes (+ 3.0 4.0)
I would write a recursive method for doint the tree manipulation but  
my main problem is, that I do not know how to "reattach" the modfied  
subtree to my result.
$a.tree=castIntToFloat($a.tree) won't work because $a.tree is  
readonly :-(

kind regards & thanks in advance

Tilman Bender
Student des Software Engineering
Hochschule Heilbronn
tbender at stud.hs-heilbronn.de



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090506/8c04aefa/attachment.html 


More information about the antlr-interest mailing list