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.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       // do nothing, no semantic check for SESEs
309       return;
310     }
311
312     throw new Error();
313   }
314
315   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
316     checkExpressionNode(md, nametable, ben.getExpression(), null);
317   }
318
319   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
320     VarDescriptor vd=dn.getVarDescriptor();
321     checkTypeDescriptor(vd.getType());
322     Descriptor d=nametable.get(vd.getSymbol());
323     if ((d==null)||
324         (d instanceof FieldDescriptor)) {
325       nametable.add(vd);
326     } else
327       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
328     if (dn.getExpression()!=null)
329       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
330   }
331
332   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
333     TagVarDescriptor vd=dn.getTagVarDescriptor();
334     Descriptor d=nametable.get(vd.getSymbol());
335     if ((d==null)||
336         (d instanceof FieldDescriptor)) {
337       nametable.add(vd);
338     } else
339       throw new Error(vd.getSymbol()+" defined a second time");
340   }
341
342   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
343     checkBlockNode(md, nametable, sbn.getBlockNode());
344   }
345
346   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
347     checkBlockNode(md, nametable, sbn.getBlockNode());
348   }
349
350   void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
351     checkBlockNode(md, nametable, sbn.getBlockNode());
352     //todo this could be Object
353     checkExpressionNode(md, nametable, sbn.getExpr(), null);
354   }
355
356   void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
357       if (loopstack.empty())
358           throw new Error("continue/break outside of loop");
359       LoopNode ln=(LoopNode)loopstack.peek();
360       cbn.setLoop(ln);
361   }
362
363   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
364     if (d instanceof TaskDescriptor)
365       throw new Error("Illegal return appears in Task: "+d.getSymbol());
366     MethodDescriptor md=(MethodDescriptor)d;
367     if (rn.getReturnExpression()!=null)
368       if (md.getReturnType()==null)
369         throw new Error("Constructor can't return something.");
370       else if (md.getReturnType().isVoid())
371         throw new Error(md+" is void");
372       else
373         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
374     else
375     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
376       throw new Error("Need to return something for "+md);
377   }
378
379   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
380     if (md instanceof MethodDescriptor)
381       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
382     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
383     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
384   }
385
386   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
387     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
388     checkBlockNode(md, nametable, isn.getTrueBlock());
389     if (isn.getFalseBlock()!=null)
390       checkBlockNode(md, nametable, isn.getFalseBlock());
391   }
392
393   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
394     switch(en.kind()) {
395     case Kind.AssignmentNode:
396       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
397       return;
398
399     case Kind.CastNode:
400       checkCastNode(md,nametable,(CastNode)en,td);
401       return;
402
403     case Kind.CreateObjectNode:
404       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
405       return;
406
407     case Kind.FieldAccessNode:
408       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
409       return;
410
411     case Kind.ArrayAccessNode:
412       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
413       return;
414
415     case Kind.LiteralNode:
416       checkLiteralNode(md,nametable,(LiteralNode)en,td);
417       return;
418
419     case Kind.MethodInvokeNode:
420       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
421       return;
422
423     case Kind.NameNode:
424       checkNameNode(md,nametable,(NameNode)en,td);
425       return;
426
427     case Kind.OpNode:
428       checkOpNode(md,nametable,(OpNode)en,td);
429       return;
430
431     case Kind.OffsetNode:
432       checkOffsetNode(md, nametable, (OffsetNode)en, td);
433       return;
434
435     case Kind.TertiaryNode:
436       checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
437       return;
438       
439     case Kind.InstanceOfNode:
440       checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
441       return;
442
443     case Kind.ArrayInitializerNode:
444       checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
445       return;
446     }
447     throw new Error();
448   }
449
450   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
451     /* Get type descriptor */
452     if (cn.getType()==null) {
453       NameDescriptor typenamed=cn.getTypeName().getName();
454       String typename=typenamed.toString();
455       TypeDescriptor ntd=new TypeDescriptor(getClass(typename));
456       cn.setType(ntd);
457     }
458
459     /* Check the type descriptor */
460     TypeDescriptor cast_type=cn.getType();
461     checkTypeDescriptor(cast_type);
462
463     /* Type check */
464     if (td!=null) {
465       if (!typeutil.isSuperorType(td,cast_type))
466         throw new Error("Cast node returns "+cast_type+", but need "+td);
467     }
468
469     ExpressionNode en=cn.getExpression();
470     checkExpressionNode(md, nametable, en, null);
471     TypeDescriptor etd=en.getType();
472     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
473       return;
474
475     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
476       return;
477     if (typeutil.isCastable(etd, cast_type))
478       return;
479
480     /* Different branches */
481     /* TODO: change if add interfaces */
482     throw new Error("Cast will always fail\n"+cn.printNode(0));
483   }
484
485   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
486     ExpressionNode left=fan.getExpression();
487     checkExpressionNode(md,nametable,left,null);
488     TypeDescriptor ltd=left.getType();
489     String fieldname=fan.getFieldName();
490
491     FieldDescriptor fd=null;
492     if (ltd.isArray()&&fieldname.equals("length"))
493       fd=FieldDescriptor.arrayLength;
494     else
495       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
496     if (fd==null)
497       throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
498
499     if (fd.getType().iswrapper()) {
500       FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
501       fan2.setField(fd);
502       fan.left=fan2;
503       fan.fieldname="value";
504
505       ExpressionNode leftwr=fan.getExpression();
506       TypeDescriptor ltdwr=leftwr.getType();
507       String fieldnamewr=fan.getFieldName();
508       FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
509       fan.setField(fdwr);
510       if (fdwr==null)
511           throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
512     } else {
513       fan.setField(fd);
514     }
515     if (td!=null) {
516       if (!typeutil.isSuperorType(td,fan.getType()))
517         throw new Error("Field node returns "+fan.getType()+", but need "+td);
518     }
519   }
520
521   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
522     ExpressionNode left=aan.getExpression();
523     checkExpressionNode(md,nametable,left,null);
524
525     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
526     TypeDescriptor ltd=left.getType();
527
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()+") not compatible with type of lside ("+an.getDest().getType()+")"+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         throw new Error();
1047
1048       if (ltd.isDouble()||rtd.isDouble())
1049         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1050       else if (ltd.isFloat()||rtd.isFloat())
1051         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1052       else if (ltd.isLong()||rtd.isLong())
1053         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1054       else
1055         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1056       righttype=lefttype;
1057       on.setLeftType(lefttype);
1058       on.setRightType(righttype);
1059       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1060       break;
1061
1062     case Operation.ADD:
1063       if (ltd.isString()||rtd.isString()) {
1064         ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
1065         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1066         NameDescriptor nd=new NameDescriptor("String");
1067         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1068         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1069           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1070           leftmin.addArgument(on.getLeft());
1071           on.left=leftmin;
1072           checkExpressionNode(md, nametable, on.getLeft(), null);
1073         }
1074
1075         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1076           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1077           rightmin.addArgument(on.getRight());
1078           on.right=rightmin;
1079           checkExpressionNode(md, nametable, on.getRight(), null);
1080         }
1081
1082         on.setLeftType(stringtd);
1083         on.setRightType(stringtd);
1084         on.setType(stringtd);
1085         break;
1086       }
1087
1088     case Operation.SUB:
1089     case Operation.MULT:
1090     case Operation.DIV:
1091     case Operation.MOD:
1092       // 5.6.2 Binary Numeric Promotion
1093       //TODO unboxing of reference objects
1094       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1095         throw new Error("Error in "+on.printNode(0));
1096
1097       if (ltd.isDouble()||rtd.isDouble())
1098         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1099       else if (ltd.isFloat()||rtd.isFloat())
1100         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1101       else if (ltd.isLong()||rtd.isLong())
1102         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1103       else
1104         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1105       righttype=lefttype;
1106       on.setLeftType(lefttype);
1107       on.setRightType(righttype);
1108       on.setType(lefttype);
1109       break;
1110
1111     case Operation.LEFTSHIFT:
1112     case Operation.RIGHTSHIFT:
1113     case Operation.URIGHTSHIFT:
1114       if (!rtd.isIntegerType())
1115         throw new Error();
1116       //5.6.1 Unary Numeric Promotion
1117       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1118         righttype=new TypeDescriptor(TypeDescriptor.INT);
1119       else
1120         righttype=rtd;
1121
1122       on.setRightType(righttype);
1123       if (!ltd.isIntegerType())
1124         throw new Error();
1125
1126     case Operation.UNARYPLUS:
1127     case Operation.UNARYMINUS:
1128       /*        case Operation.POSTINC:
1129           case Operation.POSTDEC:
1130           case Operation.PREINC:
1131           case Operation.PREDEC:*/
1132       if (!ltd.isNumber())
1133         throw new Error();
1134       //5.6.1 Unary Numeric Promotion
1135       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1136         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1137       else
1138         lefttype=ltd;
1139       on.setLeftType(lefttype);
1140       on.setType(lefttype);
1141       break;
1142
1143     default:
1144       throw new Error(op.toString());
1145     }
1146
1147     if (td!=null)
1148       if (!typeutil.isSuperorType(td, on.getType())) {
1149         System.out.println(td);
1150         System.out.println(on.getType());
1151         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1152       }
1153   }
1154 }