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