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