As static blocks is compiled as a method without returntype, previous isConstructor...
[IRC.git] / Robust / src / IR / Tree / SemanticCheck.java
1 package IR.Tree;
2
3 import java.util.*;
4
5 import IR.*;
6
7 public class SemanticCheck {
8   State state;
9   TypeUtil typeutil;
10   Stack loopstack;
11   HashSet toanalyze;
12   HashSet completed;
13
14
15   public SemanticCheck(State state, TypeUtil tu) {
16     this.state=state;
17     this.typeutil=tu;
18     this.loopstack=new Stack();
19     this.toanalyze=new HashSet();
20     this.completed=new HashSet();
21   }
22
23   public ClassDescriptor getClass(String classname) {
24     ClassDescriptor cd=typeutil.getClass(classname, toanalyze);
25     checkClass(cd);
26     return cd;
27   }
28
29   private void checkClass(ClassDescriptor cd) {
30     if (!completed.contains(cd)) {
31       completed.add(cd);
32       
33       //Set superclass link up
34       if (cd.getSuper()!=null) {
35         cd.setSuper(getClass(cd.getSuper()));
36         // Link together Field, Method, and Flag tables so classes
37         // inherit these from their superclasses
38         cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
39         cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
40         cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
41     if(state.MGC) {
42       // TODO add version for normal Java later
43       // Link together Field, Method tables do classes inherit these from 
44       // their ancestor interfaces
45       Vector<String> sifv = cd.getSuperInterface();
46       for(int i = 0; i < sifv.size(); i++) {
47         ClassDescriptor superif = getClass(sifv.elementAt(i));
48         cd.addSuperInterfaces(superif);
49         cd.getFieldTable().addParentIF(superif.getFieldTable());
50         cd.getMethodTable().addParentIF(superif.getMethodTable());
51       }
52     }
53       }
54       
55       /* Check to see that fields are well typed */
56       for(Iterator field_it=cd.getFields(); field_it.hasNext();) {
57         FieldDescriptor fd=(FieldDescriptor)field_it.next();
58         checkField(cd,fd);
59       }
60       
61       boolean hasConstructor = false;
62       for(Iterator method_it=cd.getMethods(); method_it.hasNext();) {
63         MethodDescriptor md=(MethodDescriptor)method_it.next();
64         checkMethod(cd,md);
65     hasConstructor |= md.isConstructor();
66       }
67       if(!hasConstructor) {
68         // add a default constructor for this class
69         MethodDescriptor md = new MethodDescriptor(new Modifiers(Modifiers.PUBLIC),
70             cd.getSymbol(), false);
71         BlockNode bn=new BlockNode();
72         state.addTreeCode(md,bn);
73         cd.addMethod(md);
74         checkMethod(cd,md);
75       }
76     }
77   }
78
79   public void semanticCheck() {
80     SymbolTable classtable=state.getClassSymbolTable();
81     toanalyze.addAll(classtable.getValueSet());
82     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
83
84     // Do methods next
85     while(!toanalyze.isEmpty()) {
86       Object obj=toanalyze.iterator().next();
87       if (obj instanceof TaskDescriptor) {
88         toanalyze.remove(obj);
89         TaskDescriptor td=(TaskDescriptor)obj;
90         try {
91           checkTask(td);
92         } catch( Error e ) {
93             System.out.println( "Error in "+td );
94             throw e;
95         }
96       } else {
97         ClassDescriptor cd=(ClassDescriptor)obj;
98         toanalyze.remove(cd);
99         //need to initialize typeutil object here...only place we can
100         //get class descriptors without first calling getclass
101         getClass(cd.getSymbol());
102         for(Iterator method_it=cd.getMethods(); method_it.hasNext();) {
103           MethodDescriptor md=(MethodDescriptor)method_it.next();
104           try {
105             checkMethodBody(cd,md);
106           } catch( Error e ) {
107             System.out.println( "Error in "+md );
108             throw e;
109           }
110         }
111       }
112     }
113   }
114
115   public void checkTypeDescriptor(TypeDescriptor td) {
116     if (td.isPrimitive())
117       return;       /* Done */
118     else if (td.isClass()) {
119       String name=td.toString();
120       ClassDescriptor field_cd=getClass(name);
121       if (field_cd==null)
122         throw new Error("Undefined class "+name);
123       td.setClassDescriptor(field_cd);
124       return;
125     } else if (td.isTag())
126       return;
127     else
128       throw new Error();
129   }
130
131   public void checkField(ClassDescriptor cd, FieldDescriptor fd) {
132     checkTypeDescriptor(fd.getType());
133   }
134
135   public void checkConstraintCheck(TaskDescriptor td, SymbolTable nametable, Vector ccs) {
136     if (ccs==null)
137       return;       /* No constraint checks to check */
138     for(int i=0; i<ccs.size(); i++) {
139       ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
140
141       for(int j=0; j<cc.numArgs(); j++) {
142         ExpressionNode en=cc.getArg(j);
143         checkExpressionNode(td,nametable,en,null);
144       }
145     }
146   }
147
148   public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
149     if (vfe==null)
150       return;       /* No flag effects to check */
151     for(int i=0; i<vfe.size(); i++) {
152       FlagEffects fe=(FlagEffects) vfe.get(i);
153       String varname=fe.getName();
154       //Make sure the variable is declared as a parameter to the task
155       VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
156       if (vd==null)
157         throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
158       fe.setVar(vd);
159
160       //Make sure it correspods to a class
161       TypeDescriptor type_d=vd.getType();
162       if (!type_d.isClass())
163         throw new Error("Cannot have non-object argument for flag_effect");
164
165       ClassDescriptor cd=type_d.getClassDesc();
166       for(int j=0; j<fe.numEffects(); j++) {
167         FlagEffect flag=fe.getEffect(j);
168         String name=flag.getName();
169         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
170         //Make sure the flag is declared
171         if (flag_d==null)
172           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
173         if (flag_d.getExternal())
174           throw new Error("Attempting to modify external flag: "+name);
175         flag.setFlag(flag_d);
176       }
177       for(int j=0; j<fe.numTagEffects(); j++) {
178         TagEffect tag=fe.getTagEffect(j);
179         String name=tag.getName();
180
181         Descriptor d=(Descriptor)nametable.get(name);
182         if (d==null)
183           throw new Error("Tag descriptor "+name+" undeclared");
184         else if (!(d instanceof TagVarDescriptor))
185           throw new Error(name+" is not a tag descriptor");
186         tag.setTag((TagVarDescriptor)d);
187       }
188     }
189   }
190
191   public void checkTask(TaskDescriptor td) {
192     for(int i=0; i<td.numParameters(); i++) {
193       /* Check that parameter is well typed */
194       TypeDescriptor param_type=td.getParamType(i);
195       checkTypeDescriptor(param_type);
196
197       /* Check the parameter's flag expression is well formed */
198       FlagExpressionNode fen=td.getFlag(td.getParameter(i));
199       if (!param_type.isClass())
200         throw new Error("Cannot have non-object argument to a task");
201       ClassDescriptor cd=param_type.getClassDesc();
202       if (fen!=null)
203         checkFlagExpressionNode(cd, fen);
204     }
205
206     checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
207     /* Check that the task code is valid */
208     BlockNode bn=state.getMethodBody(td);
209     checkBlockNode(td, td.getParameterTable(),bn);
210   }
211
212   public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
213     switch(fen.kind()) {
214     case Kind.FlagOpNode:
215     {
216       FlagOpNode fon=(FlagOpNode)fen;
217       checkFlagExpressionNode(cd, fon.getLeft());
218       if (fon.getRight()!=null)
219         checkFlagExpressionNode(cd, fon.getRight());
220       break;
221     }
222
223     case Kind.FlagNode:
224     {
225       FlagNode fn=(FlagNode)fen;
226       String name=fn.getFlagName();
227       FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
228       if (fd==null)
229         throw new Error("Undeclared flag: "+name);
230       fn.setFlag(fd);
231       break;
232     }
233
234     default:
235       throw new Error("Unrecognized FlagExpressionNode");
236     }
237   }
238
239   public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
240     if(state.MGC) {
241       // TODO add version for normal Java later
242       /* Check for abstract methods */
243       if(md.isAbstract()) {
244         if(!cd.isAbstract() && !cd.isInterface()) {
245           throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
246         }
247       }
248     }
249     /* Check return type */
250     if (!md.isConstructor() && !md.isStaticBlock())
251       if (!md.getReturnType().isVoid())
252         checkTypeDescriptor(md.getReturnType());
253
254     for(int i=0; i<md.numParameters(); i++) {
255       TypeDescriptor param_type=md.getParamType(i);
256       checkTypeDescriptor(param_type);
257     }
258     /* Link the naming environments */
259     if (!md.isStatic())     /* Fields aren't accessible directly in a static method, so don't link in this table */
260       md.getParameterTable().setParent(cd.getFieldTable());
261     md.setClassDesc(cd);
262     if (!md.isStatic()) {
263       VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
264       md.setThis(thisvd);
265     }
266   }
267
268   public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
269     ClassDescriptor superdesc=cd.getSuperDesc();
270     if (superdesc!=null) {
271       Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
272       for(Iterator methodit=possiblematches.iterator(); methodit.hasNext();) {
273         MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
274         if (md.matches(matchmd)) {
275           if (matchmd.getModifiers().isFinal()) {
276             throw new Error("Try to override final method in method:"+md+" declared in  "+cd);
277           }
278         }
279       }
280     }
281     BlockNode bn=state.getMethodBody(md);
282     checkBlockNode(md, md.getParameterTable(),bn);
283   }
284
285   public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
286     /* Link in the naming environment */
287     bn.getVarTable().setParent(nametable);
288     for(int i=0; i<bn.size(); i++) {
289       BlockStatementNode bsn=bn.get(i);
290       checkBlockStatementNode(md, bn.getVarTable(),bsn);
291     }
292   }
293
294   public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
295     switch(bsn.kind()) {
296     case Kind.BlockExpressionNode:
297       checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
298       return;
299
300     case Kind.DeclarationNode:
301       checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
302       return;
303
304     case Kind.TagDeclarationNode:
305       checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
306       return;
307
308     case Kind.IfStatementNode:
309       checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
310       return;
311       
312     case Kind.SwitchStatementNode:
313       checkSwitchStatementNode(md, nametable, (SwitchStatementNode)bsn);
314       return;
315
316     case Kind.LoopNode:
317       checkLoopNode(md, nametable, (LoopNode)bsn);
318       return;
319
320     case Kind.ReturnNode:
321       checkReturnNode(md, nametable, (ReturnNode)bsn);
322       return;
323
324     case Kind.TaskExitNode:
325       checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
326       return;
327
328     case Kind.SubBlockNode:
329       checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
330       return;
331
332     case Kind.AtomicNode:
333       checkAtomicNode(md, nametable, (AtomicNode)bsn);
334       return;
335
336     case Kind.SynchronizedNode:
337       checkSynchronizedNode(md, nametable, (SynchronizedNode)bsn);
338       return;
339
340     case Kind.ContinueBreakNode:
341         checkContinueBreakNode(md, nametable, (ContinueBreakNode) bsn);
342         return;
343
344     case Kind.SESENode:
345     case Kind.GenReachNode:
346       // do nothing, no semantic check for SESEs
347       return;
348     }
349
350     throw new Error();
351   }
352
353   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
354     checkExpressionNode(md, nametable, ben.getExpression(), null);
355   }
356
357   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
358     VarDescriptor vd=dn.getVarDescriptor();
359     checkTypeDescriptor(vd.getType());
360     Descriptor d=nametable.get(vd.getSymbol());
361     if ((d==null)||
362         (d instanceof FieldDescriptor)) {
363       nametable.add(vd);
364     } else
365       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
366     if (dn.getExpression()!=null)
367       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
368   }
369
370   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
371     TagVarDescriptor vd=dn.getTagVarDescriptor();
372     Descriptor d=nametable.get(vd.getSymbol());
373     if ((d==null)||
374         (d instanceof FieldDescriptor)) {
375       nametable.add(vd);
376     } else
377       throw new Error(vd.getSymbol()+" defined a second time");
378   }
379
380   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
381     checkBlockNode(md, nametable, sbn.getBlockNode());
382   }
383
384   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
385     checkBlockNode(md, nametable, sbn.getBlockNode());
386   }
387
388   void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
389     checkBlockNode(md, nametable, sbn.getBlockNode());
390     //todo this could be Object
391     checkExpressionNode(md, nametable, sbn.getExpr(), null);
392   }
393
394   void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
395       if (loopstack.empty())
396           throw new Error("continue/break outside of loop");
397       LoopNode ln=(LoopNode)loopstack.peek();
398       cbn.setLoop(ln);
399   }
400
401   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
402     if (d instanceof TaskDescriptor)
403       throw new Error("Illegal return appears in Task: "+d.getSymbol());
404     MethodDescriptor md=(MethodDescriptor)d;
405     if (rn.getReturnExpression()!=null)
406       if (md.getReturnType()==null)
407         throw new Error("Constructor can't return something.");
408       else if (md.getReturnType().isVoid())
409         throw new Error(md+" is void");
410       else
411         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
412     else
413     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
414       throw new Error("Need to return something for "+md);
415   }
416
417   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
418     if (md instanceof MethodDescriptor)
419       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
420     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
421     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
422   }
423
424   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
425     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
426     checkBlockNode(md, nametable, isn.getTrueBlock());
427     if (isn.getFalseBlock()!=null)
428       checkBlockNode(md, nametable, isn.getFalseBlock());
429   }
430   
431   void checkSwitchStatementNode(Descriptor md, SymbolTable nametable, SwitchStatementNode ssn) {
432     checkExpressionNode(md, nametable, ssn.getCondition(), new TypeDescriptor(TypeDescriptor.INT));
433     
434     BlockNode sbn = ssn.getSwitchBody();
435     boolean hasdefault = false;
436     for(int i = 0; i < sbn.size(); i++) {
437       boolean containdefault = checkSwitchBlockNode(md, nametable, (SwitchBlockNode)sbn.get(i));
438       if(hasdefault && containdefault) {
439         throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
440       }
441       hasdefault = containdefault;
442     }
443   }
444   
445   boolean checkSwitchBlockNode(Descriptor md, SymbolTable nametable, SwitchBlockNode sbn) {
446     Vector<SwitchLabelNode> slnv = sbn.getSwitchConditions();
447     int defaultb = 0;
448     for(int i = 0; i < slnv.size(); i++) {
449       if(slnv.elementAt(i).isdefault) {
450         defaultb++;
451       } else {
452         checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
453       }
454     }
455     if(defaultb > 1) {
456       throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
457     } else {
458       checkBlockNode(md, nametable, sbn.getSwitchBlockStatement());
459       return (defaultb > 0);
460     }
461   }
462   
463   void checkConstantExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
464     switch(en.kind()) {
465     case Kind.FieldAccessNode:
466       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
467       return;
468      
469     case Kind.LiteralNode:
470       checkLiteralNode(md,nametable,(LiteralNode)en,td);
471       return;
472     }
473     throw new Error();
474   }
475
476   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
477     switch(en.kind()) {
478     case Kind.AssignmentNode:
479       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
480       return;
481
482     case Kind.CastNode:
483       checkCastNode(md,nametable,(CastNode)en,td);
484       return;
485
486     case Kind.CreateObjectNode:
487       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
488       return;
489
490     case Kind.FieldAccessNode:
491       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
492       return;
493
494     case Kind.ArrayAccessNode:
495       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
496       return;
497
498     case Kind.LiteralNode:
499       checkLiteralNode(md,nametable,(LiteralNode)en,td);
500       return;
501
502     case Kind.MethodInvokeNode:
503       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
504       return;
505
506     case Kind.NameNode:
507       checkNameNode(md,nametable,(NameNode)en,td);
508       return;
509
510     case Kind.OpNode:
511       checkOpNode(md,nametable,(OpNode)en,td);
512       return;
513
514     case Kind.OffsetNode:
515       checkOffsetNode(md, nametable, (OffsetNode)en, td);
516       return;
517
518     case Kind.TertiaryNode:
519       checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
520       return;
521       
522     case Kind.InstanceOfNode:
523       checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
524       return;
525
526     case Kind.ArrayInitializerNode:
527       checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
528       return;
529      
530     case Kind.ClassTypeNode:
531       checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
532       return;
533     }
534     throw new Error();
535   }
536
537   void checkClassTypeNode(Descriptor md, SymbolTable nametable, ClassTypeNode tn, TypeDescriptor td) {
538     checkTypeDescriptor(tn.getType());
539   }
540   
541   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
542     /* Get type descriptor */
543     if (cn.getType()==null) {
544       NameDescriptor typenamed=cn.getTypeName().getName();
545       String typename=typenamed.toString();
546       TypeDescriptor ntd=new TypeDescriptor(getClass(typename));
547       cn.setType(ntd);
548     }
549
550     /* Check the type descriptor */
551     TypeDescriptor cast_type=cn.getType();
552     checkTypeDescriptor(cast_type);
553
554     /* Type check */
555     if (td!=null) {
556       if (!typeutil.isSuperorType(td,cast_type))
557         throw new Error("Cast node returns "+cast_type+", but need "+td);
558     }
559
560     ExpressionNode en=cn.getExpression();
561     checkExpressionNode(md, nametable, en, null);
562     TypeDescriptor etd=en.getType();
563     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
564       return;
565
566     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
567       return;
568     if (typeutil.isCastable(etd, cast_type))
569       return;
570
571     /* Different branches */
572     /* TODO: change if add interfaces */
573     throw new Error("Cast will always fail\n"+cn.printNode(0));
574   }
575
576   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
577     ExpressionNode left=fan.getExpression();
578     checkExpressionNode(md,nametable,left,null);
579     TypeDescriptor ltd=left.getType();
580     String fieldname=fan.getFieldName();
581
582     FieldDescriptor fd=null;
583     if (ltd.isArray()&&fieldname.equals("length"))
584       fd=FieldDescriptor.arrayLength;
585     else
586       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
587     if(state.MGC) {
588       // TODO add version for normal Java later
589     if(ltd.isStatic()) {
590       if(ltd.getClassDesc().isEnum()) {
591         int value = ltd.getClassDesc().getEnumConstant(fieldname);
592         if(-1 == value) {
593           // check if this field is an enum constant
594           throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
595         }
596         fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
597         fd.setAsEnum();
598         fd.setEnumValue(value);
599       } else if(fd.isStatic()) {
600         // check if this field is a static field
601         if(fd.getExpressionNode() != null) {
602           checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
603         }
604       } else {
605         throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
606       }
607     } 
608     }
609     if (fd==null)
610       throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
611
612     if (fd.getType().iswrapper()) {
613       FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
614       fan2.setField(fd);
615       fan.left=fan2;
616       fan.fieldname="value";
617
618       ExpressionNode leftwr=fan.getExpression();
619       TypeDescriptor ltdwr=leftwr.getType();
620       String fieldnamewr=fan.getFieldName();
621       FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
622       fan.setField(fdwr);
623       if (fdwr==null)
624           throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
625     } else {
626       fan.setField(fd);
627     }
628     if (td!=null) {
629       if (!typeutil.isSuperorType(td,fan.getType()))
630         throw new Error("Field node returns "+fan.getType()+", but need "+td);
631     }
632   }
633
634   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
635     ExpressionNode left=aan.getExpression();
636     checkExpressionNode(md,nametable,left,null);
637
638     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
639     TypeDescriptor ltd=left.getType();
640     if (ltd.dereference().iswrapper()) {
641       aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
642     }
643
644     if (td!=null)
645       if (!typeutil.isSuperorType(td,aan.getType()))
646         throw new Error("Field node returns "+aan.getType()+", but need "+td);
647   }
648
649   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
650     /* Resolve the type */
651     Object o=ln.getValue();
652     if (ln.getTypeString().equals("null")) {
653       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
654     } else if (o instanceof Integer) {
655       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
656     } else if (o instanceof Long) {
657       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
658     } else if (o instanceof Float) {
659       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
660     } else if (o instanceof Boolean) {
661       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
662     } else if (o instanceof Double) {
663       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
664     } else if (o instanceof Character) {
665       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
666     } else if (o instanceof String) {
667       ln.setType(new TypeDescriptor(getClass(TypeUtil.StringClass)));
668     }
669
670     if (td!=null)
671       if (!typeutil.isSuperorType(td,ln.getType())) {
672         Long l = ln.evaluate();
673         if((ln.getType().isByte() || ln.getType().isShort() 
674             || ln.getType().isChar() || ln.getType().isInt()) 
675             && (l != null) 
676             && (td.isByte() || td.isShort() || td.isChar() 
677                 || td.isInt() || td.isLong())) {
678           long lnvalue = l.longValue();
679           if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128))) 
680               || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
681               || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
682               || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
683               || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
684             throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
685           }
686         } else {
687           throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
688         }
689       }
690   }
691
692   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
693     NameDescriptor nd=nn.getName();
694     if (nd.getBase()!=null) {
695       /* Big hack */
696       /* Rewrite NameNode */
697       ExpressionNode en=translateNameDescriptorintoExpression(nd);
698       nn.setExpression(en);
699       checkExpressionNode(md,nametable,en,td);
700     } else {
701       String varname=nd.toString();
702       Descriptor d=(Descriptor)nametable.get(varname);
703       if (d==null) {
704         if(state.MGC) {
705           // TODO add version for normal Java later
706         ClassDescriptor cd = null;
707         if(((MethodDescriptor)md).isStaticBlock()) {
708           // this is a static block, all the accessed fields should be static field
709           cd = ((MethodDescriptor)md).getClassDesc();
710           SymbolTable fieldtbl = cd.getFieldTable();
711           FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
712           if((fd == null) || (!fd.isStatic())){
713             // no such field in the class, check if this is a class
714             if(varname.equals("this")) {
715               throw new Error("Error: access this obj in a static block");
716             }
717             cd=getClass(varname);
718             if(cd != null) {
719               // this is a class name
720               nn.setClassDesc(cd);
721               return;
722             } else {
723               throw new Error("Name "+varname+" should not be used in static block: "+md);
724             }
725           } else {
726             // this is a static field
727             nn.setField(fd);
728             nn.setClassDesc(cd);
729             return;
730           }
731         } else {
732           cd=getClass(varname);
733           if(cd != null) {
734             // this is a class name
735             nn.setClassDesc(cd);
736             return;
737           } else {
738             throw new Error("Name "+varname+" undefined in: "+md);
739           }
740         }
741         } else {
742           throw new Error("Name "+varname+" undefined in: "+md);
743         }
744       }
745       if (d instanceof VarDescriptor) {
746         nn.setVar(d);
747       } else if (d instanceof FieldDescriptor) {
748         FieldDescriptor fd=(FieldDescriptor)d;
749         if (fd.getType().iswrapper()) {
750           String id=nd.getIdentifier();
751           NameDescriptor base=nd.getBase();
752           NameNode n=new NameNode(nn.getName());
753           n.setField(fd);
754           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
755           FieldAccessNode fan=new FieldAccessNode(n,"value");
756           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
757           fan.setField(fdval);
758           nn.setExpression(fan);
759         } else {
760           nn.setField(fd);
761           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
762         }
763       } else if (d instanceof TagVarDescriptor) {
764         nn.setVar(d);
765       } else throw new Error("Wrong type of descriptor");
766       if (td!=null)
767         if (!typeutil.isSuperorType(td,nn.getType()))
768           throw new Error("Field node returns "+nn.getType()+", but need "+td);
769     }
770   }
771
772   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
773     TypeDescriptor ltd=ofn.td;
774     checkTypeDescriptor(ltd);
775     
776     String fieldname = ofn.fieldname;
777     FieldDescriptor fd=null;
778     if (ltd.isArray()&&fieldname.equals("length")) {
779       fd=FieldDescriptor.arrayLength;
780     } else {
781       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
782     }
783
784     ofn.setField(fd);
785     checkField(ltd.getClassDesc(), fd);
786
787     if (fd==null)
788       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
789
790     if (td!=null) {
791       if (!typeutil.isSuperorType(td, ofn.getType())) {
792         System.out.println(td);
793         System.out.println(ofn.getType());
794         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
795       }
796     }
797   }
798
799
800   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
801     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
802     checkExpressionNode(md, nametable, tn.getTrueExpr(), td );
803     checkExpressionNode(md, nametable, tn.getFalseExpr(), td );
804   }
805
806   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
807     if (td!=null&&!td.isBoolean())
808       throw new Error("Expecting type "+td+"for instanceof expression");
809     
810     checkTypeDescriptor(tn.getExprType());
811     checkExpressionNode(md, nametable, tn.getExpr(), null);
812   }
813
814   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
815     Vector<TypeDescriptor> vec_type = new Vector<TypeDescriptor>();
816     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
817       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td==null?td:td.dereference());
818       vec_type.add(ain.getVarInitializer(i).getType());
819     }
820     // descide the type of this variableInitializerNode
821     TypeDescriptor out_type = vec_type.elementAt(0);
822     for(int i = 1; i < vec_type.size(); i++) {
823       TypeDescriptor tmp_type = vec_type.elementAt(i);
824       if(out_type == null) {
825         if(tmp_type != null) {
826           out_type = tmp_type;
827         }
828       } else if(out_type.isNull()) {
829         if(!tmp_type.isNull() ) {
830           if(!tmp_type.isArray()) {
831             throw new Error("Error: mixed type in var initializer list");
832           } else {
833             out_type = tmp_type;
834           }
835         }
836       } else if(out_type.isArray()) {
837         if(tmp_type.isArray()) {
838           if(tmp_type.getArrayCount() > out_type.getArrayCount()) {
839             out_type = tmp_type;
840           }
841         } else if((tmp_type != null) && (!tmp_type.isNull())) {
842           throw new Error("Error: mixed type in var initializer list");
843         }
844       } else if(out_type.isInt()) {
845         if(!tmp_type.isInt()) {
846           throw new Error("Error: mixed type in var initializer list");
847         }
848       } else if(out_type.isString()) {
849         if(!tmp_type.isString()) {
850           throw new Error("Error: mixed type in var initializer list");
851         }
852       }
853     }
854     if(out_type != null) {
855       out_type = out_type.makeArray(state);
856     }
857     ain.setType(out_type);
858   }
859
860   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
861     boolean postinc=true;
862     if (an.getOperation().getBaseOp()==null||
863         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
864          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
865       postinc=false;
866     if (!postinc)      
867       checkExpressionNode(md, nametable, an.getSrc(),td);
868     //TODO: Need check on validity of operation here
869     if (!((an.getDest() instanceof FieldAccessNode)||
870           (an.getDest() instanceof ArrayAccessNode)||
871           (an.getDest() instanceof NameNode)))
872       throw new Error("Bad lside in "+an.printNode(0));
873     checkExpressionNode(md, nametable, an.getDest(), null);
874
875     /* We want parameter variables to tasks to be immutable */
876     if (md instanceof TaskDescriptor) {
877       if (an.getDest() instanceof NameNode) {
878         NameNode nn=(NameNode)an.getDest();
879         if (nn.getVar()!=null) {
880           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
881             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
882         }
883       }
884     }
885
886     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
887       //String add
888       ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
889       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
890       NameDescriptor nd=new NameDescriptor("String");
891       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
892
893       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
894         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
895         rightmin.addArgument(an.getSrc());
896         an.right=rightmin;
897         checkExpressionNode(md, nametable, an.getSrc(), null);
898       }
899     }
900
901     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
902       TypeDescriptor dt = an.getDest().getType();
903       TypeDescriptor st = an.getSrc().getType();
904       Long l = an.getSrc().evaluate();
905       if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) 
906           && (l != null) 
907           && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
908         long lnvalue = l.longValue();
909         if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128))) 
910             || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
911             || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
912             || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
913             || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
914           throw new Error("Field node returns "+st+", but need "+dt+" in "+md);
915         }
916       } else {
917         throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
918       }
919     }
920   }
921
922   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
923       loopstack.push(ln);
924     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
925       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
926       checkBlockNode(md, nametable, ln.getBody());
927     } else {
928       //For loop case
929       /* Link in the initializer naming environment */
930       BlockNode bn=ln.getInitializer();
931       bn.getVarTable().setParent(nametable);
932       for(int i=0; i<bn.size(); i++) {
933         BlockStatementNode bsn=bn.get(i);
934         checkBlockStatementNode(md, bn.getVarTable(),bsn);
935       }
936       //check the condition
937       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
938       checkBlockNode(md, bn.getVarTable(), ln.getBody());
939       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
940     }
941     loopstack.pop();
942   }
943
944
945   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con, TypeDescriptor td) {
946     TypeDescriptor[] tdarray=new TypeDescriptor[con.numArgs()];
947     for(int i=0; i<con.numArgs(); i++) {
948       ExpressionNode en=con.getArg(i);
949       checkExpressionNode(md,nametable,en,null);
950       tdarray[i]=en.getType();
951     }
952
953     TypeDescriptor typetolookin=con.getType();
954     checkTypeDescriptor(typetolookin);
955
956     if (td!=null&&!typeutil.isSuperorType(td, typetolookin))
957       throw new Error(typetolookin + " isn't a "+td);
958     
959     /* Check Array Initializers */
960     if(state.MGC && (con.getArrayInitializer() != null)) {
961       checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), td);
962     }
963
964     /* Check flag effects */
965     if (con.getFlagEffects()!=null) {
966       FlagEffects fe=con.getFlagEffects();
967       ClassDescriptor cd=typetolookin.getClassDesc();
968
969       for(int j=0; j<fe.numEffects(); j++) {
970         FlagEffect flag=fe.getEffect(j);
971         String name=flag.getName();
972         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
973         //Make sure the flag is declared
974         if (flag_d==null)
975           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
976         if (flag_d.getExternal())
977           throw new Error("Attempting to modify external flag: "+name);
978         flag.setFlag(flag_d);
979       }
980       for(int j=0; j<fe.numTagEffects(); j++) {
981         TagEffect tag=fe.getTagEffect(j);
982         String name=tag.getName();
983
984         Descriptor d=(Descriptor)nametable.get(name);
985         if (d==null)
986           throw new Error("Tag descriptor "+name+" undeclared");
987         else if (!(d instanceof TagVarDescriptor))
988           throw new Error(name+" is not a tag descriptor");
989         tag.setTag((TagVarDescriptor)d);
990       }
991     }
992
993     if ((!typetolookin.isClass())&&(!typetolookin.isArray()))
994       throw new Error("Can't allocate primitive type:"+con.printNode(0));
995
996     if (!typetolookin.isArray()) {
997       //Array's don't need constructor calls
998       ClassDescriptor classtolookin=typetolookin.getClassDesc();
999
1000       Set methoddescriptorset=classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
1001       MethodDescriptor bestmd=null;
1002 NextMethod:
1003       for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
1004         MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1005         /* Need correct number of parameters */
1006         if (con.numArgs()!=currmd.numParameters())
1007           continue;
1008         for(int i=0; i<con.numArgs(); i++) {
1009           if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1010             continue NextMethod;
1011         }
1012         /* Local allocations can't call global allocator */
1013         if (!con.isGlobal()&&currmd.isGlobal())
1014           continue;
1015
1016         /* Method okay so far */
1017         if (bestmd==null)
1018           bestmd=currmd;
1019         else {
1020           if (typeutil.isMoreSpecific(currmd,bestmd)) {
1021             bestmd=currmd;
1022           } else if (con.isGlobal()&&match(currmd, bestmd)) {
1023             if (currmd.isGlobal()&&!bestmd.isGlobal())
1024               bestmd=currmd;
1025             else if (currmd.isGlobal()&&bestmd.isGlobal())
1026               throw new Error();
1027           } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
1028             throw new Error("No method is most specific");
1029           }
1030
1031           /* Is this more specific than bestmd */
1032         }
1033       }
1034       if (bestmd==null)
1035         throw new Error("No method found for "+con.printNode(0)+" in "+md);
1036       con.setConstructor(bestmd);
1037     }
1038   }
1039
1040
1041   /** Check to see if md1 is the same specificity as md2.*/
1042
1043   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1044     /* Checks if md1 is more specific than md2 */
1045     if (md1.numParameters()!=md2.numParameters())
1046       throw new Error();
1047     for(int i=0; i<md1.numParameters(); i++) {
1048       if (!md2.getParamType(i).equals(md1.getParamType(i)))
1049         return false;
1050     }
1051     if (!md2.getReturnType().equals(md1.getReturnType()))
1052       return false;
1053
1054     if (!md2.getClassDesc().equals(md1.getClassDesc()))
1055       return false;
1056
1057     return true;
1058   }
1059
1060
1061
1062   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd) {
1063     String id=nd.getIdentifier();
1064     NameDescriptor base=nd.getBase();
1065     if (base==null)
1066       return new NameNode(nd);
1067     else
1068       return new FieldAccessNode(translateNameDescriptorintoExpression(base),id);
1069   }
1070
1071
1072   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1073     /*Typecheck subexpressions
1074        and get types for expressions*/
1075
1076     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1077     for(int i=0; i<min.numArgs(); i++) {
1078       ExpressionNode en=min.getArg(i);
1079       checkExpressionNode(md,nametable,en,null);
1080       tdarray[i]=en.getType();
1081       if(state.MGC && en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1082         tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1083       }
1084     }
1085     TypeDescriptor typetolookin=null;
1086     if (min.getExpression()!=null) {
1087       checkExpressionNode(md,nametable,min.getExpression(),null);
1088       typetolookin=min.getExpression().getType();
1089       //if (typetolookin==null)
1090       //throw new Error(md+" has null return type");
1091
1092     } else if (min.getBaseName()!=null) {
1093       String rootname=min.getBaseName().getRoot();
1094       if (rootname.equals("super")) {
1095         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1096         typetolookin=new TypeDescriptor(supercd);
1097       } else if (nametable.get(rootname)!=null) {
1098         //we have an expression
1099         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName()));
1100         checkExpressionNode(md, nametable, min.getExpression(), null);
1101         typetolookin=min.getExpression().getType();
1102       } else {
1103         //we have a type
1104         ClassDescriptor cd;
1105         if (min.getBaseName().getSymbol().equals("System.out"))
1106           cd=getClass("System");
1107         else
1108           cd=getClass(min.getBaseName().getSymbol());
1109         if (cd==null)
1110           throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
1111         typetolookin=new TypeDescriptor(cd);
1112       }
1113     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1114       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1115       min.methodid=supercd.getSymbol();
1116       typetolookin=new TypeDescriptor(supercd);
1117     } else if (md instanceof MethodDescriptor) {
1118       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1119     } else {
1120       /* If this a task descriptor we throw an error at this point */
1121       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1122     }
1123     if (!typetolookin.isClass())
1124       throw new Error("Error with method call to "+min.getMethodName());
1125     ClassDescriptor classtolookin=typetolookin.getClassDesc();
1126     //System.out.println("Method name="+min.getMethodName());
1127
1128     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1129     MethodDescriptor bestmd=null;
1130 NextMethod:
1131     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
1132       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1133       /* Need correct number of parameters */
1134       if (min.numArgs()!=currmd.numParameters())
1135         continue;
1136       for(int i=0; i<min.numArgs(); i++) {
1137         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1138           continue NextMethod;
1139       }
1140       /* Method okay so far */
1141       if (bestmd==null)
1142         bestmd=currmd;
1143       else {
1144         if (typeutil.isMoreSpecific(currmd,bestmd)) {
1145           bestmd=currmd;
1146         } else if (!typeutil.isMoreSpecific(bestmd, currmd))
1147           throw new Error("No method is most specific");
1148
1149         /* Is this more specific than bestmd */
1150       }
1151     }
1152     if (bestmd==null)
1153       throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1154     min.setMethod(bestmd);
1155
1156     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
1157       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1158     /* Check whether we need to set this parameter to implied this */
1159     if (!bestmd.isStatic()) {
1160       if (min.getExpression()==null) {
1161         ExpressionNode en=new NameNode(new NameDescriptor("this"));
1162         min.setExpression(en);
1163         checkExpressionNode(md, nametable, min.getExpression(), null);
1164       }
1165     }
1166   }
1167
1168
1169   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1170     checkExpressionNode(md, nametable, on.getLeft(), null);
1171     if (on.getRight()!=null)
1172       checkExpressionNode(md, nametable, on.getRight(), null);
1173     TypeDescriptor ltd=on.getLeft().getType();
1174     TypeDescriptor rtd=on.getRight()!=null ? on.getRight().getType() : null;
1175     TypeDescriptor lefttype=null;
1176     TypeDescriptor righttype=null;
1177     Operation op=on.getOp();
1178
1179     switch(op.getOp()) {
1180     case Operation.LOGIC_OR:
1181     case Operation.LOGIC_AND:
1182       if (!(rtd.isBoolean()))
1183         throw new Error();
1184       on.setRightType(rtd);
1185
1186     case Operation.LOGIC_NOT:
1187       if (!(ltd.isBoolean()))
1188         throw new Error();
1189       //no promotion
1190       on.setLeftType(ltd);
1191
1192       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1193       break;
1194
1195     case Operation.COMP:
1196       // 5.6.2 Binary Numeric Promotion
1197       //TODO unboxing of reference objects
1198       if (ltd.isDouble())
1199         throw new Error();
1200       else if (ltd.isFloat())
1201         throw new Error();
1202       else if (ltd.isLong())
1203         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1204       else
1205         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1206       on.setLeftType(lefttype);
1207       on.setType(lefttype);
1208       break;
1209
1210     case Operation.BIT_OR:
1211     case Operation.BIT_XOR:
1212     case Operation.BIT_AND:
1213       // 5.6.2 Binary Numeric Promotion
1214       //TODO unboxing of reference objects
1215       if (ltd.isDouble()||rtd.isDouble())
1216         throw new Error();
1217       else if (ltd.isFloat()||rtd.isFloat())
1218         throw new Error();
1219       else if (ltd.isLong()||rtd.isLong())
1220         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1221       // 090205 hack for boolean
1222       else if (ltd.isBoolean()||rtd.isBoolean())
1223         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1224       else
1225         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1226       righttype=lefttype;
1227
1228       on.setLeftType(lefttype);
1229       on.setRightType(righttype);
1230       on.setType(lefttype);
1231       break;
1232
1233     case Operation.ISAVAILABLE:
1234       if (!(ltd.isPtr())) {
1235         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1236       }
1237       lefttype=ltd;
1238       on.setLeftType(lefttype);
1239       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1240       break;
1241
1242     case Operation.EQUAL:
1243     case Operation.NOTEQUAL:
1244       // 5.6.2 Binary Numeric Promotion
1245       //TODO unboxing of reference objects
1246       if (ltd.isBoolean()||rtd.isBoolean()) {
1247         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1248           throw new Error();
1249         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1250       } else if (ltd.isPtr()||rtd.isPtr()) {
1251         if (!(ltd.isPtr()&&rtd.isPtr()))
1252           throw new Error();
1253         righttype=rtd;
1254         lefttype=ltd;
1255       } else if (ltd.isDouble()||rtd.isDouble())
1256         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1257       else if (ltd.isFloat()||rtd.isFloat())
1258         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1259       else if (ltd.isLong()||rtd.isLong())
1260         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1261       else
1262         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1263
1264       on.setLeftType(lefttype);
1265       on.setRightType(righttype);
1266       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1267       break;
1268
1269
1270
1271     case Operation.LT:
1272     case Operation.GT:
1273     case Operation.LTE:
1274     case Operation.GTE:
1275       // 5.6.2 Binary Numeric Promotion
1276       //TODO unboxing of reference objects
1277       if (!ltd.isNumber()||!rtd.isNumber()) {
1278         if (!ltd.isNumber())
1279           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1280         if (!rtd.isNumber())
1281           throw new Error("Rightside is not number"+on.printNode(0));
1282       }
1283
1284       if (ltd.isDouble()||rtd.isDouble())
1285         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1286       else if (ltd.isFloat()||rtd.isFloat())
1287         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1288       else if (ltd.isLong()||rtd.isLong())
1289         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1290       else
1291         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1292       righttype=lefttype;
1293       on.setLeftType(lefttype);
1294       on.setRightType(righttype);
1295       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1296       break;
1297
1298     case Operation.ADD:
1299       if (ltd.isString()||rtd.isString()) {
1300         ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
1301         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1302         NameDescriptor nd=new NameDescriptor("String");
1303         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1304         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1305           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1306           leftmin.addArgument(on.getLeft());
1307           on.left=leftmin;
1308           checkExpressionNode(md, nametable, on.getLeft(), null);
1309         }
1310
1311         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1312           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1313           rightmin.addArgument(on.getRight());
1314           on.right=rightmin;
1315           checkExpressionNode(md, nametable, on.getRight(), null);
1316         }
1317
1318         on.setLeftType(stringtd);
1319         on.setRightType(stringtd);
1320         on.setType(stringtd);
1321         break;
1322       }
1323
1324     case Operation.SUB:
1325     case Operation.MULT:
1326     case Operation.DIV:
1327     case Operation.MOD:
1328       // 5.6.2 Binary Numeric Promotion
1329       //TODO unboxing of reference objects
1330       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1331         throw new Error("Error in "+on.printNode(0));
1332
1333       if (ltd.isDouble()||rtd.isDouble())
1334         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1335       else if (ltd.isFloat()||rtd.isFloat())
1336         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1337       else if (ltd.isLong()||rtd.isLong())
1338         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1339       else
1340         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1341       righttype=lefttype;
1342       on.setLeftType(lefttype);
1343       on.setRightType(righttype);
1344       on.setType(lefttype);
1345       break;
1346
1347     case Operation.LEFTSHIFT:
1348     case Operation.RIGHTSHIFT:
1349     case Operation.URIGHTSHIFT:
1350       if (!rtd.isIntegerType())
1351         throw new Error();
1352       //5.6.1 Unary Numeric Promotion
1353       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1354         righttype=new TypeDescriptor(TypeDescriptor.INT);
1355       else
1356         righttype=rtd;
1357
1358       on.setRightType(righttype);
1359       if (!ltd.isIntegerType())
1360         throw new Error();
1361
1362     case Operation.UNARYPLUS:
1363     case Operation.UNARYMINUS:
1364       /*        case Operation.POSTINC:
1365           case Operation.POSTDEC:
1366           case Operation.PREINC:
1367           case Operation.PREDEC:*/
1368       if (!ltd.isNumber())
1369         throw new Error();
1370       //5.6.1 Unary Numeric Promotion
1371       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1372         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1373       else
1374         lefttype=ltd;
1375       on.setLeftType(lefttype);
1376       on.setType(lefttype);
1377       break;
1378
1379     default:
1380       throw new Error(op.toString());
1381     }
1382
1383     if (td!=null)
1384       if (!typeutil.isSuperorType(td, on.getType())) {
1385         System.out.println(td);
1386         System.out.println(on.getType());
1387         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1388       }
1389   }
1390 }