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