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     if (ltd.dereference().iswrapper()) {
528       aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
529     }
530
531     if (td!=null)
532       if (!typeutil.isSuperorType(td,aan.getType()))
533         throw new Error("Field node returns "+aan.getType()+", but need "+td);
534   }
535
536   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
537     /* Resolve the type */
538     Object o=ln.getValue();
539     if (ln.getTypeString().equals("null")) {
540       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
541     } else if (o instanceof Integer) {
542       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
543     } else if (o instanceof Long) {
544       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
545     } else if (o instanceof Float) {
546       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
547     } else if (o instanceof Boolean) {
548       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
549     } else if (o instanceof Double) {
550       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
551     } else if (o instanceof Character) {
552       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
553     } else if (o instanceof String) {
554       ln.setType(new TypeDescriptor(getClass(TypeUtil.StringClass)));
555     }
556
557     if (td!=null)
558       if (!typeutil.isSuperorType(td,ln.getType()))
559         throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
560   }
561
562   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
563     NameDescriptor nd=nn.getName();
564     if (nd.getBase()!=null) {
565       /* Big hack */
566       /* Rewrite NameNode */
567       ExpressionNode en=translateNameDescriptorintoExpression(nd);
568       nn.setExpression(en);
569       checkExpressionNode(md,nametable,en,td);
570     } else {
571       String varname=nd.toString();
572       Descriptor d=(Descriptor)nametable.get(varname);
573       if (d==null) {
574         throw new Error("Name "+varname+" undefined in: "+md);
575       }
576       if (d instanceof VarDescriptor) {
577         nn.setVar(d);
578       } else if (d instanceof FieldDescriptor) {
579         FieldDescriptor fd=(FieldDescriptor)d;
580         if (fd.getType().iswrapper()) {
581           String id=nd.getIdentifier();
582           NameDescriptor base=nd.getBase();
583           NameNode n=new NameNode(nn.getName());
584           n.setField(fd);
585           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
586           FieldAccessNode fan=new FieldAccessNode(n,"value");
587           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
588           fan.setField(fdval);
589           nn.setExpression(fan);
590         } else {
591           nn.setField(fd);
592           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
593         }
594       } else if (d instanceof TagVarDescriptor) {
595         nn.setVar(d);
596       } else throw new Error("Wrong type of descriptor");
597       if (td!=null)
598         if (!typeutil.isSuperorType(td,nn.getType()))
599           throw new Error("Field node returns "+nn.getType()+", but need "+td);
600     }
601   }
602
603   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
604     TypeDescriptor ltd=ofn.td;
605     checkTypeDescriptor(ltd);
606     
607     String fieldname = ofn.fieldname;
608     FieldDescriptor fd=null;
609     if (ltd.isArray()&&fieldname.equals("length")) {
610       fd=FieldDescriptor.arrayLength;
611     } else {
612       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
613     }
614
615     ofn.setField(fd);
616     checkField(ltd.getClassDesc(), fd);
617
618     if (fd==null)
619       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
620
621     if (td!=null) {
622       if (!typeutil.isSuperorType(td, ofn.getType())) {
623         System.out.println(td);
624         System.out.println(ofn.getType());
625         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
626       }
627     }
628   }
629
630
631   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
632     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
633     checkExpressionNode(md, nametable, tn.getTrueExpr(), td );
634     checkExpressionNode(md, nametable, tn.getFalseExpr(), td );
635   }
636
637   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
638     if (td!=null&&!td.isBoolean())
639       throw new Error("Expecting type "+td+"for instanceof expression");
640     
641     checkTypeDescriptor(tn.getExprType());
642     checkExpressionNode(md, nametable, tn.getExpr(), null);
643   }
644
645   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
646     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
647       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td); 
648     }
649   }
650
651   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
652     boolean postinc=true;
653     if (an.getOperation().getBaseOp()==null||
654         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
655          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
656       postinc=false;
657     if (!postinc)      
658       checkExpressionNode(md, nametable, an.getSrc(),td);
659     //TODO: Need check on validity of operation here
660     if (!((an.getDest() instanceof FieldAccessNode)||
661           (an.getDest() instanceof ArrayAccessNode)||
662           (an.getDest() instanceof NameNode)))
663       throw new Error("Bad lside in "+an.printNode(0));
664     checkExpressionNode(md, nametable, an.getDest(), null);
665
666     /* We want parameter variables to tasks to be immutable */
667     if (md instanceof TaskDescriptor) {
668       if (an.getDest() instanceof NameNode) {
669         NameNode nn=(NameNode)an.getDest();
670         if (nn.getVar()!=null) {
671           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
672             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
673         }
674       }
675     }
676
677     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
678       //String add
679       ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
680       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
681       NameDescriptor nd=new NameDescriptor("String");
682       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
683
684       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
685         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
686         rightmin.addArgument(an.getSrc());
687         an.right=rightmin;
688         checkExpressionNode(md, nametable, an.getSrc(), null);
689       }
690     }
691
692     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
693       throw new Error("Type of rside ("+an.getSrc().getType()+") not compatible with type of lside ("+an.getDest().getType()+")"+an.printNode(0));
694     }
695   }
696
697   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
698       loopstack.push(ln);
699     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
700       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
701       checkBlockNode(md, nametable, ln.getBody());
702     } else {
703       //For loop case
704       /* Link in the initializer naming environment */
705       BlockNode bn=ln.getInitializer();
706       bn.getVarTable().setParent(nametable);
707       for(int i=0; i<bn.size(); i++) {
708         BlockStatementNode bsn=bn.get(i);
709         checkBlockStatementNode(md, bn.getVarTable(),bsn);
710       }
711       //check the condition
712       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
713       checkBlockNode(md, bn.getVarTable(), ln.getBody());
714       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
715     }
716     loopstack.pop();
717   }
718
719
720   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con, TypeDescriptor td) {
721     TypeDescriptor[] tdarray=new TypeDescriptor[con.numArgs()];
722     for(int i=0; i<con.numArgs(); i++) {
723       ExpressionNode en=con.getArg(i);
724       checkExpressionNode(md,nametable,en,null);
725       tdarray[i]=en.getType();
726     }
727
728     TypeDescriptor typetolookin=con.getType();
729     checkTypeDescriptor(typetolookin);
730
731     if (td!=null&&!typeutil.isSuperorType(td, typetolookin))
732       throw new Error(typetolookin + " isn't a "+td);
733
734     /* Check flag effects */
735     if (con.getFlagEffects()!=null) {
736       FlagEffects fe=con.getFlagEffects();
737       ClassDescriptor cd=typetolookin.getClassDesc();
738
739       for(int j=0; j<fe.numEffects(); j++) {
740         FlagEffect flag=fe.getEffect(j);
741         String name=flag.getName();
742         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
743         //Make sure the flag is declared
744         if (flag_d==null)
745           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
746         if (flag_d.getExternal())
747           throw new Error("Attempting to modify external flag: "+name);
748         flag.setFlag(flag_d);
749       }
750       for(int j=0; j<fe.numTagEffects(); j++) {
751         TagEffect tag=fe.getTagEffect(j);
752         String name=tag.getName();
753
754         Descriptor d=(Descriptor)nametable.get(name);
755         if (d==null)
756           throw new Error("Tag descriptor "+name+" undeclared");
757         else if (!(d instanceof TagVarDescriptor))
758           throw new Error(name+" is not a tag descriptor");
759         tag.setTag((TagVarDescriptor)d);
760       }
761     }
762
763     if ((!typetolookin.isClass())&&(!typetolookin.isArray()))
764       throw new Error("Can't allocate primitive type:"+con.printNode(0));
765
766     if (!typetolookin.isArray()) {
767       //Array's don't need constructor calls
768       ClassDescriptor classtolookin=typetolookin.getClassDesc();
769
770       Set methoddescriptorset=classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
771       MethodDescriptor bestmd=null;
772 NextMethod:
773       for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
774         MethodDescriptor currmd=(MethodDescriptor)methodit.next();
775         /* Need correct number of parameters */
776         if (con.numArgs()!=currmd.numParameters())
777           continue;
778         for(int i=0; i<con.numArgs(); i++) {
779           if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
780             continue NextMethod;
781         }
782         /* Local allocations can't call global allocator */
783         if (!con.isGlobal()&&currmd.isGlobal())
784           continue;
785
786         /* Method okay so far */
787         if (bestmd==null)
788           bestmd=currmd;
789         else {
790           if (typeutil.isMoreSpecific(currmd,bestmd)) {
791             bestmd=currmd;
792           } else if (con.isGlobal()&&match(currmd, bestmd)) {
793             if (currmd.isGlobal()&&!bestmd.isGlobal())
794               bestmd=currmd;
795             else if (currmd.isGlobal()&&bestmd.isGlobal())
796               throw new Error();
797           } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
798             throw new Error("No method is most specific");
799           }
800
801           /* Is this more specific than bestmd */
802         }
803       }
804       if (bestmd==null)
805         throw new Error("No method found for "+con.printNode(0)+" in "+md);
806       con.setConstructor(bestmd);
807     }
808   }
809
810
811   /** Check to see if md1 is the same specificity as md2.*/
812
813   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
814     /* Checks if md1 is more specific than md2 */
815     if (md1.numParameters()!=md2.numParameters())
816       throw new Error();
817     for(int i=0; i<md1.numParameters(); i++) {
818       if (!md2.getParamType(i).equals(md1.getParamType(i)))
819         return false;
820     }
821     if (!md2.getReturnType().equals(md1.getReturnType()))
822       return false;
823
824     if (!md2.getClassDesc().equals(md1.getClassDesc()))
825       return false;
826
827     return true;
828   }
829
830
831
832   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd) {
833     String id=nd.getIdentifier();
834     NameDescriptor base=nd.getBase();
835     if (base==null)
836       return new NameNode(nd);
837     else
838       return new FieldAccessNode(translateNameDescriptorintoExpression(base),id);
839   }
840
841
842   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
843     /*Typecheck subexpressions
844        and get types for expressions*/
845
846     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
847     for(int i=0; i<min.numArgs(); i++) {
848       ExpressionNode en=min.getArg(i);
849       checkExpressionNode(md,nametable,en,null);
850       tdarray[i]=en.getType();
851     }
852     TypeDescriptor typetolookin=null;
853     if (min.getExpression()!=null) {
854       checkExpressionNode(md,nametable,min.getExpression(),null);
855       typetolookin=min.getExpression().getType();
856       //if (typetolookin==null)
857       //throw new Error(md+" has null return type");
858
859     } else if (min.getBaseName()!=null) {
860       String rootname=min.getBaseName().getRoot();
861       if (rootname.equals("super")) {
862         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
863         typetolookin=new TypeDescriptor(supercd);
864       } else if (nametable.get(rootname)!=null) {
865         //we have an expression
866         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName()));
867         checkExpressionNode(md, nametable, min.getExpression(), null);
868         typetolookin=min.getExpression().getType();
869       } else {
870         //we have a type
871         ClassDescriptor cd;
872         if (min.getBaseName().getSymbol().equals("System.out"))
873           cd=getClass("System");
874         else
875           cd=getClass(min.getBaseName().getSymbol());
876         if (cd==null)
877           throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
878         typetolookin=new TypeDescriptor(cd);
879       }
880     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
881       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
882       min.methodid=supercd.getSymbol();
883       typetolookin=new TypeDescriptor(supercd);
884     } else if (md instanceof MethodDescriptor) {
885       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
886     } else {
887       /* If this a task descriptor we throw an error at this point */
888       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
889     }
890     if (!typetolookin.isClass())
891       throw new Error("Error with method call to "+min.getMethodName());
892     ClassDescriptor classtolookin=typetolookin.getClassDesc();
893     //System.out.println("Method name="+min.getMethodName());
894
895     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
896     MethodDescriptor bestmd=null;
897 NextMethod:
898     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
899       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
900       /* Need correct number of parameters */
901       if (min.numArgs()!=currmd.numParameters())
902         continue;
903       for(int i=0; i<min.numArgs(); i++) {
904         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
905           continue NextMethod;
906       }
907       /* Method okay so far */
908       if (bestmd==null)
909         bestmd=currmd;
910       else {
911         if (typeutil.isMoreSpecific(currmd,bestmd)) {
912           bestmd=currmd;
913         } else if (!typeutil.isMoreSpecific(bestmd, currmd))
914           throw new Error("No method is most specific");
915
916         /* Is this more specific than bestmd */
917       }
918     }
919     if (bestmd==null)
920       throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
921     min.setMethod(bestmd);
922
923     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
924       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
925     /* Check whether we need to set this parameter to implied this */
926     if (!bestmd.isStatic()) {
927       if (min.getExpression()==null) {
928         ExpressionNode en=new NameNode(new NameDescriptor("this"));
929         min.setExpression(en);
930         checkExpressionNode(md, nametable, min.getExpression(), null);
931       }
932     }
933   }
934
935
936   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
937     checkExpressionNode(md, nametable, on.getLeft(), null);
938     if (on.getRight()!=null)
939       checkExpressionNode(md, nametable, on.getRight(), null);
940     TypeDescriptor ltd=on.getLeft().getType();
941     TypeDescriptor rtd=on.getRight()!=null ? on.getRight().getType() : null;
942     TypeDescriptor lefttype=null;
943     TypeDescriptor righttype=null;
944     Operation op=on.getOp();
945
946     switch(op.getOp()) {
947     case Operation.LOGIC_OR:
948     case Operation.LOGIC_AND:
949       if (!(rtd.isBoolean()))
950         throw new Error();
951       on.setRightType(rtd);
952
953     case Operation.LOGIC_NOT:
954       if (!(ltd.isBoolean()))
955         throw new Error();
956       //no promotion
957       on.setLeftType(ltd);
958
959       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
960       break;
961
962     case Operation.COMP:
963       // 5.6.2 Binary Numeric Promotion
964       //TODO unboxing of reference objects
965       if (ltd.isDouble())
966         throw new Error();
967       else if (ltd.isFloat())
968         throw new Error();
969       else if (ltd.isLong())
970         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
971       else
972         lefttype=new TypeDescriptor(TypeDescriptor.INT);
973       on.setLeftType(lefttype);
974       on.setType(lefttype);
975       break;
976
977     case Operation.BIT_OR:
978     case Operation.BIT_XOR:
979     case Operation.BIT_AND:
980       // 5.6.2 Binary Numeric Promotion
981       //TODO unboxing of reference objects
982       if (ltd.isDouble()||rtd.isDouble())
983         throw new Error();
984       else if (ltd.isFloat()||rtd.isFloat())
985         throw new Error();
986       else if (ltd.isLong()||rtd.isLong())
987         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
988       // 090205 hack for boolean
989       else if (ltd.isBoolean()||rtd.isBoolean())
990         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
991       else
992         lefttype=new TypeDescriptor(TypeDescriptor.INT);
993       righttype=lefttype;
994
995       on.setLeftType(lefttype);
996       on.setRightType(righttype);
997       on.setType(lefttype);
998       break;
999
1000     case Operation.ISAVAILABLE:
1001       if (!(ltd.isPtr())) {
1002         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1003       }
1004       lefttype=ltd;
1005       on.setLeftType(lefttype);
1006       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1007       break;
1008
1009     case Operation.EQUAL:
1010     case Operation.NOTEQUAL:
1011       // 5.6.2 Binary Numeric Promotion
1012       //TODO unboxing of reference objects
1013       if (ltd.isBoolean()||rtd.isBoolean()) {
1014         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1015           throw new Error();
1016         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1017       } else if (ltd.isPtr()||rtd.isPtr()) {
1018         if (!(ltd.isPtr()&&rtd.isPtr()))
1019           throw new Error();
1020         righttype=rtd;
1021         lefttype=ltd;
1022       } else if (ltd.isDouble()||rtd.isDouble())
1023         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1024       else if (ltd.isFloat()||rtd.isFloat())
1025         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1026       else if (ltd.isLong()||rtd.isLong())
1027         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1028       else
1029         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1030
1031       on.setLeftType(lefttype);
1032       on.setRightType(righttype);
1033       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1034       break;
1035
1036
1037
1038     case Operation.LT:
1039     case Operation.GT:
1040     case Operation.LTE:
1041     case Operation.GTE:
1042       // 5.6.2 Binary Numeric Promotion
1043       //TODO unboxing of reference objects
1044       if (!ltd.isNumber()||!rtd.isNumber()) {
1045         if (!ltd.isNumber())
1046           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1047         if (!rtd.isNumber())
1048           throw new Error("Rightside is not number"+on.printNode(0));
1049       }
1050
1051       if (ltd.isDouble()||rtd.isDouble())
1052         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1053       else if (ltd.isFloat()||rtd.isFloat())
1054         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1055       else if (ltd.isLong()||rtd.isLong())
1056         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1057       else
1058         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1059       righttype=lefttype;
1060       on.setLeftType(lefttype);
1061       on.setRightType(righttype);
1062       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1063       break;
1064
1065     case Operation.ADD:
1066       if (ltd.isString()||rtd.isString()) {
1067         ClassDescriptor stringcl=getClass(TypeUtil.StringClass);
1068         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1069         NameDescriptor nd=new NameDescriptor("String");
1070         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1071         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1072           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1073           leftmin.addArgument(on.getLeft());
1074           on.left=leftmin;
1075           checkExpressionNode(md, nametable, on.getLeft(), null);
1076         }
1077
1078         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1079           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1080           rightmin.addArgument(on.getRight());
1081           on.right=rightmin;
1082           checkExpressionNode(md, nametable, on.getRight(), null);
1083         }
1084
1085         on.setLeftType(stringtd);
1086         on.setRightType(stringtd);
1087         on.setType(stringtd);
1088         break;
1089       }
1090
1091     case Operation.SUB:
1092     case Operation.MULT:
1093     case Operation.DIV:
1094     case Operation.MOD:
1095       // 5.6.2 Binary Numeric Promotion
1096       //TODO unboxing of reference objects
1097       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1098         throw new Error("Error in "+on.printNode(0));
1099
1100       if (ltd.isDouble()||rtd.isDouble())
1101         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1102       else if (ltd.isFloat()||rtd.isFloat())
1103         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1104       else if (ltd.isLong()||rtd.isLong())
1105         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1106       else
1107         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1108       righttype=lefttype;
1109       on.setLeftType(lefttype);
1110       on.setRightType(righttype);
1111       on.setType(lefttype);
1112       break;
1113
1114     case Operation.LEFTSHIFT:
1115     case Operation.RIGHTSHIFT:
1116     case Operation.URIGHTSHIFT:
1117       if (!rtd.isIntegerType())
1118         throw new Error();
1119       //5.6.1 Unary Numeric Promotion
1120       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1121         righttype=new TypeDescriptor(TypeDescriptor.INT);
1122       else
1123         righttype=rtd;
1124
1125       on.setRightType(righttype);
1126       if (!ltd.isIntegerType())
1127         throw new Error();
1128
1129     case Operation.UNARYPLUS:
1130     case Operation.UNARYMINUS:
1131       /*        case Operation.POSTINC:
1132           case Operation.POSTDEC:
1133           case Operation.PREINC:
1134           case Operation.PREDEC:*/
1135       if (!ltd.isNumber())
1136         throw new Error();
1137       //5.6.1 Unary Numeric Promotion
1138       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1139         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1140       else
1141         lefttype=ltd;
1142       on.setLeftType(lefttype);
1143       on.setType(lefttype);
1144       break;
1145
1146     default:
1147       throw new Error(op.toString());
1148     }
1149
1150     if (td!=null)
1151       if (!typeutil.isSuperorType(td, on.getType())) {
1152         System.out.println(td);
1153         System.out.println(on.getType());
1154         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1155       }
1156   }
1157 }