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