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