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