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