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