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