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