7aa5e3e9a337aceb0967f61dc27e930e1ea27508
[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     case Kind.SESENode:
271       // do nothing, no semantic check for SESEs
272       return;
273     }
274
275     throw new Error();
276   }
277
278   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
279     checkExpressionNode(md, nametable, ben.getExpression(), null);
280   }
281
282   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
283     VarDescriptor vd=dn.getVarDescriptor();
284     checkTypeDescriptor(vd.getType());
285     Descriptor d=nametable.get(vd.getSymbol());
286     if ((d==null)||
287         (d instanceof FieldDescriptor)) {
288       nametable.add(vd);
289     } else
290       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
291     if (dn.getExpression()!=null)
292       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
293   }
294
295   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
296     TagVarDescriptor vd=dn.getTagVarDescriptor();
297     Descriptor d=nametable.get(vd.getSymbol());
298     if ((d==null)||
299         (d instanceof FieldDescriptor)) {
300       nametable.add(vd);
301     } else
302       throw new Error(vd.getSymbol()+" defined a second time");
303   }
304
305   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
306     checkBlockNode(md, nametable, sbn.getBlockNode());
307   }
308
309   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
310     checkBlockNode(md, nametable, sbn.getBlockNode());
311   }
312
313   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
314     if (d instanceof TaskDescriptor)
315       throw new Error("Illegal return appears in Task: "+d.getSymbol());
316     MethodDescriptor md=(MethodDescriptor)d;
317     if (rn.getReturnExpression()!=null)
318       if (md.getReturnType()==null)
319         throw new Error("Constructor can't return something.");
320       else if (md.getReturnType().isVoid())
321         throw new Error(md+" is void");
322       else
323         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
324     else
325     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
326       throw new Error("Need to return something for "+md);
327   }
328
329   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
330     if (md instanceof MethodDescriptor)
331       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
332     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
333     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
334   }
335
336   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
337     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
338     checkBlockNode(md, nametable, isn.getTrueBlock());
339     if (isn.getFalseBlock()!=null)
340       checkBlockNode(md, nametable, isn.getFalseBlock());
341   }
342
343   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
344     switch(en.kind()) {
345     case Kind.AssignmentNode:
346       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
347       return;
348
349     case Kind.CastNode:
350       checkCastNode(md,nametable,(CastNode)en,td);
351       return;
352
353     case Kind.CreateObjectNode:
354       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
355       return;
356
357     case Kind.FieldAccessNode:
358       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
359       return;
360
361     case Kind.ArrayAccessNode:
362       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
363       return;
364
365     case Kind.LiteralNode:
366       checkLiteralNode(md,nametable,(LiteralNode)en,td);
367       return;
368
369     case Kind.MethodInvokeNode:
370       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
371       return;
372
373     case Kind.NameNode:
374       checkNameNode(md,nametable,(NameNode)en,td);
375       return;
376
377     case Kind.OpNode:
378       checkOpNode(md,nametable,(OpNode)en,td);
379       return;
380
381     case Kind.OffsetNode:
382       checkOffsetNode(md, nametable, (OffsetNode)en, new TypeDescriptor(TypeDescriptor.OFFSET));
383       return;
384     }
385     throw new Error();
386   }
387
388   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
389     /* Get type descriptor */
390     if (cn.getType()==null) {
391       NameDescriptor typenamed=cn.getTypeName().getName();
392       String typename=typenamed.toString();
393       TypeDescriptor ntd=new TypeDescriptor(typeutil.getClass(typename));
394       cn.setType(ntd);
395     }
396
397     /* Check the type descriptor */
398     TypeDescriptor cast_type=cn.getType();
399     checkTypeDescriptor(cast_type);
400
401     /* Type check */
402     if (td!=null) {
403       if (!typeutil.isSuperorType(td,cast_type))
404         throw new Error("Cast node returns "+cast_type+", but need "+td);
405     }
406
407     ExpressionNode en=cn.getExpression();
408     checkExpressionNode(md, nametable, en, null);
409     TypeDescriptor etd=en.getType();
410     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
411       return;
412
413     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
414       return;
415     if (typeutil.isCastable(etd, cast_type))
416       return;
417
418     /* Different branches */
419     /* TODO: change if add interfaces */
420     throw new Error("Cast will always fail\n"+cn.printNode(0));
421   }
422
423   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
424     ExpressionNode left=fan.getExpression();
425     checkExpressionNode(md,nametable,left,null);
426     TypeDescriptor ltd=left.getType();
427     String fieldname=fan.getFieldName();
428
429     FieldDescriptor fd=null;
430     if (ltd.isArray()&&fieldname.equals("length"))
431       fd=FieldDescriptor.arrayLength;
432     else
433       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
434     if (fd==null)
435       throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
436     fan.setField(fd);
437     if (td!=null)
438       if (!typeutil.isSuperorType(td,fan.getType()))
439         throw new Error("Field node returns "+fan.getType()+", but need "+td);
440   }
441
442   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
443     ExpressionNode left=aan.getExpression();
444     checkExpressionNode(md,nametable,left,null);
445
446     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
447     TypeDescriptor ltd=left.getType();
448
449     if (td!=null)
450       if (!typeutil.isSuperorType(td,aan.getType()))
451         throw new Error("Field node returns "+aan.getType()+", but need "+td);
452   }
453
454   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
455     /* Resolve the type */
456     Object o=ln.getValue();
457     if (ln.getTypeString().equals("null")) {
458       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
459     } else if (o instanceof Integer) {
460       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
461     } else if (o instanceof Long) {
462       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
463     } else if (o instanceof Float) {
464       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
465     } else if (o instanceof Boolean) {
466       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
467     } else if (o instanceof Double) {
468       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
469     } else if (o instanceof Character) {
470       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
471     } else if (o instanceof String) {
472       ln.setType(new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass)));
473     }
474
475     if (td!=null)
476       if (!typeutil.isSuperorType(td,ln.getType()))
477         throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
478   }
479
480   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
481     NameDescriptor nd=nn.getName();
482     if (nd.getBase()!=null) {
483       /* Big hack */
484       /* Rewrite NameNode */
485       ExpressionNode en=translateNameDescriptorintoExpression(nd);
486       nn.setExpression(en);
487       checkExpressionNode(md,nametable,en,td);
488     } else {
489       String varname=nd.toString();
490       Descriptor d=(Descriptor)nametable.get(varname);
491       if (d==null) {
492         throw new Error("Name "+varname+" undefined in: "+md);
493       }
494       if (d instanceof VarDescriptor) {
495         nn.setVar(d);
496       } else if (d instanceof FieldDescriptor) {
497         nn.setField((FieldDescriptor)d);
498         nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
499       } else if (d instanceof TagVarDescriptor) {
500         nn.setVar(d);
501       } else throw new Error("Wrong type of descriptor");
502       if (td!=null)
503         if (!typeutil.isSuperorType(td,nn.getType()))
504           throw new Error("Field node returns "+nn.getType()+", but need "+td);
505     }
506   }
507
508   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
509     TypeDescriptor ltd = ofn.td;
510     //System.out.println("Testing TypeDescriptor ltd = " + ofn.td);
511     String fieldname = ofn.fieldname;
512     //System.out.println("Testing String fieldname = " + ofn.fieldname);
513     Descriptor d = (Descriptor) nameTable.get(fieldname);
514     //System.out.println("Testing Descriptor d = " + d.toString());
515
516     ClassDescriptor cd = null;
517     checkTypeDescriptor(ltd);
518     cd = ltd.getClassDesc();
519     ofn.setClassDesc(cd);
520     //System.out.println("Testing for ClassDescriptor cd = " + cd.toString());
521
522     FieldDescriptor fd=null;
523     if (ltd.isArray()&&fieldname.equals("length")) {
524       fd=FieldDescriptor.arrayLength;
525     } else {
526       fd=(FieldDescriptor) cd.getFieldTable().get(fieldname);
527     }
528     //System.out.println("Testing for FieldDescriptor fd = " + fd.toString());
529     ofn.setField(fd);
530     if (fd==null)
531       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
532     ofn.setType(td);
533   }
534
535   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
536     boolean postinc=true;
537     if (an.getOperation().getBaseOp()==null||
538         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
539          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
540       postinc=false;
541
542     if (!postinc)
543       checkExpressionNode(md, nametable, an.getSrc(),td);
544     //TODO: Need check on validity of operation here
545     if (!((an.getDest() instanceof FieldAccessNode)||
546           (an.getDest() instanceof ArrayAccessNode)||
547           (an.getDest() instanceof NameNode)))
548       throw new Error("Bad lside in "+an.printNode(0));
549     checkExpressionNode(md, nametable, an.getDest(), null);
550
551     /* We want parameter variables to tasks to be immutable */
552     if (md instanceof TaskDescriptor) {
553       if (an.getDest() instanceof NameNode) {
554         NameNode nn=(NameNode)an.getDest();
555         if (nn.getVar()!=null) {
556           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
557             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
558         }
559       }
560     }
561
562     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
563       //String add
564       ClassDescriptor stringcl=typeutil.getClass(TypeUtil.StringClass);
565       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
566       NameDescriptor nd=new NameDescriptor("String");
567       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
568
569       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
570         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
571         rightmin.addArgument(an.getSrc());
572         an.right=rightmin;
573         checkExpressionNode(md, nametable, an.getSrc(), null);
574       }
575     }
576
577     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
578       throw new Error("Type of rside ("+an.getSrc().getType()+") not compatible with type of lside ("+an.getDest().getType()+")"+an.printNode(0));
579     }
580   }
581
582   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
583     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
584       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
585       checkBlockNode(md, nametable, ln.getBody());
586     } else {
587       //For loop case
588       /* Link in the initializer naming environment */
589       BlockNode bn=ln.getInitializer();
590       bn.getVarTable().setParent(nametable);
591       for(int i=0; i<bn.size(); i++) {
592         BlockStatementNode bsn=bn.get(i);
593         checkBlockStatementNode(md, bn.getVarTable(),bsn);
594       }
595       //check the condition
596       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
597       checkBlockNode(md, bn.getVarTable(), ln.getBody());
598       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
599     }
600   }
601
602
603   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con, TypeDescriptor td) {
604     TypeDescriptor[] tdarray=new TypeDescriptor[con.numArgs()];
605     for(int i=0; i<con.numArgs(); i++) {
606       ExpressionNode en=con.getArg(i);
607       checkExpressionNode(md,nametable,en,null);
608       tdarray[i]=en.getType();
609     }
610
611     TypeDescriptor typetolookin=con.getType();
612     checkTypeDescriptor(typetolookin);
613
614     if (td!=null&&!typeutil.isSuperorType(td, typetolookin))
615       throw new Error(typetolookin + " isn't a "+td);
616
617     /* Check flag effects */
618     if (con.getFlagEffects()!=null) {
619       FlagEffects fe=con.getFlagEffects();
620       ClassDescriptor cd=typetolookin.getClassDesc();
621
622       for(int j=0; j<fe.numEffects(); j++) {
623         FlagEffect flag=fe.getEffect(j);
624         String name=flag.getName();
625         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
626         //Make sure the flag is declared
627         if (flag_d==null)
628           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
629         if (flag_d.getExternal())
630           throw new Error("Attempting to modify external flag: "+name);
631         flag.setFlag(flag_d);
632       }
633       for(int j=0; j<fe.numTagEffects(); j++) {
634         TagEffect tag=fe.getTagEffect(j);
635         String name=tag.getName();
636
637         Descriptor d=(Descriptor)nametable.get(name);
638         if (d==null)
639           throw new Error("Tag descriptor "+name+" undeclared");
640         else if (!(d instanceof TagVarDescriptor))
641           throw new Error(name+" is not a tag descriptor");
642         tag.setTag((TagVarDescriptor)d);
643       }
644     }
645
646     if ((!typetolookin.isClass())&&(!typetolookin.isArray()))
647       throw new Error("Can't allocate primitive type:"+con.printNode(0));
648
649     if (!typetolookin.isArray()) {
650       //Array's don't need constructor calls
651       ClassDescriptor classtolookin=typetolookin.getClassDesc();
652
653       Set methoddescriptorset=classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
654       MethodDescriptor bestmd=null;
655 NextMethod:
656       for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
657         MethodDescriptor currmd=(MethodDescriptor)methodit.next();
658         /* Need correct number of parameters */
659         if (con.numArgs()!=currmd.numParameters())
660           continue;
661         for(int i=0; i<con.numArgs(); i++) {
662           if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
663             continue NextMethod;
664         }
665         /* Local allocations can't call global allocator */
666         if (!con.isGlobal()&&currmd.isGlobal())
667           continue;
668
669         /* Method okay so far */
670         if (bestmd==null)
671           bestmd=currmd;
672         else {
673           if (typeutil.isMoreSpecific(currmd,bestmd)) {
674             bestmd=currmd;
675           } else if (con.isGlobal()&&match(currmd, bestmd)) {
676             if (currmd.isGlobal()&&!bestmd.isGlobal())
677               bestmd=currmd;
678             else if (currmd.isGlobal()&&bestmd.isGlobal())
679               throw new Error();
680           } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
681             throw new Error("No method is most specific");
682           }
683
684           /* Is this more specific than bestmd */
685         }
686       }
687       if (bestmd==null)
688         throw new Error("No method found for "+con.printNode(0)+" in "+md);
689       con.setConstructor(bestmd);
690     }
691   }
692
693
694   /** Check to see if md1 is the same specificity as md2.*/
695
696   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
697     /* Checks if md1 is more specific than md2 */
698     if (md1.numParameters()!=md2.numParameters())
699       throw new Error();
700     for(int i=0; i<md1.numParameters(); i++) {
701       if (!md2.getParamType(i).equals(md1.getParamType(i)))
702         return false;
703     }
704     if (!md2.getReturnType().equals(md1.getReturnType()))
705       return false;
706
707     if (!md2.getClassDesc().equals(md1.getClassDesc()))
708       return false;
709
710     return true;
711   }
712
713
714
715   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd) {
716     String id=nd.getIdentifier();
717     NameDescriptor base=nd.getBase();
718     if (base==null)
719       return new NameNode(nd);
720     else
721       return new FieldAccessNode(translateNameDescriptorintoExpression(base),id);
722   }
723
724
725   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
726     /*Typecheck subexpressions
727        and get types for expressions*/
728
729     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
730     for(int i=0; i<min.numArgs(); i++) {
731       ExpressionNode en=min.getArg(i);
732       checkExpressionNode(md,nametable,en,null);
733       tdarray[i]=en.getType();
734     }
735     TypeDescriptor typetolookin=null;
736     if (min.getExpression()!=null) {
737       checkExpressionNode(md,nametable,min.getExpression(),null);
738       typetolookin=min.getExpression().getType();
739     } else if (min.getBaseName()!=null) {
740       String rootname=min.getBaseName().getRoot();
741       if (rootname.equals("super")) {
742         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
743         typetolookin=new TypeDescriptor(supercd);
744       } else if (nametable.get(rootname)!=null) {
745         //we have an expression
746         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName()));
747         checkExpressionNode(md, nametable, min.getExpression(), null);
748         typetolookin=min.getExpression().getType();
749       } else {
750         //we have a type
751         ClassDescriptor cd=typeutil.getClass(min.getBaseName().getSymbol());
752         if (cd==null)
753           throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
754         typetolookin=new TypeDescriptor(cd);
755       }
756     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
757       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
758       min.methodid=supercd.getSymbol();
759       typetolookin=new TypeDescriptor(supercd);
760     } else if (md instanceof MethodDescriptor) {
761       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
762     } else {
763       /* If this a task descriptor we throw an error at this point */
764       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
765     }
766     if (!typetolookin.isClass())
767       throw new Error("Error with method call to "+min.getMethodName());
768     ClassDescriptor classtolookin=typetolookin.getClassDesc();
769     //System.out.println("Method name="+min.getMethodName());
770
771     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
772     MethodDescriptor bestmd=null;
773 NextMethod:
774     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
775       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
776       /* Need correct number of parameters */
777       if (min.numArgs()!=currmd.numParameters())
778         continue;
779       for(int i=0; i<min.numArgs(); i++) {
780         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
781           continue NextMethod;
782       }
783       /* Method okay so far */
784       if (bestmd==null)
785         bestmd=currmd;
786       else {
787         if (typeutil.isMoreSpecific(currmd,bestmd)) {
788           bestmd=currmd;
789         } else if (!typeutil.isMoreSpecific(bestmd, currmd))
790           throw new Error("No method is most specific");
791
792         /* Is this more specific than bestmd */
793       }
794     }
795     if (bestmd==null)
796       throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
797     min.setMethod(bestmd);
798
799     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
800       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
801     /* Check whether we need to set this parameter to implied this */
802     if (!bestmd.isStatic()) {
803       if (min.getExpression()==null) {
804         ExpressionNode en=new NameNode(new NameDescriptor("this"));
805         min.setExpression(en);
806         checkExpressionNode(md, nametable, min.getExpression(), null);
807       }
808     }
809   }
810
811
812   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
813     checkExpressionNode(md, nametable, on.getLeft(), null);
814     if (on.getRight()!=null)
815       checkExpressionNode(md, nametable, on.getRight(), null);
816     TypeDescriptor ltd=on.getLeft().getType();
817     TypeDescriptor rtd=on.getRight()!=null ? on.getRight().getType() : null;
818     TypeDescriptor lefttype=null;
819     TypeDescriptor righttype=null;
820     Operation op=on.getOp();
821
822     switch(op.getOp()) {
823     case Operation.LOGIC_OR:
824     case Operation.LOGIC_AND:
825       if (!(rtd.isBoolean()))
826         throw new Error();
827       on.setRightType(rtd);
828
829     case Operation.LOGIC_NOT:
830       if (!(ltd.isBoolean()))
831         throw new Error();
832       //no promotion
833       on.setLeftType(ltd);
834
835       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
836       break;
837
838     case Operation.COMP:
839       // 5.6.2 Binary Numeric Promotion
840       //TODO unboxing of reference objects
841       if (ltd.isDouble())
842         throw new Error();
843       else if (ltd.isFloat())
844         throw new Error();
845       else if (ltd.isLong())
846         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
847       else
848         lefttype=new TypeDescriptor(TypeDescriptor.INT);
849       on.setLeftType(lefttype);
850       on.setType(lefttype);
851       break;
852
853     case Operation.BIT_OR:
854     case Operation.BIT_XOR:
855     case Operation.BIT_AND:
856       // 5.6.2 Binary Numeric Promotion
857       //TODO unboxing of reference objects
858       if (ltd.isDouble()||rtd.isDouble())
859         throw new Error();
860       else if (ltd.isFloat()||rtd.isFloat())
861         throw new Error();
862       else if (ltd.isLong()||rtd.isLong())
863         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
864       // 090205 hack for boolean
865       else if (ltd.isBoolean()||rtd.isBoolean())
866         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
867       else
868         lefttype=new TypeDescriptor(TypeDescriptor.INT);
869       righttype=lefttype;
870
871       on.setLeftType(lefttype);
872       on.setRightType(righttype);
873       on.setType(lefttype);
874       break;
875
876     case Operation.ISAVAILABLE:
877       if (!(ltd.isPtr())) {
878         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
879       }
880       lefttype=ltd;
881       on.setLeftType(lefttype);
882       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
883       break;
884
885     case Operation.EQUAL:
886     case Operation.NOTEQUAL:
887       // 5.6.2 Binary Numeric Promotion
888       //TODO unboxing of reference objects
889       if (ltd.isBoolean()||rtd.isBoolean()) {
890         if (!(ltd.isBoolean()&&rtd.isBoolean()))
891           throw new Error();
892         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
893       } else if (ltd.isPtr()||rtd.isPtr()) {
894         if (!(ltd.isPtr()&&rtd.isPtr()))
895           throw new Error();
896         righttype=rtd;
897         lefttype=ltd;
898       } else if (ltd.isDouble()||rtd.isDouble())
899         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
900       else if (ltd.isFloat()||rtd.isFloat())
901         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
902       else if (ltd.isLong()||rtd.isLong())
903         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
904       else
905         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
906
907       on.setLeftType(lefttype);
908       on.setRightType(righttype);
909       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
910       break;
911
912
913
914     case Operation.LT:
915     case Operation.GT:
916     case Operation.LTE:
917     case Operation.GTE:
918       // 5.6.2 Binary Numeric Promotion
919       //TODO unboxing of reference objects
920       if (!ltd.isNumber()||!rtd.isNumber())
921         throw new Error();
922
923       if (ltd.isDouble()||rtd.isDouble())
924         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
925       else if (ltd.isFloat()||rtd.isFloat())
926         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
927       else if (ltd.isLong()||rtd.isLong())
928         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
929       else
930         lefttype=new TypeDescriptor(TypeDescriptor.INT);
931       righttype=lefttype;
932       on.setLeftType(lefttype);
933       on.setRightType(righttype);
934       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
935       break;
936
937     case Operation.ADD:
938       if (ltd.isString()||rtd.isString()) {
939         ClassDescriptor stringcl=typeutil.getClass(TypeUtil.StringClass);
940         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
941         NameDescriptor nd=new NameDescriptor("String");
942         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
943         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
944           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
945           leftmin.addArgument(on.getLeft());
946           on.left=leftmin;
947           checkExpressionNode(md, nametable, on.getLeft(), null);
948         }
949
950         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
951           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
952           rightmin.addArgument(on.getRight());
953           on.right=rightmin;
954           checkExpressionNode(md, nametable, on.getRight(), null);
955         }
956
957         on.setLeftType(stringtd);
958         on.setRightType(stringtd);
959         on.setType(stringtd);
960         break;
961       }
962
963     case Operation.SUB:
964     case Operation.MULT:
965     case Operation.DIV:
966     case Operation.MOD:
967       // 5.6.2 Binary Numeric Promotion
968       //TODO unboxing of reference objects
969       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
970         throw new Error("Error in "+on.printNode(0));
971
972       if (ltd.isDouble()||rtd.isDouble())
973         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
974       else if (ltd.isFloat()||rtd.isFloat())
975         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
976       else if (ltd.isLong()||rtd.isLong())
977         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
978       else
979         lefttype=new TypeDescriptor(TypeDescriptor.INT);
980       righttype=lefttype;
981       on.setLeftType(lefttype);
982       on.setRightType(righttype);
983       on.setType(lefttype);
984       break;
985
986     case Operation.LEFTSHIFT:
987     case Operation.RIGHTSHIFT:
988     case Operation.URIGHTSHIFT:
989       if (!rtd.isIntegerType())
990         throw new Error();
991       //5.6.1 Unary Numeric Promotion
992       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
993         righttype=new TypeDescriptor(TypeDescriptor.INT);
994       else
995         righttype=rtd;
996
997       on.setRightType(righttype);
998       if (!ltd.isIntegerType())
999         throw new Error();
1000
1001     case Operation.UNARYPLUS:
1002     case Operation.UNARYMINUS:
1003       /*        case Operation.POSTINC:
1004           case Operation.POSTDEC:
1005           case Operation.PREINC:
1006           case Operation.PREDEC:*/
1007       if (!ltd.isNumber())
1008         throw new Error();
1009       //5.6.1 Unary Numeric Promotion
1010       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1011         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1012       else
1013         lefttype=ltd;
1014       on.setLeftType(lefttype);
1015       on.setType(lefttype);
1016       break;
1017
1018     default:
1019       throw new Error(op.toString());
1020     }
1021
1022     if (td!=null)
1023       if (!typeutil.isSuperorType(td, on.getType())) {
1024         System.out.println(td);
1025         System.out.println(on.getType());
1026         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1027       }
1028   }
1029 }