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