changes to make sure that i don't step on stephen's work on imports...
[IRC.git] / Robust / src / IR / Tree / SemanticCheck.java
1 package IR.Tree;
2
3 import java.util.*;
4
5 import IR.*;
6
7 public class SemanticCheck {
8   State state;
9   TypeUtil typeutil;
10   Stack loopstack;
11   HashSet toanalyze;
12   HashMap<ClassDescriptor, Integer> completed;
13   
14   public static final int NOCHECK=0;
15   public static final int REFERENCE=1;
16   public static final int INIT=2;
17   
18   boolean checkAll;
19
20   public SemanticCheck(State state, TypeUtil tu) {
21     this(state, tu, true);
22   }
23
24   public SemanticCheck(State state, TypeUtil tu, boolean checkAll) {
25     this.state=state;
26     this.typeutil=tu;
27     this.loopstack=new Stack();
28     this.toanalyze=new HashSet();
29     this.completed=new HashMap<ClassDescriptor, Integer>();
30     this.checkAll=checkAll;
31   }
32
33   public ClassDescriptor getClass(ClassDescriptor context, String classname) {
34     return getClass(context, classname, INIT);
35   }
36
37   public ClassDescriptor getClass(ClassDescriptor context, String classname, int fullcheck) {
38     if (context!=null) {
39       Hashtable remaptable=context.getSingleImportMappings();
40       classname=remaptable.containsKey(classname)?((String)remaptable.get(classname)):classname;
41     }
42     ClassDescriptor cd=typeutil.getClass(classname, toanalyze);
43     checkClass(cd, fullcheck);
44     return cd;
45   }
46
47   private void checkClass(ClassDescriptor cd) {
48     checkClass(cd, INIT);
49   }
50
51   private void checkClass(ClassDescriptor cd, int fullcheck) {
52     if (!completed.containsKey(cd)||completed.get(cd)<fullcheck) {
53       int oldstatus=completed.containsKey(cd)?completed.get(cd):0;
54       completed.put(cd, fullcheck);
55       
56       if (fullcheck>=REFERENCE&&oldstatus<REFERENCE) {
57         //Set superclass link up
58         if (cd.getSuper()!=null) {
59           cd.setSuper(getClass(cd, cd.getSuper(), fullcheck));
60           if(cd.getSuperDesc().isInterface()) {
61             throw new Error("Error! Class " + cd.getSymbol() + " extends interface " + cd.getSuper());
62           }
63           // Link together Field, Method, and Flag tables so classes
64           // inherit these from their superclasses
65           cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
66           cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
67           cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
68         }
69         // Link together Field, Method tables do classes inherit these from 
70         // their ancestor interfaces
71         Vector<String> sifv = cd.getSuperInterface();
72         for(int i = 0; i < sifv.size(); i++) {
73           ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck);
74           if(!superif.isInterface()) {
75             throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol());
76           }
77           cd.addSuperInterfaces(superif);
78           cd.getFieldTable().addParentIF(superif.getFieldTable());
79           cd.getMethodTable().addParentIF(superif.getMethodTable());
80         }
81       }
82       if (oldstatus<INIT&&fullcheck>=INIT) {
83         /* Check to see that fields are well typed */
84         for(Iterator field_it=cd.getFields(); field_it.hasNext();) {
85           FieldDescriptor fd=(FieldDescriptor)field_it.next();
86           checkField(cd,fd);
87         }
88         for(Iterator method_it=cd.getMethods(); method_it.hasNext();) {
89           MethodDescriptor md=(MethodDescriptor)method_it.next();
90           checkMethod(cd,md);
91         }
92       }
93     }
94   }
95
96   public void semanticCheck() {
97     SymbolTable classtable = state.getClassSymbolTable();
98     toanalyze.addAll(classtable.getValueSet());
99     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
100
101     // Do methods next
102     while (!toanalyze.isEmpty()) {
103       Object obj = toanalyze.iterator().next();
104       if (obj instanceof TaskDescriptor) {
105         toanalyze.remove(obj);
106         TaskDescriptor td = (TaskDescriptor) obj;
107         try {
108           checkTask(td);
109         } catch (Error e) {
110           System.out.println("Error in " + td);
111           throw e;
112         }
113       } else {
114         ClassDescriptor cd = (ClassDescriptor) obj;
115         toanalyze.remove(cd);
116         
117         // need to initialize typeutil object here...only place we can
118         // get class descriptors without first calling getclass
119         getClass(cd, cd.getSymbol());
120         for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
121           MethodDescriptor md = (MethodDescriptor) method_it.next();
122           try {
123             checkMethodBody(cd, md);
124           } catch (Error e) {
125             System.out.println("Error in " + md);
126             throw e;
127           }
128         }
129       }
130     }
131   }
132
133   private void checkTypeDescriptor(ClassDescriptor cd, TypeDescriptor td) {
134     if (td.isPrimitive())
135       return;       /* Done */
136     else if (td.isClass()) {
137       String name=td.toString();
138       int index = name.lastIndexOf('.');
139       if(index != -1) {
140         name = name.substring(index+1);
141       }
142       ClassDescriptor field_cd=checkAll?getClass(cd, name):getClass(cd, name, REFERENCE);
143
144       if (field_cd==null)
145         throw new Error("Undefined class "+name);
146       td.setClassDescriptor(field_cd);
147       return;
148     } else if (td.isTag())
149       return;
150     else
151       throw new Error();
152   }
153
154   public void checkField(ClassDescriptor cd, FieldDescriptor fd) {
155     checkTypeDescriptor(cd, fd.getType());
156   }
157
158   public void checkConstraintCheck(TaskDescriptor td, SymbolTable nametable, Vector ccs) {
159     if (ccs==null)
160       return;       /* No constraint checks to check */
161     for(int i=0; i<ccs.size(); i++) {
162       ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
163
164       for(int j=0; j<cc.numArgs(); j++) {
165         ExpressionNode en=cc.getArg(j);
166         checkExpressionNode(td,nametable,en,null);
167       }
168     }
169   }
170
171   public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
172     if (vfe==null)
173       return;       /* No flag effects to check */
174     for(int i=0; i<vfe.size(); i++) {
175       FlagEffects fe=(FlagEffects) vfe.get(i);
176       String varname=fe.getName();
177       //Make sure the variable is declared as a parameter to the task
178       VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
179       if (vd==null)
180         throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
181       fe.setVar(vd);
182
183       //Make sure it correspods to a class
184       TypeDescriptor type_d=vd.getType();
185       if (!type_d.isClass())
186         throw new Error("Cannot have non-object argument for flag_effect");
187
188       ClassDescriptor cd=type_d.getClassDesc();
189       for(int j=0; j<fe.numEffects(); j++) {
190         FlagEffect flag=fe.getEffect(j);
191         String name=flag.getName();
192         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
193         //Make sure the flag is declared
194         if (flag_d==null)
195           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
196         if (flag_d.getExternal())
197           throw new Error("Attempting to modify external flag: "+name);
198         flag.setFlag(flag_d);
199       }
200       for(int j=0; j<fe.numTagEffects(); j++) {
201         TagEffect tag=fe.getTagEffect(j);
202         String name=tag.getName();
203
204         Descriptor d=(Descriptor)nametable.get(name);
205         if (d==null)
206           throw new Error("Tag descriptor "+name+" undeclared");
207         else if (!(d instanceof TagVarDescriptor))
208           throw new Error(name+" is not a tag descriptor");
209         tag.setTag((TagVarDescriptor)d);
210       }
211     }
212   }
213
214   public void checkTask(TaskDescriptor td) {
215     for(int i=0; i<td.numParameters(); i++) {
216       /* Check that parameter is well typed */
217       TypeDescriptor param_type=td.getParamType(i);
218       checkTypeDescriptor(null, param_type);
219
220       /* Check the parameter's flag expression is well formed */
221       FlagExpressionNode fen=td.getFlag(td.getParameter(i));
222       if (!param_type.isClass())
223         throw new Error("Cannot have non-object argument to a task");
224       ClassDescriptor cd=param_type.getClassDesc();
225       if (fen!=null)
226         checkFlagExpressionNode(cd, fen);
227     }
228
229     checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
230     /* Check that the task code is valid */
231     BlockNode bn=state.getMethodBody(td);
232     checkBlockNode(td, td.getParameterTable(),bn);
233   }
234
235   public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
236     switch(fen.kind()) {
237     case Kind.FlagOpNode:
238     {
239       FlagOpNode fon=(FlagOpNode)fen;
240       checkFlagExpressionNode(cd, fon.getLeft());
241       if (fon.getRight()!=null)
242         checkFlagExpressionNode(cd, fon.getRight());
243       break;
244     }
245
246     case Kind.FlagNode:
247     {
248       FlagNode fn=(FlagNode)fen;
249       String name=fn.getFlagName();
250       FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
251       if (fd==null)
252         throw new Error("Undeclared flag: "+name);
253       fn.setFlag(fd);
254       break;
255     }
256
257     default:
258       throw new Error("Unrecognized FlagExpressionNode");
259     }
260   }
261
262   public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
263     /* Check for abstract methods */
264     if(md.isAbstract()) {
265       if(!cd.isAbstract() && !cd.isInterface()) {
266         throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
267       }
268     }
269
270     /* Check return type */
271     if (!md.isConstructor() && !md.isStaticBlock())
272       if (!md.getReturnType().isVoid()) {
273         checkTypeDescriptor(cd, md.getReturnType());
274       }
275     for(int i=0; i<md.numParameters(); i++) {
276       TypeDescriptor param_type=md.getParamType(i);
277       checkTypeDescriptor(cd, param_type);
278     }
279     /* Link the naming environments */
280     if (!md.isStatic())     /* Fields aren't accessible directly in a static method, so don't link in this table */
281       md.getParameterTable().setParent(cd.getFieldTable());
282     md.setClassDesc(cd);
283     if (!md.isStatic()) {
284       VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
285       md.setThis(thisvd);
286     }
287     if(md.isDefaultConstructor() && (cd.getSuperDesc() != null)) {
288       // add the construction of it super class, can only be super()
289       NameDescriptor nd=new NameDescriptor("super");
290       MethodInvokeNode min=new MethodInvokeNode(nd);
291       BlockExpressionNode ben=new BlockExpressionNode(min);
292       BlockNode bn = state.getMethodBody(md);
293       bn.addFirstBlockStatement(ben);
294     }
295   }
296
297   public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
298     ClassDescriptor superdesc=cd.getSuperDesc();
299     if (superdesc!=null) {
300       Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
301       for(Iterator methodit=possiblematches.iterator(); methodit.hasNext();) {
302         MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
303         if (md.matches(matchmd)) {
304           if (matchmd.getModifiers().isFinal()) {
305             throw new Error("Try to override final method in method:"+md+" declared in  "+cd);
306           }
307         }
308       }
309     }
310     BlockNode bn=state.getMethodBody(md);
311     checkBlockNode(md, md.getParameterTable(),bn);
312   }
313
314   public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
315     /* Link in the naming environment */
316     bn.getVarTable().setParent(nametable);
317     for(int i=0; i<bn.size(); i++) {
318       BlockStatementNode bsn=bn.get(i);
319       checkBlockStatementNode(md, bn.getVarTable(),bsn);
320     }
321   }
322
323   public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
324     switch(bsn.kind()) {
325     case Kind.BlockExpressionNode:
326       checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
327       return;
328
329     case Kind.DeclarationNode:
330       checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
331       return;
332
333     case Kind.TagDeclarationNode:
334       checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
335       return;
336
337     case Kind.IfStatementNode:
338       checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
339       return;
340       
341     case Kind.SwitchStatementNode:
342       checkSwitchStatementNode(md, nametable, (SwitchStatementNode)bsn);
343       return;
344
345     case Kind.LoopNode:
346       checkLoopNode(md, nametable, (LoopNode)bsn);
347       return;
348
349     case Kind.ReturnNode:
350       checkReturnNode(md, nametable, (ReturnNode)bsn);
351       return;
352
353     case Kind.TaskExitNode:
354       checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
355       return;
356
357     case Kind.SubBlockNode:
358       checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
359       return;
360
361     case Kind.AtomicNode:
362       checkAtomicNode(md, nametable, (AtomicNode)bsn);
363       return;
364
365     case Kind.SynchronizedNode:
366       checkSynchronizedNode(md, nametable, (SynchronizedNode)bsn);
367       return;
368
369     case Kind.ContinueBreakNode:
370         checkContinueBreakNode(md, nametable, (ContinueBreakNode) bsn);
371         return;
372
373     case Kind.SESENode:
374     case Kind.GenReachNode:
375       // do nothing, no semantic check for SESEs
376       return;
377     }
378
379     throw new Error();
380   }
381
382   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
383     checkExpressionNode(md, nametable, ben.getExpression(), null);
384   }
385
386   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
387     VarDescriptor vd=dn.getVarDescriptor();
388     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), vd.getType());
389     Descriptor d=nametable.get(vd.getSymbol());
390     if ((d==null)||
391         (d instanceof FieldDescriptor)) {
392       nametable.add(vd);
393     } else
394       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
395     if (dn.getExpression()!=null)
396       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
397   }
398
399   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
400     TagVarDescriptor vd=dn.getTagVarDescriptor();
401     Descriptor d=nametable.get(vd.getSymbol());
402     if ((d==null)||
403         (d instanceof FieldDescriptor)) {
404       nametable.add(vd);
405     } else
406       throw new Error(vd.getSymbol()+" defined a second time");
407   }
408
409   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
410     checkBlockNode(md, nametable, sbn.getBlockNode());
411   }
412
413   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
414     checkBlockNode(md, nametable, sbn.getBlockNode());
415   }
416
417   void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
418     checkBlockNode(md, nametable, sbn.getBlockNode());
419     //todo this could be Object
420     checkExpressionNode(md, nametable, sbn.getExpr(), null);
421   }
422
423   void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
424       if (loopstack.empty())
425           throw new Error("continue/break outside of loop");
426       Object o = loopstack.peek();
427       if(o instanceof LoopNode) {
428         LoopNode ln=(LoopNode)o;
429         cbn.setLoop(ln);
430       }
431   }
432
433   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
434     if (d instanceof TaskDescriptor)
435       throw new Error("Illegal return appears in Task: "+d.getSymbol());
436     MethodDescriptor md=(MethodDescriptor)d;
437     if (rn.getReturnExpression()!=null)
438       if (md.getReturnType()==null)
439         throw new Error("Constructor can't return something.");
440       else if (md.getReturnType().isVoid())
441         throw new Error(md+" is void");
442       else
443         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
444     else
445     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
446       throw new Error("Need to return something for "+md);
447   }
448
449   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
450     if (md instanceof MethodDescriptor)
451       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
452     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
453     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
454   }
455
456   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
457     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
458     checkBlockNode(md, nametable, isn.getTrueBlock());
459     if (isn.getFalseBlock()!=null)
460       checkBlockNode(md, nametable, isn.getFalseBlock());
461   }
462   
463   void checkSwitchStatementNode(Descriptor md, SymbolTable nametable, SwitchStatementNode ssn) {
464     checkExpressionNode(md, nametable, ssn.getCondition(), new TypeDescriptor(TypeDescriptor.INT));
465     
466     BlockNode sbn = ssn.getSwitchBody();
467     boolean hasdefault = false;
468     for(int i = 0; i < sbn.size(); i++) {
469       boolean containdefault = checkSwitchBlockNode(md, nametable, (SwitchBlockNode)sbn.get(i));
470       if(hasdefault && containdefault) {
471         throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
472       }
473       hasdefault = containdefault;
474     }
475   }
476   
477   boolean checkSwitchBlockNode(Descriptor md, SymbolTable nametable, SwitchBlockNode sbn) {
478     Vector<SwitchLabelNode> slnv = sbn.getSwitchConditions();
479     int defaultb = 0;
480     for(int i = 0; i < slnv.size(); i++) {
481       if(slnv.elementAt(i).isdefault) {
482         defaultb++;
483       } else {
484         checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
485       }
486     }
487     if(defaultb > 1) {
488       throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
489     } else {
490       loopstack.push(sbn);
491       checkBlockNode(md, nametable, sbn.getSwitchBlockStatement());
492       loopstack.pop();
493       return (defaultb > 0);
494     }
495   }
496   
497   void checkConstantExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
498     switch(en.kind()) {
499     case Kind.FieldAccessNode:
500       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
501       return;
502      
503     case Kind.LiteralNode:
504       checkLiteralNode(md,nametable,(LiteralNode)en,td);
505       return;
506       
507     case Kind.NameNode:
508       checkNameNode(md,nametable,(NameNode)en,td);
509       return;
510       
511     case Kind.OpNode:
512       checkOpNode(md, nametable, (OpNode)en, td);
513       return;
514     }
515     throw new Error();
516   }
517
518   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
519     switch(en.kind()) {
520     case Kind.AssignmentNode:
521       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
522       return;
523
524     case Kind.CastNode:
525       checkCastNode(md,nametable,(CastNode)en,td);
526       return;
527
528     case Kind.CreateObjectNode:
529       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
530       return;
531
532     case Kind.FieldAccessNode:
533       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
534       return;
535
536     case Kind.ArrayAccessNode:
537       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
538       return;
539
540     case Kind.LiteralNode:
541       checkLiteralNode(md,nametable,(LiteralNode)en,td);
542       return;
543
544     case Kind.MethodInvokeNode:
545       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
546       return;
547
548     case Kind.NameNode:
549       checkNameNode(md,nametable,(NameNode)en,td);
550       return;
551
552     case Kind.OpNode:
553       checkOpNode(md,nametable,(OpNode)en,td);
554       return;
555
556     case Kind.OffsetNode:
557       checkOffsetNode(md, nametable, (OffsetNode)en, td);
558       return;
559
560     case Kind.TertiaryNode:
561       checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
562       return;
563       
564     case Kind.InstanceOfNode:
565       checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
566       return;
567
568     case Kind.ArrayInitializerNode:
569       checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
570       return;
571      
572     case Kind.ClassTypeNode:
573       checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
574       return;
575     }
576     throw new Error();
577   }
578
579   void checkClassTypeNode(Descriptor md, SymbolTable nametable, ClassTypeNode tn, TypeDescriptor td) {
580     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getType());
581   }
582   
583   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
584     /* Get type descriptor */
585     if (cn.getType()==null) {
586       NameDescriptor typenamed=cn.getTypeName().getName();
587       TypeDescriptor ntd=new TypeDescriptor(getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typenamed.toString()));
588       cn.setType(ntd);
589     }
590
591     /* Check the type descriptor */
592     TypeDescriptor cast_type=cn.getType();
593     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),cast_type);
594
595     /* Type check */
596     if (td!=null) {
597       if (!typeutil.isSuperorType(td,cast_type))
598         throw new Error("Cast node returns "+cast_type+", but need "+td);
599     }
600
601     ExpressionNode en=cn.getExpression();
602     checkExpressionNode(md, nametable, en, null);
603     TypeDescriptor etd=en.getType();
604     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
605       return;
606
607     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
608       return;
609     if (typeutil.isCastable(etd, cast_type))
610       return;
611
612     /* Different branches */
613     /* TODO: change if add interfaces */
614     throw new Error("Cast will always fail\n"+cn.printNode(0));
615   }
616
617   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
618     ExpressionNode left=fan.getExpression();
619     checkExpressionNode(md,nametable,left,null);
620     TypeDescriptor ltd=left.getType();
621     String fieldname=fan.getFieldName();
622
623     FieldDescriptor fd=null;
624     if (ltd.isArray()&&fieldname.equals("length"))
625       fd=FieldDescriptor.arrayLength;
626     else
627       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
628
629     if(ltd.isClassNameRef()) {
630       // the field access is using a class name directly
631       if(ltd.getClassDesc().isEnum()) {
632         int value = ltd.getClassDesc().getEnumConstant(fieldname);
633         if(-1 == value) {
634           // check if this field is an enum constant
635           throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
636         }
637         fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
638         fd.setAsEnum();
639         fd.setEnumValue(value);
640       } else if(fd == null) {
641         throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
642       } else if(fd.isStatic()) {
643         // check if this field is a static field
644         if(fd.getExpressionNode() != null) {
645           checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
646         }
647       } else {
648         throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
649       }
650     } 
651
652     if (fd==null)
653       throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
654
655     if (fd.getType().iswrapper()) {
656       FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
657       fan2.setNumLine(left.getNumLine());
658       fan2.setField(fd);
659       fan.left=fan2;
660       fan.fieldname="value";
661
662       ExpressionNode leftwr=fan.getExpression();
663       TypeDescriptor ltdwr=leftwr.getType();
664       String fieldnamewr=fan.getFieldName();
665       FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
666       fan.setField(fdwr);
667       if (fdwr==null)
668           throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
669     } else {
670       fan.setField(fd);
671     }
672     if (td!=null) {
673       if (!typeutil.isSuperorType(td,fan.getType()))
674         throw new Error("Field node returns "+fan.getType()+", but need "+td);
675     }
676   }
677
678   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
679     ExpressionNode left=aan.getExpression();
680     checkExpressionNode(md,nametable,left,null);
681
682     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
683     TypeDescriptor ltd=left.getType();
684     if (ltd.dereference().iswrapper()) {
685       aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
686     }
687
688     if (td!=null)
689       if (!typeutil.isSuperorType(td,aan.getType()))
690         throw new Error("Field node returns "+aan.getType()+", but need "+td);
691   }
692
693   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
694     /* Resolve the type */
695     Object o=ln.getValue();
696     if (ln.getTypeString().equals("null")) {
697       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
698     } else if (o instanceof Integer) {
699       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
700     } else if (o instanceof Long) {
701       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
702     } else if (o instanceof Float) {
703       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
704     } else if (o instanceof Boolean) {
705       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
706     } else if (o instanceof Double) {
707       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
708     } else if (o instanceof Character) {
709       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
710     } else if (o instanceof String) {
711       ln.setType(new TypeDescriptor(getClass(null, TypeUtil.StringClass)));
712     }
713
714     if (td!=null)
715       if (!typeutil.isSuperorType(td,ln.getType())) {
716         Long l = ln.evaluate();
717         if((ln.getType().isByte() || ln.getType().isShort() 
718             || ln.getType().isChar() || ln.getType().isInt()) 
719             && (l != null) 
720             && (td.isByte() || td.isShort() || td.isChar() 
721                 || td.isInt() || td.isLong())) {
722           long lnvalue = l.longValue();
723           if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128))) 
724               || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
725               || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
726               || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
727               || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
728             throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
729           }
730         } else {
731           throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
732         }
733       }
734   }
735
736   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
737     NameDescriptor nd=nn.getName();
738     if (nd.getBase()!=null) {
739       /* Big hack */
740       /* Rewrite NameNode */
741       ExpressionNode en=translateNameDescriptorintoExpression(nd,nn.getNumLine());
742       nn.setExpression(en);
743       checkExpressionNode(md,nametable,en,td);
744     } else {
745       String varname=nd.toString();
746       if(varname.equals("this")) {
747         // "this"
748         nn.setVar((VarDescriptor)nametable.get("this")); 
749         return;
750       }
751       Descriptor d=(Descriptor)nametable.get(varname);
752       if (d==null) {
753         ClassDescriptor cd = null;
754         if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
755           // this is a static block, all the accessed fields should be static field
756           cd = ((MethodDescriptor)md).getClassDesc();
757           SymbolTable fieldtbl = cd.getFieldTable();
758           FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
759           if((fd == null) || (!fd.isStatic())){
760             // no such field in the class, check if this is a class
761             if(varname.equals("this")) {
762               throw new Error("Error: access this obj in a static block");
763             }
764             cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
765             if(cd != null) {
766               // this is a class name
767               nn.setClassDesc(cd);
768               return;
769             } else {
770               throw new Error("Name "+varname+" should not be used in static block: "+md);
771             }
772           } else {
773             // this is a static field
774             nn.setField(fd);
775             nn.setClassDesc(cd);
776             return;
777           }
778         } else {
779           // check if the var is a static field of the class
780           if(md instanceof MethodDescriptor) {
781             cd = ((MethodDescriptor)md).getClassDesc();
782             FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
783             if((fd != null) && (fd.isStatic())) {
784               nn.setField(fd);
785               nn.setClassDesc(cd);
786               if (td!=null)
787                 if (!typeutil.isSuperorType(td,nn.getType()))
788                   throw new Error("Field node returns "+nn.getType()+", but need "+td);
789               return;
790             } else if(fd != null) {
791               throw new Error("Name "+varname+" should not be used in " + md);
792             }
793           }
794           cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
795           if(cd != null) {
796             // this is a class name
797             nn.setClassDesc(cd);
798             return;
799           } else {
800             throw new Error("Name "+varname+" undefined in: "+md);
801           }
802         }
803       }
804       if (d instanceof VarDescriptor) {
805         nn.setVar(d);
806       } else if (d instanceof FieldDescriptor) {
807         FieldDescriptor fd=(FieldDescriptor)d;
808         if (fd.getType().iswrapper()) {
809           String id=nd.getIdentifier();
810           NameDescriptor base=nd.getBase();
811           NameNode n=new NameNode(nn.getName());
812           n.setNumLine(nn.getNumLine());
813           n.setField(fd);
814           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
815           FieldAccessNode fan=new FieldAccessNode(n,"value");
816           fan.setNumLine(n.getNumLine());
817           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
818           fan.setField(fdval);
819           nn.setExpression(fan);
820         } else {
821           nn.setField(fd);
822           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
823         }
824       } else if (d instanceof TagVarDescriptor) {
825         nn.setVar(d);
826       } else throw new Error("Wrong type of descriptor");
827       if (td!=null)
828         if (!typeutil.isSuperorType(td,nn.getType()))
829           throw new Error("Field node returns "+nn.getType()+", but need "+td);
830     }
831   }
832
833   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
834     TypeDescriptor ltd=ofn.td;
835     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),ltd);
836     
837     String fieldname = ofn.fieldname;
838     FieldDescriptor fd=null;
839     if (ltd.isArray()&&fieldname.equals("length")) {
840       fd=FieldDescriptor.arrayLength;
841     } else {
842       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
843     }
844
845     ofn.setField(fd);
846     checkField(ltd.getClassDesc(), fd);
847
848     if (fd==null)
849       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
850
851     if (td!=null) {
852       if (!typeutil.isSuperorType(td, ofn.getType())) {
853         System.out.println(td);
854         System.out.println(ofn.getType());
855         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
856       }
857     }
858   }
859
860
861   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
862     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
863     checkExpressionNode(md, nametable, tn.getTrueExpr(), td );
864     checkExpressionNode(md, nametable, tn.getFalseExpr(), td );
865   }
866
867   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
868     if (td!=null&&!td.isBoolean())
869       throw new Error("Expecting type "+td+"for instanceof expression");
870     
871     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getExprType());
872     checkExpressionNode(md, nametable, tn.getExpr(), null);
873   }
874
875   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
876     Vector<TypeDescriptor> vec_type = new Vector<TypeDescriptor>();
877     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
878       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td==null?td:td.dereference());
879       vec_type.add(ain.getVarInitializer(i).getType());
880     }
881     // descide the type of this variableInitializerNode
882     TypeDescriptor out_type = vec_type.elementAt(0);
883     for(int i = 1; i < vec_type.size(); i++) {
884       TypeDescriptor tmp_type = vec_type.elementAt(i);
885       if(out_type == null) {
886         if(tmp_type != null) {
887           out_type = tmp_type;
888         }
889       } else if(out_type.isNull()) {
890         if(!tmp_type.isNull() ) {
891           if(!tmp_type.isArray()) {
892             throw new Error("Error: mixed type in var initializer list");
893           } else {
894             out_type = tmp_type;
895           }
896         }
897       } else if(out_type.isArray()) {
898         if(tmp_type.isArray()) {
899           if(tmp_type.getArrayCount() > out_type.getArrayCount()) {
900             out_type = tmp_type;
901           }
902         } else if((tmp_type != null) && (!tmp_type.isNull())) {
903           throw new Error("Error: mixed type in var initializer list");
904         }
905       } else if(out_type.isInt()) {
906         if(!tmp_type.isInt()) {
907           throw new Error("Error: mixed type in var initializer list");
908         }
909       } else if(out_type.isString()) {
910         if(!tmp_type.isString()) {
911           throw new Error("Error: mixed type in var initializer list");
912         }
913       }
914     }
915     if(out_type != null) {
916       out_type = out_type.makeArray(state);
917       //out_type.setStatic();
918     }
919     ain.setType(out_type);
920   }
921
922   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
923     boolean postinc=true;
924     if (an.getOperation().getBaseOp()==null||
925         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
926          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
927       postinc=false;
928     if (!postinc)      
929       checkExpressionNode(md, nametable, an.getSrc(),td);
930     //TODO: Need check on validity of operation here
931     if (!((an.getDest() instanceof FieldAccessNode)||
932           (an.getDest() instanceof ArrayAccessNode)||
933           (an.getDest() instanceof NameNode)))
934       throw new Error("Bad lside in "+an.printNode(0));
935     checkExpressionNode(md, nametable, an.getDest(), null);
936
937     /* We want parameter variables to tasks to be immutable */
938     if (md instanceof TaskDescriptor) {
939       if (an.getDest() instanceof NameNode) {
940         NameNode nn=(NameNode)an.getDest();
941         if (nn.getVar()!=null) {
942           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
943             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
944         }
945       }
946     }
947
948     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
949       //String add
950       ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
951       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
952       NameDescriptor nd=new NameDescriptor("String");
953       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
954
955       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
956         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
957         rightmin.setNumLine(an.getSrc().getNumLine());
958         rightmin.addArgument(an.getSrc());
959         an.right=rightmin;
960         checkExpressionNode(md, nametable, an.getSrc(), null);
961       }
962     }
963
964     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
965       TypeDescriptor dt = an.getDest().getType();
966       TypeDescriptor st = an.getSrc().getType();
967       if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
968         if(dt.getArrayCount() != st.getArrayCount()) {
969           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
970         } else {
971           do {
972             dt = dt.dereference();
973             st = st.dereference();
974           } while(dt.isArray());
975           if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) 
976               && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
977             return;
978           } else {
979             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
980           }
981         }
982       } else {
983         Long l = an.getSrc().evaluate();
984         if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) 
985             && (l != null) 
986             && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
987           long lnvalue = l.longValue();
988           if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128))) 
989               || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
990               || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
991               || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
992               || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
993             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
994           }
995         } else {
996           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
997         }
998       }
999     }
1000   }
1001
1002   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
1003       loopstack.push(ln);
1004     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
1005       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1006       checkBlockNode(md, nametable, ln.getBody());
1007     } else {
1008       //For loop case
1009       /* Link in the initializer naming environment */
1010       BlockNode bn=ln.getInitializer();
1011       bn.getVarTable().setParent(nametable);
1012       for(int i=0; i<bn.size(); i++) {
1013         BlockStatementNode bsn=bn.get(i);
1014         checkBlockStatementNode(md, bn.getVarTable(),bsn);
1015       }
1016       //check the condition
1017       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1018       checkBlockNode(md, bn.getVarTable(), ln.getBody());
1019       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
1020     }
1021     loopstack.pop();
1022   }
1023
1024
1025   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con,
1026       TypeDescriptor td) {
1027     TypeDescriptor[] tdarray = new TypeDescriptor[con.numArgs()];
1028     for (int i = 0; i < con.numArgs(); i++) {
1029       ExpressionNode en = con.getArg(i);
1030       checkExpressionNode(md, nametable, en, null);
1031       tdarray[i] = en.getType();
1032     }
1033
1034     TypeDescriptor typetolookin = con.getType();
1035     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typetolookin);
1036
1037     if (td != null && !typeutil.isSuperorType(td, typetolookin))
1038       throw new Error(typetolookin + " isn't a " + td);
1039
1040     /* Check Array Initializers */
1041     if ((con.getArrayInitializer() != null)) {
1042       checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), td);
1043     }
1044
1045     /* Check flag effects */
1046     if (con.getFlagEffects() != null) {
1047       FlagEffects fe = con.getFlagEffects();
1048       ClassDescriptor cd = typetolookin.getClassDesc();
1049
1050       for (int j = 0; j < fe.numEffects(); j++) {
1051         FlagEffect flag = fe.getEffect(j);
1052         String name = flag.getName();
1053         FlagDescriptor flag_d = (FlagDescriptor) cd.getFlagTable().get(name);
1054         // Make sure the flag is declared
1055         if (flag_d == null)
1056           throw new Error("Flag descriptor " + name + " undefined in class: " + cd.getSymbol());
1057         if (flag_d.getExternal())
1058           throw new Error("Attempting to modify external flag: " + name);
1059         flag.setFlag(flag_d);
1060       }
1061       for (int j = 0; j < fe.numTagEffects(); j++) {
1062         TagEffect tag = fe.getTagEffect(j);
1063         String name = tag.getName();
1064
1065         Descriptor d = (Descriptor) nametable.get(name);
1066         if (d == null)
1067           throw new Error("Tag descriptor " + name + " undeclared");
1068         else if (!(d instanceof TagVarDescriptor))
1069           throw new Error(name + " is not a tag descriptor");
1070         tag.setTag((TagVarDescriptor) d);
1071       }
1072     }
1073
1074     if ((!typetolookin.isClass()) && (!typetolookin.isArray()))
1075       throw new Error("Can't allocate primitive type:" + con.printNode(0));
1076
1077     if (!typetolookin.isArray()) {
1078       // Array's don't need constructor calls
1079       ClassDescriptor classtolookin = typetolookin.getClassDesc();
1080
1081       Set methoddescriptorset = classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
1082       MethodDescriptor bestmd = null;
1083       NextMethod: for (Iterator methodit = methoddescriptorset.iterator(); methodit.hasNext();) {
1084         MethodDescriptor currmd = (MethodDescriptor) methodit.next();
1085         /* Need correct number of parameters */
1086         if (con.numArgs() != currmd.numParameters())
1087           continue;
1088         for (int i = 0; i < con.numArgs(); i++) {
1089           if (!typeutil.isSuperorType(currmd.getParamType(i), tdarray[i]))
1090             continue NextMethod;
1091         }
1092         /* Local allocations can't call global allocator */
1093         if (!con.isGlobal() && currmd.isGlobal())
1094           continue;
1095
1096         /* Method okay so far */
1097         if (bestmd == null)
1098           bestmd = currmd;
1099         else {
1100           if (typeutil.isMoreSpecific(currmd, bestmd)) {
1101             bestmd = currmd;
1102           } else if (con.isGlobal() && match(currmd, bestmd)) {
1103             if (currmd.isGlobal() && !bestmd.isGlobal())
1104               bestmd = currmd;
1105             else if (currmd.isGlobal() && bestmd.isGlobal())
1106               throw new Error();
1107           } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
1108             throw new Error("No method is most specific:" + bestmd + " and " + currmd);
1109           }
1110
1111           /* Is this more specific than bestmd */
1112         }
1113       }
1114       if (bestmd == null)
1115         throw new Error("No method found for " + con.printNode(0) + " in " + md);
1116       con.setConstructor(bestmd);
1117     }
1118   }
1119
1120
1121   /** Check to see if md1 is the same specificity as md2.*/
1122
1123   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1124     /* Checks if md1 is more specific than md2 */
1125     if (md1.numParameters()!=md2.numParameters())
1126       throw new Error();
1127     for(int i=0; i<md1.numParameters(); i++) {
1128       if (!md2.getParamType(i).equals(md1.getParamType(i)))
1129         return false;
1130     }
1131     if (!md2.getReturnType().equals(md1.getReturnType()))
1132       return false;
1133
1134     if (!md2.getClassDesc().equals(md1.getClassDesc()))
1135       return false;
1136
1137     return true;
1138   }
1139
1140
1141
1142   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd, int numLine) {
1143     String id=nd.getIdentifier();
1144     NameDescriptor base=nd.getBase();
1145     if (base==null){
1146       NameNode nn=new NameNode(nd);
1147       nn.setNumLine(numLine);
1148       return nn;
1149     }else{
1150       FieldAccessNode fan=new FieldAccessNode(translateNameDescriptorintoExpression(base,numLine),id);
1151       fan.setNumLine(numLine);
1152       return fan;
1153     }
1154   }
1155
1156
1157   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1158     /*Typecheck subexpressions
1159        and get types for expressions*/
1160
1161     boolean isstatic = false;
1162     if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStatic()) {
1163       isstatic = true;
1164     }
1165     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1166     for(int i=0; i<min.numArgs(); i++) {
1167       ExpressionNode en=min.getArg(i);
1168       checkExpressionNode(md,nametable,en,null);
1169       tdarray[i]=en.getType();
1170       if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1171         tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1172       }
1173     }
1174     TypeDescriptor typetolookin=null;
1175     if (min.getExpression()!=null) {
1176       checkExpressionNode(md,nametable,min.getExpression(),null);
1177       typetolookin=min.getExpression().getType();
1178       //if (typetolookin==null)
1179       //throw new Error(md+" has null return type");
1180
1181     } else if (min.getBaseName()!=null) {
1182       String rootname=min.getBaseName().getRoot();
1183       if (rootname.equals("super")) {
1184         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1185         typetolookin=new TypeDescriptor(supercd);
1186         min.setSuper();
1187       } else if (rootname.equals("this")) {
1188         if(isstatic) {
1189           throw new Error("use this object in static method md = "+ md.toString());
1190         }
1191         ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
1192         typetolookin=new TypeDescriptor(cd);
1193       } else if (nametable.get(rootname)!=null) {
1194         //we have an expression
1195         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
1196         checkExpressionNode(md, nametable, min.getExpression(), null);
1197         typetolookin=min.getExpression().getType();
1198       } else {
1199         if(!min.getBaseName().getSymbol().equals("System.out")) {
1200           ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
1201           checkExpressionNode(md, nametable, nn, null);
1202           typetolookin = nn.getType();
1203           if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
1204                && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
1205             // this is not a pure class name, need to add to 
1206             min.setExpression(nn);
1207           }
1208         } else {
1209           //we have a type
1210           ClassDescriptor cd = null;
1211           //if (min.getBaseName().getSymbol().equals("System.out"))
1212           cd=getClass(null, "System");
1213           /*else {
1214             cd=getClass(min.getBaseName().getSymbol());
1215             }*/
1216           if (cd==null)
1217             throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
1218           typetolookin=new TypeDescriptor(cd);
1219         }
1220       }
1221     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1222       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1223       min.methodid=supercd.getSymbol();
1224       typetolookin=new TypeDescriptor(supercd);
1225     } else if (md instanceof MethodDescriptor) {
1226       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1227     } else {
1228       /* If this a task descriptor we throw an error at this point */
1229       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1230     }
1231     if (!typetolookin.isClass())
1232       throw new Error("Error with method call to "+min.getMethodName());
1233     ClassDescriptor classtolookin=typetolookin.getClassDesc();
1234     //System.out.println("Method name="+min.getMethodName());
1235
1236     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1237     MethodDescriptor bestmd=null;
1238 NextMethod:
1239     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
1240       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1241       /* Need correct number of parameters */
1242       if (min.numArgs()!=currmd.numParameters())
1243         continue;
1244       for(int i=0; i<min.numArgs(); i++) {
1245         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1246           if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong())) 
1247               && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
1248             // primitive parameters vs object
1249           } else {
1250             continue NextMethod;
1251           }
1252       }
1253       /* Method okay so far */
1254       if (bestmd==null)
1255         bestmd=currmd;
1256       else {
1257         if (typeutil.isMoreSpecific(currmd,bestmd)) {
1258           bestmd=currmd;
1259         } else if (!typeutil.isMoreSpecific(bestmd, currmd))
1260           throw new Error("No method is most specific:"+bestmd+" and "+currmd);
1261
1262         /* Is this more specific than bestmd */
1263       }
1264     }
1265     if (bestmd==null)
1266       throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1267     min.setMethod(bestmd);
1268
1269     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
1270       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1271     /* Check whether we need to set this parameter to implied this */
1272     if (! isstatic && !bestmd.isStatic()) {
1273       if (min.getExpression()==null) {
1274         ExpressionNode en=new NameNode(new NameDescriptor("this"));
1275         min.setExpression(en);
1276         checkExpressionNode(md, nametable, min.getExpression(), null);
1277       }
1278     }
1279     
1280     /* Check if we need to wrap primitive paratmeters to objects */
1281     for(int i=0; i<min.numArgs(); i++) {
1282       if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
1283          && min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
1284         // Shall wrap this primitive parameter as a object
1285         ExpressionNode exp = min.getArg(i);
1286         TypeDescriptor ptd = null;
1287         NameDescriptor nd=null;
1288         if(exp.getType().isInt()) {
1289           nd = new NameDescriptor("Integer");
1290           ptd = state.getTypeDescriptor(nd);
1291         } else if(exp.getType().isLong()) {
1292           nd = new NameDescriptor("Long");
1293           ptd = state.getTypeDescriptor(nd);
1294         }
1295         boolean isglobal = false;
1296         String disjointId = null;
1297         CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
1298         con.addArgument(exp);
1299         checkExpressionNode(md, nametable, con, null);
1300         min.setArgument(con, i);
1301       }
1302     }
1303   }
1304
1305
1306   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1307     checkExpressionNode(md, nametable, on.getLeft(), null);
1308     if (on.getRight()!=null)
1309       checkExpressionNode(md, nametable, on.getRight(), null);
1310     TypeDescriptor ltd=on.getLeft().getType();
1311     TypeDescriptor rtd=on.getRight()!=null ? on.getRight().getType() : null;
1312     TypeDescriptor lefttype=null;
1313     TypeDescriptor righttype=null;
1314     Operation op=on.getOp();
1315
1316     switch(op.getOp()) {
1317     case Operation.LOGIC_OR:
1318     case Operation.LOGIC_AND:
1319       if (!(rtd.isBoolean()))
1320         throw new Error();
1321       on.setRightType(rtd);
1322
1323     case Operation.LOGIC_NOT:
1324       if (!(ltd.isBoolean()))
1325         throw new Error();
1326       //no promotion
1327       on.setLeftType(ltd);
1328
1329       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1330       break;
1331
1332     case Operation.COMP:
1333       // 5.6.2 Binary Numeric Promotion
1334       //TODO unboxing of reference objects
1335       if (ltd.isDouble())
1336         throw new Error();
1337       else if (ltd.isFloat())
1338         throw new Error();
1339       else if (ltd.isLong())
1340         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1341       else
1342         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1343       on.setLeftType(lefttype);
1344       on.setType(lefttype);
1345       break;
1346
1347     case Operation.BIT_OR:
1348     case Operation.BIT_XOR:
1349     case Operation.BIT_AND:
1350       // 5.6.2 Binary Numeric Promotion
1351       //TODO unboxing of reference objects
1352       if (ltd.isDouble()||rtd.isDouble())
1353         throw new Error();
1354       else if (ltd.isFloat()||rtd.isFloat())
1355         throw new Error();
1356       else if (ltd.isLong()||rtd.isLong())
1357         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1358       // 090205 hack for boolean
1359       else if (ltd.isBoolean()||rtd.isBoolean())
1360         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1361       else
1362         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1363       righttype=lefttype;
1364
1365       on.setLeftType(lefttype);
1366       on.setRightType(righttype);
1367       on.setType(lefttype);
1368       break;
1369
1370     case Operation.ISAVAILABLE:
1371       if (!(ltd.isPtr())) {
1372         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1373       }
1374       lefttype=ltd;
1375       on.setLeftType(lefttype);
1376       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1377       break;
1378
1379     case Operation.EQUAL:
1380     case Operation.NOTEQUAL:
1381       // 5.6.2 Binary Numeric Promotion
1382       //TODO unboxing of reference objects
1383       if (ltd.isBoolean()||rtd.isBoolean()) {
1384         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1385           throw new Error();
1386         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1387       } else if (ltd.isPtr()||rtd.isPtr()) {
1388         if (!(ltd.isPtr()&&rtd.isPtr())) {
1389       if(!rtd.isEnum()) {
1390         throw new Error();
1391       }
1392     }
1393         righttype=rtd;
1394         lefttype=ltd;
1395       } else if (ltd.isDouble()||rtd.isDouble())
1396         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1397       else if (ltd.isFloat()||rtd.isFloat())
1398         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1399       else if (ltd.isLong()||rtd.isLong())
1400         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1401       else
1402         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1403
1404       on.setLeftType(lefttype);
1405       on.setRightType(righttype);
1406       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1407       break;
1408
1409
1410
1411     case Operation.LT:
1412     case Operation.GT:
1413     case Operation.LTE:
1414     case Operation.GTE:
1415       // 5.6.2 Binary Numeric Promotion
1416       //TODO unboxing of reference objects
1417       if (!ltd.isNumber()||!rtd.isNumber()) {
1418         if (!ltd.isNumber())
1419           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1420         if (!rtd.isNumber())
1421           throw new Error("Rightside is not number"+on.printNode(0));
1422       }
1423
1424       if (ltd.isDouble()||rtd.isDouble())
1425         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1426       else if (ltd.isFloat()||rtd.isFloat())
1427         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1428       else if (ltd.isLong()||rtd.isLong())
1429         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1430       else
1431         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1432       righttype=lefttype;
1433       on.setLeftType(lefttype);
1434       on.setRightType(righttype);
1435       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1436       break;
1437
1438     case Operation.ADD:
1439       if (ltd.isString()||rtd.isString()) {
1440         ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1441         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1442         NameDescriptor nd=new NameDescriptor("String");
1443         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1444         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1445           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1446           leftmin.setNumLine(on.getLeft().getNumLine());
1447           leftmin.addArgument(on.getLeft());
1448           on.left=leftmin;
1449           checkExpressionNode(md, nametable, on.getLeft(), null);
1450         }
1451
1452         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1453           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1454           rightmin.setNumLine(on.getRight().getNumLine());
1455           rightmin.addArgument(on.getRight());
1456           on.right=rightmin;
1457           checkExpressionNode(md, nametable, on.getRight(), null);
1458         }
1459
1460         on.setLeftType(stringtd);
1461         on.setRightType(stringtd);
1462         on.setType(stringtd);
1463         break;
1464       }
1465
1466     case Operation.SUB:
1467     case Operation.MULT:
1468     case Operation.DIV:
1469     case Operation.MOD:
1470       // 5.6.2 Binary Numeric Promotion
1471       //TODO unboxing of reference objects
1472       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1473         throw new Error("Error in "+on.printNode(0));
1474
1475       if (ltd.isDouble()||rtd.isDouble())
1476         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1477       else if (ltd.isFloat()||rtd.isFloat())
1478         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1479       else if (ltd.isLong()||rtd.isLong())
1480         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1481       else
1482         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1483       righttype=lefttype;
1484       on.setLeftType(lefttype);
1485       on.setRightType(righttype);
1486       on.setType(lefttype);
1487       break;
1488
1489     case Operation.LEFTSHIFT:
1490     case Operation.RIGHTSHIFT:
1491     case Operation.URIGHTSHIFT:
1492       if (!rtd.isIntegerType())
1493         throw new Error();
1494       //5.6.1 Unary Numeric Promotion
1495       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1496         righttype=new TypeDescriptor(TypeDescriptor.INT);
1497       else
1498         righttype=rtd;
1499
1500       on.setRightType(righttype);
1501       if (!ltd.isIntegerType())
1502         throw new Error();
1503
1504     case Operation.UNARYPLUS:
1505     case Operation.UNARYMINUS:
1506       /*        case Operation.POSTINC:
1507           case Operation.POSTDEC:
1508           case Operation.PREINC:
1509           case Operation.PREDEC:*/
1510       if (!ltd.isNumber())
1511         throw new Error();
1512       //5.6.1 Unary Numeric Promotion
1513       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1514         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1515       else
1516         lefttype=ltd;
1517       on.setLeftType(lefttype);
1518       on.setType(lefttype);
1519       break;
1520
1521     default:
1522       throw new Error(op.toString());
1523     }
1524
1525     if (td!=null)
1526       if (!typeutil.isSuperorType(td, on.getType())) {
1527         System.out.println(td);
1528         System.out.println(on.getType());
1529         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1530       }
1531   }
1532   
1533 }