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