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