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