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