two methods for generating a reach graph at any desired program point, one is a dummy...
[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.SynchronizedNode:
300       checkSynchronizedNode(md, nametable, (SynchronizedNode)bsn);
301       return;
302
303     case Kind.ContinueBreakNode:
304         checkContinueBreakNode(md, nametable, (ContinueBreakNode) bsn);
305         return;
306
307     case Kind.SESENode:
308     case Kind.GenReachNode:
309       // do nothing, no semantic check for SESEs
310       return;
311     }
312
313     throw new Error();
314   }
315
316   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
317     checkExpressionNode(md, nametable, ben.getExpression(), null);
318   }
319
320   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
321     VarDescriptor vd=dn.getVarDescriptor();
322     checkTypeDescriptor(vd.getType());
323     Descriptor d=nametable.get(vd.getSymbol());
324     if ((d==null)||
325         (d instanceof FieldDescriptor)) {
326       nametable.add(vd);
327     } else
328       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
329     if (dn.getExpression()!=null)
330       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
331   }
332
333   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
334     TagVarDescriptor vd=dn.getTagVarDescriptor();
335     Descriptor d=nametable.get(vd.getSymbol());
336     if ((d==null)||
337         (d instanceof FieldDescriptor)) {
338       nametable.add(vd);
339     } else
340       throw new Error(vd.getSymbol()+" defined a second time");
341   }
342
343   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
344     checkBlockNode(md, nametable, sbn.getBlockNode());
345   }
346
347   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
348     checkBlockNode(md, nametable, sbn.getBlockNode());
349   }
350
351   void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
352     checkBlockNode(md, nametable, sbn.getBlockNode());
353     //todo this could be Object
354     checkExpressionNode(md, nametable, sbn.getExpr(), null);
355   }
356
357   void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
358       if (loopstack.empty())
359           throw new Error("continue/break outside of loop");
360       LoopNode ln=(LoopNode)loopstack.peek();
361       cbn.setLoop(ln);
362   }
363
364   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
365     if (d instanceof TaskDescriptor)
366       throw new Error("Illegal return appears in Task: "+d.getSymbol());
367     MethodDescriptor md=(MethodDescriptor)d;
368     if (rn.getReturnExpression()!=null)
369       if (md.getReturnType()==null)
370         throw new Error("Constructor can't return something.");
371       else if (md.getReturnType().isVoid())
372         throw new Error(md+" is void");
373       else
374         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
375     else
376     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
377       throw new Error("Need to return something for "+md);
378   }
379
380   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
381     if (md instanceof MethodDescriptor)
382       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
383     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
384     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
385   }
386
387   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
388     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
389     checkBlockNode(md, nametable, isn.getTrueBlock());
390     if (isn.getFalseBlock()!=null)
391       checkBlockNode(md, nametable, isn.getFalseBlock());
392   }
393
394   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
395     switch(en.kind()) {
396     case Kind.AssignmentNode:
397       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
398       return;
399
400     case Kind.CastNode:
401       checkCastNode(md,nametable,(CastNode)en,td);
402       return;
403
404     case Kind.CreateObjectNode:
405       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
406       return;
407
408     case Kind.FieldAccessNode:
409       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
410       return;
411
412     case Kind.ArrayAccessNode:
413       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
414       return;
415
416     case Kind.LiteralNode:
417       checkLiteralNode(md,nametable,(LiteralNode)en,td);
418       return;
419
420     case Kind.MethodInvokeNode:
421       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
422       return;
423
424     case Kind.NameNode:
425       checkNameNode(md,nametable,(NameNode)en,td);
426       return;
427
428     case Kind.OpNode:
429       checkOpNode(md,nametable,(OpNode)en,td);
430       return;
431
432     case Kind.OffsetNode:
433       checkOffsetNode(md, nametable, (OffsetNode)en, td);
434       return;
435
436     case Kind.TertiaryNode:
437       checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
438       return;
439       
440     case Kind.InstanceOfNode:
441       checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
442       return;
443
444     case Kind.ArrayInitializerNode:
445       checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
446       return;
447     }
448     throw new Error();
449   }
450
451   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
452     /* Get type descriptor */
453     if (cn.getType()==null) {
454       NameDescriptor typenamed=cn.getTypeName().getName();
455       String typename=typenamed.toString();
456       TypeDescriptor ntd=new TypeDescriptor(getClass(typename));
457       cn.setType(ntd);
458     }
459
460     /* Check the type descriptor */
461     TypeDescriptor cast_type=cn.getType();
462     checkTypeDescriptor(cast_type);
463
464     /* Type check */
465     if (td!=null) {
466       if (!typeutil.isSuperorType(td,cast_type))
467         throw new Error("Cast node returns "+cast_type+", but need "+td);
468     }
469
470     ExpressionNode en=cn.getExpression();
471     checkExpressionNode(md, nametable, en, null);
472     TypeDescriptor etd=en.getType();
473     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
474       return;
475
476     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
477       return;
478     if (typeutil.isCastable(etd, cast_type))
479       return;
480
481     /* Different branches */
482     /* TODO: change if add interfaces */
483     throw new Error("Cast will always fail\n"+cn.printNode(0));
484   }
485
486   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
487     ExpressionNode left=fan.getExpression();
488     checkExpressionNode(md,nametable,left,null);
489     TypeDescriptor ltd=left.getType();
490     String fieldname=fan.getFieldName();
491
492     FieldDescriptor fd=null;
493     if (ltd.isArray()&&fieldname.equals("length"))
494       fd=FieldDescriptor.arrayLength;
495     else
496       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
497     if (fd==null)
498       throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
499
500     if (fd.getType().iswrapper()) {
501       FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
502       fan2.setField(fd);
503       fan.left=fan2;
504       fan.fieldname="value";
505
506       ExpressionNode leftwr=fan.getExpression();
507       TypeDescriptor ltdwr=leftwr.getType();
508       String fieldnamewr=fan.getFieldName();
509       FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
510       fan.setField(fdwr);
511       if (fdwr==null)
512           throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
513     } else {
514       fan.setField(fd);
515     }
516     if (td!=null) {
517       if (!typeutil.isSuperorType(td,fan.getType()))
518         throw new Error("Field node returns "+fan.getType()+", but need "+td);
519     }
520   }
521
522   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
523     ExpressionNode left=aan.getExpression();
524     checkExpressionNode(md,nametable,left,null);
525
526     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
527     TypeDescriptor ltd=left.getType();
528     if (ltd.dereference().iswrapper()) {
529       aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
530     }
531
532     if (td!=null)
533       if (!typeutil.isSuperorType(td,aan.getType()))
534         throw new Error("Field node returns "+aan.getType()+", but need "+td);
535   }
536
537   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
538     /* Resolve the type */
539     Object o=ln.getValue();
540     if (ln.getTypeString().equals("null")) {
541       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
542     } else if (o instanceof Integer) {
543       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
544     } else if (o instanceof Long) {
545       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
546     } else if (o instanceof Float) {
547       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
548     } else if (o instanceof Boolean) {
549       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
550     } else if (o instanceof Double) {
551       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
552     } else if (o instanceof Character) {
553       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
554     } else if (o instanceof String) {
555       ln.setType(new TypeDescriptor(getClass(TypeUtil.StringClass)));
556     }
557
558     if (td!=null)
559       if (!typeutil.isSuperorType(td,ln.getType()))
560         throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
561   }
562
563   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
564     NameDescriptor nd=nn.getName();
565     if (nd.getBase()!=null) {
566       /* Big hack */
567       /* Rewrite NameNode */
568       ExpressionNode en=translateNameDescriptorintoExpression(nd);
569       nn.setExpression(en);
570       checkExpressionNode(md,nametable,en,td);
571     } else {
572       String varname=nd.toString();
573       Descriptor d=(Descriptor)nametable.get(varname);
574       if (d==null) {
575         throw new Error("Name "+varname+" undefined in: "+md);
576       }
577       if (d instanceof VarDescriptor) {
578         nn.setVar(d);
579       } else if (d instanceof FieldDescriptor) {
580         FieldDescriptor fd=(FieldDescriptor)d;
581         if (fd.getType().iswrapper()) {
582           String id=nd.getIdentifier();
583           NameDescriptor base=nd.getBase();
584           NameNode n=new NameNode(nn.getName());
585           n.setField(fd);
586           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
587           FieldAccessNode fan=new FieldAccessNode(n,"value");
588           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
589           fan.setField(fdval);
590           nn.setExpression(fan);
591         } else {
592           nn.setField(fd);
593           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
594         }
595       } else if (d instanceof TagVarDescriptor) {
596         nn.setVar(d);
597       } else throw new Error("Wrong type of descriptor");
598       if (td!=null)
599         if (!typeutil.isSuperorType(td,nn.getType()))
600           throw new Error("Field node returns "+nn.getType()+", but need "+td);
601     }
602   }
603
604   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
605     TypeDescriptor ltd=ofn.td;
606     checkTypeDescriptor(ltd);
607     
608     String fieldname = ofn.fieldname;
609     FieldDescriptor fd=null;
610     if (ltd.isArray()&&fieldname.equals("length")) {
611       fd=FieldDescriptor.arrayLength;
612     } else {
613       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
614     }
615
616     ofn.setField(fd);
617     checkField(ltd.getClassDesc(), fd);
618
619     if (fd==null)
620       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
621
622     if (td!=null) {
623       if (!typeutil.isSuperorType(td, ofn.getType())) {
624         System.out.println(td);
625         System.out.println(ofn.getType());
626         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
627       }
628     }
629   }
630
631
632   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
633     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
634     checkExpressionNode(md, nametable, tn.getTrueExpr(), td );
635     checkExpressionNode(md, nametable, tn.getFalseExpr(), td );
636   }
637
638   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
639     if (td!=null&&!td.isBoolean())
640       throw new Error("Expecting type "+td+"for instanceof expression");
641     
642     checkTypeDescriptor(tn.getExprType());
643     checkExpressionNode(md, nametable, tn.getExpr(), null);
644   }
645
646   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
647     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
648       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td); 
649     }
650   }
651
652   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
653     boolean postinc=true;
654     if (an.getOperation().getBaseOp()==null||
655         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
656          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
657       postinc=false;
658     if (!postinc)      
659       checkExpressionNode(md, nametable, an.getSrc(),td);
660     //TODO: Need check on validity of operation here
661     if (!((an.getDest() instanceof FieldAccessNode)||
662           (an.getDest() instanceof ArrayAccessNode)||
663           (an.getDest() instanceof NameNode)))
664       throw new Error("Bad lside in "+an.printNode(0));
665     checkExpressionNode(md, nametable, an.getDest(), null);
666
667     /* We want parameter variables to tasks to be immutable */
668     if (md instanceof TaskDescriptor) {
669       if (an.getDest() instanceof NameNode) {
670         NameNode nn=(NameNode)an.getDest();
671         if (nn.getVar()!=null) {
672           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
673             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
674         }
675       }
676     }
677
678     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
679       //String add
680       ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
681       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
682       NameDescriptor nd=new NameDescriptor("String");
683       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
684
685       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
686         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
687         rightmin.addArgument(an.getSrc());
688         an.right=rightmin;
689         checkExpressionNode(md, nametable, an.getSrc(), null);
690       }
691     }
692
693     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
694       throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
695     }
696   }
697
698   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
699       loopstack.push(ln);
700     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
701       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
702       checkBlockNode(md, nametable, ln.getBody());
703     } else {
704       //For loop case
705       /* Link in the initializer naming environment */
706       BlockNode bn=ln.getInitializer();
707       bn.getVarTable().setParent(nametable);
708       for(int i=0; i<bn.size(); i++) {
709         BlockStatementNode bsn=bn.get(i);
710         checkBlockStatementNode(md, bn.getVarTable(),bsn);
711       }
712       //check the condition
713       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
714       checkBlockNode(md, bn.getVarTable(), ln.getBody());
715       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
716     }
717     loopstack.pop();
718   }
719
720
721   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con, TypeDescriptor td) {
722     TypeDescriptor[] tdarray=new TypeDescriptor[con.numArgs()];
723     for(int i=0; i<con.numArgs(); i++) {
724       ExpressionNode en=con.getArg(i);
725       checkExpressionNode(md,nametable,en,null);
726       tdarray[i]=en.getType();
727     }
728
729     TypeDescriptor typetolookin=con.getType();
730     checkTypeDescriptor(typetolookin);
731
732     if (td!=null&&!typeutil.isSuperorType(td, typetolookin))
733       throw new Error(typetolookin + " isn't a "+td);
734
735     /* Check flag effects */
736     if (con.getFlagEffects()!=null) {
737       FlagEffects fe=con.getFlagEffects();
738       ClassDescriptor cd=typetolookin.getClassDesc();
739
740       for(int j=0; j<fe.numEffects(); j++) {
741         FlagEffect flag=fe.getEffect(j);
742         String name=flag.getName();
743         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
744         //Make sure the flag is declared
745         if (flag_d==null)
746           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
747         if (flag_d.getExternal())
748           throw new Error("Attempting to modify external flag: "+name);
749         flag.setFlag(flag_d);
750       }
751       for(int j=0; j<fe.numTagEffects(); j++) {
752         TagEffect tag=fe.getTagEffect(j);
753         String name=tag.getName();
754
755         Descriptor d=(Descriptor)nametable.get(name);
756         if (d==null)
757           throw new Error("Tag descriptor "+name+" undeclared");
758         else if (!(d instanceof TagVarDescriptor))
759           throw new Error(name+" is not a tag descriptor");
760         tag.setTag((TagVarDescriptor)d);
761       }
762     }
763
764     if ((!typetolookin.isClass())&&(!typetolookin.isArray()))
765       throw new Error("Can't allocate primitive type:"+con.printNode(0));
766
767     if (!typetolookin.isArray()) {
768       //Array's don't need constructor calls
769       ClassDescriptor classtolookin=typetolookin.getClassDesc();
770
771       Set methoddescriptorset=classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
772       MethodDescriptor bestmd=null;
773 NextMethod:
774       for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
775         MethodDescriptor currmd=(MethodDescriptor)methodit.next();
776         /* Need correct number of parameters */
777         if (con.numArgs()!=currmd.numParameters())
778           continue;
779         for(int i=0; i<con.numArgs(); i++) {
780           if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
781             continue NextMethod;
782         }
783         /* Local allocations can't call global allocator */
784         if (!con.isGlobal()&&currmd.isGlobal())
785           continue;
786
787         /* Method okay so far */
788         if (bestmd==null)
789           bestmd=currmd;
790         else {
791           if (typeutil.isMoreSpecific(currmd,bestmd)) {
792             bestmd=currmd;
793           } else if (con.isGlobal()&&match(currmd, bestmd)) {
794             if (currmd.isGlobal()&&!bestmd.isGlobal())
795               bestmd=currmd;
796             else if (currmd.isGlobal()&&bestmd.isGlobal())
797               throw new Error();
798           } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
799             throw new Error("No method is most specific");
800           }
801
802           /* Is this more specific than bestmd */
803         }
804       }
805       if (bestmd==null)
806         throw new Error("No method found for "+con.printNode(0)+" in "+md);
807       con.setConstructor(bestmd);
808     }
809   }
810
811
812   /** Check to see if md1 is the same specificity as md2.*/
813
814   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
815     /* Checks if md1 is more specific than md2 */
816     if (md1.numParameters()!=md2.numParameters())
817       throw new Error();
818     for(int i=0; i<md1.numParameters(); i++) {
819       if (!md2.getParamType(i).equals(md1.getParamType(i)))
820         return false;
821     }
822     if (!md2.getReturnType().equals(md1.getReturnType()))
823       return false;
824
825     if (!md2.getClassDesc().equals(md1.getClassDesc()))
826       return false;
827
828     return true;
829   }
830
831
832
833   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd) {
834     String id=nd.getIdentifier();
835     NameDescriptor base=nd.getBase();
836     if (base==null)
837       return new NameNode(nd);
838     else
839       return new FieldAccessNode(translateNameDescriptorintoExpression(base),id);
840   }
841
842
843   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
844     /*Typecheck subexpressions
845        and get types for expressions*/
846
847     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
848     for(int i=0; i<min.numArgs(); i++) {
849       ExpressionNode en=min.getArg(i);
850       checkExpressionNode(md,nametable,en,null);
851       tdarray[i]=en.getType();
852     }
853     TypeDescriptor typetolookin=null;
854     if (min.getExpression()!=null) {
855       checkExpressionNode(md,nametable,min.getExpression(),null);
856       typetolookin=min.getExpression().getType();
857       //if (typetolookin==null)
858       //throw new Error(md+" has null return type");
859
860     } else if (min.getBaseName()!=null) {
861       String rootname=min.getBaseName().getRoot();
862       if (rootname.equals("super")) {
863         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
864         typetolookin=new TypeDescriptor(supercd);
865       } else if (nametable.get(rootname)!=null) {
866         //we have an expression
867         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName()));
868         checkExpressionNode(md, nametable, min.getExpression(), null);
869         typetolookin=min.getExpression().getType();
870       } else {
871         //we have a type
872         ClassDescriptor cd;
873         if (min.getBaseName().getSymbol().equals("System.out"))
874           cd=getClass("System");
875         else
876           cd=getClass(min.getBaseName().getSymbol());
877         if (cd==null)
878           throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
879         typetolookin=new TypeDescriptor(cd);
880       }
881     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
882       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
883       min.methodid=supercd.getSymbol();
884       typetolookin=new TypeDescriptor(supercd);
885     } else if (md instanceof MethodDescriptor) {
886       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
887     } else {
888       /* If this a task descriptor we throw an error at this point */
889       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
890     }
891     if (!typetolookin.isClass())
892       throw new Error("Error with method call to "+min.getMethodName());
893     ClassDescriptor classtolookin=typetolookin.getClassDesc();
894     //System.out.println("Method name="+min.getMethodName());
895
896     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
897     MethodDescriptor bestmd=null;
898 NextMethod:
899     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
900       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
901       /* Need correct number of parameters */
902       if (min.numArgs()!=currmd.numParameters())
903         continue;
904       for(int i=0; i<min.numArgs(); i++) {
905         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
906           continue NextMethod;
907       }
908       /* Method okay so far */
909       if (bestmd==null)
910         bestmd=currmd;
911       else {
912         if (typeutil.isMoreSpecific(currmd,bestmd)) {
913           bestmd=currmd;
914         } else if (!typeutil.isMoreSpecific(bestmd, currmd))
915           throw new Error("No method is most specific");
916
917         /* Is this more specific than bestmd */
918       }
919     }
920     if (bestmd==null)
921       throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
922     min.setMethod(bestmd);
923
924     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
925       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
926     /* Check whether we need to set this parameter to implied this */
927     if (!bestmd.isStatic()) {
928       if (min.getExpression()==null) {
929         ExpressionNode en=new NameNode(new NameDescriptor("this"));
930         min.setExpression(en);
931         checkExpressionNode(md, nametable, min.getExpression(), null);
932       }
933     }
934   }
935
936
937   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
938     checkExpressionNode(md, nametable, on.getLeft(), null);
939     if (on.getRight()!=null)
940       checkExpressionNode(md, nametable, on.getRight(), null);
941     TypeDescriptor ltd=on.getLeft().getType();
942     TypeDescriptor rtd=on.getRight()!=null ? on.getRight().getType() : null;
943     TypeDescriptor lefttype=null;
944     TypeDescriptor righttype=null;
945     Operation op=on.getOp();
946
947     switch(op.getOp()) {
948     case Operation.LOGIC_OR:
949     case Operation.LOGIC_AND:
950       if (!(rtd.isBoolean()))
951         throw new Error();
952       on.setRightType(rtd);
953
954     case Operation.LOGIC_NOT:
955       if (!(ltd.isBoolean()))
956         throw new Error();
957       //no promotion
958       on.setLeftType(ltd);
959
960       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
961       break;
962
963     case Operation.COMP:
964       // 5.6.2 Binary Numeric Promotion
965       //TODO unboxing of reference objects
966       if (ltd.isDouble())
967         throw new Error();
968       else if (ltd.isFloat())
969         throw new Error();
970       else if (ltd.isLong())
971         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
972       else
973         lefttype=new TypeDescriptor(TypeDescriptor.INT);
974       on.setLeftType(lefttype);
975       on.setType(lefttype);
976       break;
977
978     case Operation.BIT_OR:
979     case Operation.BIT_XOR:
980     case Operation.BIT_AND:
981       // 5.6.2 Binary Numeric Promotion
982       //TODO unboxing of reference objects
983       if (ltd.isDouble()||rtd.isDouble())
984         throw new Error();
985       else if (ltd.isFloat()||rtd.isFloat())
986         throw new Error();
987       else if (ltd.isLong()||rtd.isLong())
988         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
989       // 090205 hack for boolean
990       else if (ltd.isBoolean()||rtd.isBoolean())
991         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
992       else
993         lefttype=new TypeDescriptor(TypeDescriptor.INT);
994       righttype=lefttype;
995
996       on.setLeftType(lefttype);
997       on.setRightType(righttype);
998       on.setType(lefttype);
999       break;
1000
1001     case Operation.ISAVAILABLE:
1002       if (!(ltd.isPtr())) {
1003         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1004       }
1005       lefttype=ltd;
1006       on.setLeftType(lefttype);
1007       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1008       break;
1009
1010     case Operation.EQUAL:
1011     case Operation.NOTEQUAL:
1012       // 5.6.2 Binary Numeric Promotion
1013       //TODO unboxing of reference objects
1014       if (ltd.isBoolean()||rtd.isBoolean()) {
1015         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1016           throw new Error();
1017         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1018       } else if (ltd.isPtr()||rtd.isPtr()) {
1019         if (!(ltd.isPtr()&&rtd.isPtr()))
1020           throw new Error();
1021         righttype=rtd;
1022         lefttype=ltd;
1023       } else if (ltd.isDouble()||rtd.isDouble())
1024         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1025       else if (ltd.isFloat()||rtd.isFloat())
1026         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1027       else if (ltd.isLong()||rtd.isLong())
1028         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1029       else
1030         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1031
1032       on.setLeftType(lefttype);
1033       on.setRightType(righttype);
1034       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1035       break;
1036
1037
1038
1039     case Operation.LT:
1040     case Operation.GT:
1041     case Operation.LTE:
1042     case Operation.GTE:
1043       // 5.6.2 Binary Numeric Promotion
1044       //TODO unboxing of reference objects
1045       if (!ltd.isNumber()||!rtd.isNumber()) {
1046         if (!ltd.isNumber())
1047           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1048         if (!rtd.isNumber())
1049           throw new Error("Rightside is not number"+on.printNode(0));
1050       }
1051
1052       if (ltd.isDouble()||rtd.isDouble())
1053         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1054       else if (ltd.isFloat()||rtd.isFloat())
1055         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1056       else if (ltd.isLong()||rtd.isLong())
1057         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1058       else
1059         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1060       righttype=lefttype;
1061       on.setLeftType(lefttype);
1062       on.setRightType(righttype);
1063       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1064       break;
1065
1066     case Operation.ADD:
1067       if (ltd.isString()||rtd.isString()) {
1068         ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
1069         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1070         NameDescriptor nd=new NameDescriptor("String");
1071         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1072         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1073           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1074           leftmin.addArgument(on.getLeft());
1075           on.left=leftmin;
1076           checkExpressionNode(md, nametable, on.getLeft(), null);
1077         }
1078
1079         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1080           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1081           rightmin.addArgument(on.getRight());
1082           on.right=rightmin;
1083           checkExpressionNode(md, nametable, on.getRight(), null);
1084         }
1085
1086         on.setLeftType(stringtd);
1087         on.setRightType(stringtd);
1088         on.setType(stringtd);
1089         break;
1090       }
1091
1092     case Operation.SUB:
1093     case Operation.MULT:
1094     case Operation.DIV:
1095     case Operation.MOD:
1096       // 5.6.2 Binary Numeric Promotion
1097       //TODO unboxing of reference objects
1098       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1099         throw new Error("Error in "+on.printNode(0));
1100
1101       if (ltd.isDouble()||rtd.isDouble())
1102         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1103       else if (ltd.isFloat()||rtd.isFloat())
1104         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1105       else if (ltd.isLong()||rtd.isLong())
1106         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1107       else
1108         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1109       righttype=lefttype;
1110       on.setLeftType(lefttype);
1111       on.setRightType(righttype);
1112       on.setType(lefttype);
1113       break;
1114
1115     case Operation.LEFTSHIFT:
1116     case Operation.RIGHTSHIFT:
1117     case Operation.URIGHTSHIFT:
1118       if (!rtd.isIntegerType())
1119         throw new Error();
1120       //5.6.1 Unary Numeric Promotion
1121       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1122         righttype=new TypeDescriptor(TypeDescriptor.INT);
1123       else
1124         righttype=rtd;
1125
1126       on.setRightType(righttype);
1127       if (!ltd.isIntegerType())
1128         throw new Error();
1129
1130     case Operation.UNARYPLUS:
1131     case Operation.UNARYMINUS:
1132       /*        case Operation.POSTINC:
1133           case Operation.POSTDEC:
1134           case Operation.PREINC:
1135           case Operation.PREDEC:*/
1136       if (!ltd.isNumber())
1137         throw new Error();
1138       //5.6.1 Unary Numeric Promotion
1139       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1140         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1141       else
1142         lefttype=ltd;
1143       on.setLeftType(lefttype);
1144       on.setType(lefttype);
1145       break;
1146
1147     default:
1148       throw new Error(op.toString());
1149     }
1150
1151     if (td!=null)
1152       if (!typeutil.isSuperorType(td, on.getType())) {
1153         System.out.println(td);
1154         System.out.println(on.getType());
1155         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1156       }
1157   }
1158 }