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