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