Changes to MGC class library and fix a bug regarding nested inline class declaration
[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   HashMap<ClassDescriptor, Vector<VarDescriptor>> inlineClass2LiveVars;
14   boolean trialcheck = false;
15   Vector<ClassDescriptor> inlineClassWithTrialCheck;
16
17   public static final int NOCHECK=0;
18   public static final int REFERENCE=1;
19   public static final int INIT=2;
20
21   boolean checkAll;
22
23   public boolean hasLayout(ClassDescriptor cd) {
24     return completed.get(cd)!=null&&completed.get(cd)==INIT;
25   }
26
27   public SemanticCheck(State state, TypeUtil tu) {
28     this(state, tu, true);
29   }
30
31   public SemanticCheck(State state, TypeUtil tu, boolean checkAll) {
32     this.state=state;
33     this.typeutil=tu;
34     this.loopstack=new Stack();
35     this.toanalyze=new HashSet();
36     this.completed=new HashMap<ClassDescriptor, Integer>();
37     this.checkAll=checkAll;
38     this.inlineClass2LiveVars = new HashMap<ClassDescriptor, Vector<VarDescriptor>>();
39     this.inlineClassWithTrialCheck = new Vector<ClassDescriptor>();
40   }
41
42   public ClassDescriptor getClass(ClassDescriptor context, String classname) {
43     return getClass(context, classname, INIT);
44   }
45   public ClassDescriptor getClass(ClassDescriptor context, String classnameIn, int fullcheck) {
46     ClassDescriptor cd=typeutil.getClass(context, classnameIn, toanalyze);
47     checkClass(cd, fullcheck);
48     return cd;
49   }
50
51   public void checkClass(ClassDescriptor cd) {
52     checkClass(cd, INIT);
53   }
54
55   public void checkClass(ClassDescriptor cd, int fullcheck) {
56     if (!completed.containsKey(cd)||completed.get(cd)<fullcheck) {
57       int oldstatus=completed.containsKey(cd)?completed.get(cd):0;
58       completed.put(cd, fullcheck);
59
60       if (fullcheck>=REFERENCE&&oldstatus<INIT) {
61         //Set superclass link up
62         if (cd.getSuper()!=null) {
63           ClassDescriptor superdesc=getClass(cd, cd.getSuper(), fullcheck);
64           if (superdesc.isInnerClass()) {
65             cd.setAsInnerClass();
66           }
67           if (superdesc.isInterface()) {
68             if (cd.getInline()) {
69               cd.setSuper(null);
70               cd.getSuperInterface().add(superdesc.getSymbol());
71             } else {
72               throw new Error("Error! Class " + cd.getSymbol() + " extends interface " + cd.getSuper());
73             }
74           } else {
75             cd.setSuperDesc(superdesc);
76
77             // Link together Field, Method, and Flag tables so classes
78             // inherit these from their superclasses
79             if (oldstatus<REFERENCE) {
80               cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
81               cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
82               cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
83             }
84           }
85         }
86         // Link together Field, Method tables do classes inherit these from
87         // their ancestor interfaces
88         Vector<String> sifv = cd.getSuperInterface();
89         for(int i = 0; i < sifv.size(); i++) {
90           ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck);
91           if(!superif.isInterface()) {
92             throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol());
93           }
94           if (oldstatus<REFERENCE) {
95             cd.addSuperInterfaces(superif);
96             cd.getMethodTable().addParentIF(superif.getMethodTable());
97             cd.getFieldTable().addParentIF(superif.getFieldTable());
98           }
99         }
100       }
101       if (oldstatus<INIT&&fullcheck>=INIT) {
102         /* Check to see that fields are well typed */
103         for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) {
104           FieldDescriptor fd=(FieldDescriptor)field_it.next();
105           try {
106           checkField(cd,fd);
107           } catch (Error e) {
108             System.out.println("Class/Field in "+cd+":"+fd);
109             throw e;
110           }
111         }
112         for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) {
113           MethodDescriptor md=(MethodDescriptor)method_it.next();
114           try {
115           checkMethod(cd,md);
116           } catch (Error e) {
117             System.out.println("Class/Method in "+cd+":"+md);
118             throw e;
119           }
120         }
121       }
122     }
123   }
124   
125   public void semanticCheckClass(ClassDescriptor cd) {
126     // need to initialize typeutil object here...only place we can
127     // get class descriptors without first calling getclass
128     getClass(cd, cd.getSymbol());
129     if(cd.getInline()) {
130       
131       // for inline defined anonymous classes, we need to check its 
132       // surrounding class first to get its surrounding context
133       ClassDescriptor surroundingcd = cd.getSurroundingDesc();
134       if(toanalyze.contains(surroundingcd)) {
135           toanalyze.remove(surroundingcd);
136           semanticCheckClass(surroundingcd);
137       }
138     }
139
140     for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
141       MethodDescriptor md = (MethodDescriptor) method_it.next();
142       try {
143         checkMethodBody(cd, md);
144       } catch (Error e) {
145         System.out.println("Error in " + md);
146         throw e;
147       }
148     }
149   }
150
151   public void semanticCheck() {
152     SymbolTable classtable = state.getClassSymbolTable();
153     toanalyze.addAll(classtable.getValueSet());
154     toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
155
156     // Do methods next
157     while (!toanalyze.isEmpty()) {
158       Object obj = toanalyze.iterator().next();
159       if (obj instanceof TaskDescriptor) {
160         toanalyze.remove(obj);
161         TaskDescriptor td = (TaskDescriptor) obj;
162         try {
163           checkTask(td);
164         } catch (Error e) {
165           System.out.println("Error in " + td);
166           throw e;
167         }
168       } else {
169         ClassDescriptor cd = (ClassDescriptor) obj;
170         toanalyze.remove(cd);
171         semanticCheckClass(cd);
172       }
173     }
174   }
175
176   private void checkTypeDescriptor(ClassDescriptor cd, TypeDescriptor td) {
177     if (td.isPrimitive())
178       return;       /* Done */
179     else if (td.isClass()) {
180       String name=td.toString();
181       ClassDescriptor field_cd=checkAll?getClass(cd, name):getClass(cd, name, REFERENCE);
182
183       if (field_cd==null)
184         throw new Error("Undefined class "+name);
185       td.setClassDescriptor(field_cd);
186       return;
187     } else if (td.isTag())
188       return;
189     else
190       throw new Error();
191   }
192
193   public void checkField(ClassDescriptor cd, FieldDescriptor fd) {
194     checkTypeDescriptor(cd, fd.getType());
195   }
196
197   public void checkConstraintCheck(TaskDescriptor td, SymbolTable nametable, Vector ccs) {
198     if (ccs==null)
199       return;       /* No constraint checks to check */
200     for(int i=0; i<ccs.size(); i++) {
201       ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
202
203       for(int j=0; j<cc.numArgs(); j++) {
204         ExpressionNode en=cc.getArg(j);
205         checkExpressionNode(td,nametable,en,null);
206       }
207     }
208   }
209
210   public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
211     if (vfe==null)
212       return;       /* No flag effects to check */
213     for(int i=0; i<vfe.size(); i++) {
214       FlagEffects fe=(FlagEffects) vfe.get(i);
215       String varname=fe.getName();
216       //Make sure the variable is declared as a parameter to the task
217       VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
218       if (vd==null)
219         throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
220       fe.setVar(vd);
221
222       //Make sure it correspods to a class
223       TypeDescriptor type_d=vd.getType();
224       if (!type_d.isClass())
225         throw new Error("Cannot have non-object argument for flag_effect");
226
227       ClassDescriptor cd=type_d.getClassDesc();
228       for(int j=0; j<fe.numEffects(); j++) {
229         FlagEffect flag=fe.getEffect(j);
230         String name=flag.getName();
231         FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
232         //Make sure the flag is declared
233         if (flag_d==null)
234           throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
235         if (flag_d.getExternal())
236           throw new Error("Attempting to modify external flag: "+name);
237         flag.setFlag(flag_d);
238       }
239       for(int j=0; j<fe.numTagEffects(); j++) {
240         TagEffect tag=fe.getTagEffect(j);
241         String name=tag.getName();
242
243         Descriptor d=(Descriptor)nametable.get(name);
244         if (d==null)
245           throw new Error("Tag descriptor "+name+" undeclared");
246         else if (!(d instanceof TagVarDescriptor))
247           throw new Error(name+" is not a tag descriptor");
248         tag.setTag((TagVarDescriptor)d);
249       }
250     }
251   }
252
253   public void checkTask(TaskDescriptor td) {
254     for(int i=0; i<td.numParameters(); i++) {
255       /* Check that parameter is well typed */
256       TypeDescriptor param_type=td.getParamType(i);
257       checkTypeDescriptor(null, param_type);
258
259       /* Check the parameter's flag expression is well formed */
260       FlagExpressionNode fen=td.getFlag(td.getParameter(i));
261       if (!param_type.isClass())
262         throw new Error("Cannot have non-object argument to a task");
263       ClassDescriptor cd=param_type.getClassDesc();
264       if (fen!=null)
265         checkFlagExpressionNode(cd, fen);
266     }
267
268     checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
269     /* Check that the task code is valid */
270     BlockNode bn=state.getMethodBody(td);
271     checkBlockNode(td, td.getParameterTable(),bn);
272   }
273
274   public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
275     switch(fen.kind()) {
276     case Kind.FlagOpNode:
277     {
278       FlagOpNode fon=(FlagOpNode)fen;
279       checkFlagExpressionNode(cd, fon.getLeft());
280       if (fon.getRight()!=null)
281         checkFlagExpressionNode(cd, fon.getRight());
282       break;
283     }
284
285     case Kind.FlagNode:
286     {
287       FlagNode fn=(FlagNode)fen;
288       String name=fn.getFlagName();
289       FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
290       if (fd==null)
291         throw new Error("Undeclared flag: "+name);
292       fn.setFlag(fd);
293       break;
294     }
295
296     default:
297       throw new Error("Unrecognized FlagExpressionNode");
298     }
299   }
300
301   public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
302     /* Check for abstract methods */
303     if(md.isAbstract()) {
304       if(!cd.isAbstract() && !cd.isInterface()) {
305         throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
306       }
307     }
308
309     /* Check return type */
310     if (!md.isConstructor() && !md.isStaticBlock())
311       if (!md.getReturnType().isVoid()) {
312         checkTypeDescriptor(cd, md.getReturnType());
313       }
314     for(int i=0; i<md.numParameters(); i++) {
315       TypeDescriptor param_type=md.getParamType(i);
316       checkTypeDescriptor(cd, param_type);
317     }
318     /* Link the naming environments */
319     if (!md.isStatic())     /* Fields aren't accessible directly in a static method, so don't link in this table */
320       md.getParameterTable().setParent(cd.getFieldTable());
321     md.setClassDesc(cd);
322     if (!md.isStatic()) {
323       VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
324       md.setThis(thisvd);
325     }
326     if(md.isDefaultConstructor() && (cd.getSuperDesc() != null) && !cd.getInline()) {
327       // add the construction of it super class, can only be super()
328       // NOTE: inline class should be treated differently
329       NameDescriptor nd=new NameDescriptor("super");
330       MethodInvokeNode min=new MethodInvokeNode(nd);
331       BlockExpressionNode ben=new BlockExpressionNode(min);
332       BlockNode bn = state.getMethodBody(md);
333       bn.addFirstBlockStatement(ben);
334     }
335   }
336
337   public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
338     ClassDescriptor superdesc=cd.getSuperDesc();
339     // for inline classes, it has done this during trial check
340     if ((!cd.getInline() || !this.inlineClassWithTrialCheck.contains(cd)) && (superdesc!=null)) {
341       Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
342       for(Iterator methodit=possiblematches.iterator(); methodit.hasNext(); ) {
343         MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
344         if (md.matches(matchmd)) {
345           if (matchmd.getModifiers().isFinal()) {
346             throw new Error("Try to override final method in method:"+md+" declared in  "+cd);
347           }
348         }
349       }
350     }
351     BlockNode bn=state.getMethodBody(md);
352     checkBlockNode(md, md.getParameterTable(),bn);
353   }
354
355   public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
356     /* Link in the naming environment */
357     bn.getVarTable().setParent(nametable);
358     for(int i=0; i<bn.size(); i++) {
359       BlockStatementNode bsn=bn.get(i);
360       checkBlockStatementNode(md, bn.getVarTable(),bsn);
361     }
362   }
363
364   public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
365     switch(bsn.kind()) {
366     case Kind.BlockExpressionNode:
367       checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
368       return;
369
370     case Kind.DeclarationNode:
371       checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
372       return;
373
374     case Kind.TagDeclarationNode:
375       checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
376       return;
377
378     case Kind.IfStatementNode:
379       checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
380       return;
381
382     case Kind.SwitchStatementNode:
383       checkSwitchStatementNode(md, nametable, (SwitchStatementNode)bsn);
384       return;
385
386     case Kind.LoopNode:
387       checkLoopNode(md, nametable, (LoopNode)bsn);
388       return;
389
390     case Kind.ReturnNode:
391       checkReturnNode(md, nametable, (ReturnNode)bsn);
392       return;
393
394     case Kind.TaskExitNode:
395       checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
396       return;
397
398     case Kind.SubBlockNode:
399       checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
400       return;
401
402     case Kind.AtomicNode:
403       checkAtomicNode(md, nametable, (AtomicNode)bsn);
404       return;
405
406     case Kind.SynchronizedNode:
407       checkSynchronizedNode(md, nametable, (SynchronizedNode)bsn);
408       return;
409
410     case Kind.ContinueBreakNode:
411       checkContinueBreakNode(md, nametable, (ContinueBreakNode) bsn);
412       return;
413
414     case Kind.SESENode:
415     case Kind.GenReachNode:
416     case Kind.GenDefReachNode:
417       // do nothing, no semantic check for SESEs
418       return;
419     }
420
421     throw new Error();
422   }
423
424   void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
425     checkExpressionNode(md, nametable, ben.getExpression(), null);
426   }
427
428   void checkDeclarationNode(Descriptor md, SymbolTable nametable,  DeclarationNode dn) {
429     VarDescriptor vd=dn.getVarDescriptor();
430     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), vd.getType());
431     Descriptor d=nametable.get(vd.getSymbol());
432     if ((d==null)||
433         (d instanceof FieldDescriptor)) {
434       nametable.add(vd);
435     } else if((md instanceof MethodDescriptor) && (((MethodDescriptor)md).getClassDesc().getInline()) && this.inlineClassWithTrialCheck.contains(((MethodDescriptor)md).getClassDesc())) {
436       // for inline classes, the var has been checked during trial check and added into the nametable
437     } else
438       throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
439     if (dn.getExpression()!=null)
440       checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
441   }
442
443   void checkTagDeclarationNode(Descriptor md, SymbolTable nametable,  TagDeclarationNode dn) {
444     TagVarDescriptor vd=dn.getTagVarDescriptor();
445     Descriptor d=nametable.get(vd.getSymbol());
446     if ((d==null)||
447         (d instanceof FieldDescriptor)) {
448       nametable.add(vd);
449     } else if((md instanceof MethodDescriptor) && (((MethodDescriptor)md).getClassDesc().getInline()) && this.inlineClassWithTrialCheck.contains(((MethodDescriptor)md).getClassDesc())) {
450       // for inline classes, the var has been checked during trial check and added into the nametable
451     } else
452       throw new Error(vd.getSymbol()+" defined a second time");
453   }
454
455   void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
456     checkBlockNode(md, nametable, sbn.getBlockNode());
457   }
458
459   void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
460     checkBlockNode(md, nametable, sbn.getBlockNode());
461   }
462
463   void checkSynchronizedNode(Descriptor md, SymbolTable nametable, SynchronizedNode sbn) {
464     checkBlockNode(md, nametable, sbn.getBlockNode());
465     //todo this could be Object
466     checkExpressionNode(md, nametable, sbn.getExpr(), null);
467   }
468
469   void checkContinueBreakNode(Descriptor md, SymbolTable nametable, ContinueBreakNode cbn) {
470     if (loopstack.empty())
471       throw new Error("continue/break outside of loop");
472     Object o = loopstack.peek();
473     if(o instanceof LoopNode) {
474       LoopNode ln=(LoopNode)o;
475       cbn.setLoop(ln);
476     }
477   }
478
479   void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
480     if (d instanceof TaskDescriptor)
481       throw new Error("Illegal return appears in Task: "+d.getSymbol());
482     MethodDescriptor md=(MethodDescriptor)d;
483     if (rn.getReturnExpression()!=null)
484       if (md.getReturnType()==null)
485         throw new Error("Constructor can't return something.");
486       else if (md.getReturnType().isVoid())
487         throw new Error(md+" is void");
488       else
489         checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
490     else
491     if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
492       throw new Error("Need to return something for "+md);
493   }
494
495   void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
496     if (md instanceof MethodDescriptor)
497       throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
498     checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
499     checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
500   }
501
502   void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
503     checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
504     checkBlockNode(md, nametable, isn.getTrueBlock());
505     if (isn.getFalseBlock()!=null)
506       checkBlockNode(md, nametable, isn.getFalseBlock());
507   }
508
509   void checkSwitchStatementNode(Descriptor md, SymbolTable nametable, SwitchStatementNode ssn) {
510     checkExpressionNode(md, nametable, ssn.getCondition(), new TypeDescriptor(TypeDescriptor.INT));
511
512     BlockNode sbn = ssn.getSwitchBody();
513     boolean hasdefault = false;
514     for(int i = 0; i < sbn.size(); i++) {
515       boolean containdefault = checkSwitchBlockNode(md, nametable, (SwitchBlockNode)sbn.get(i));
516       if(hasdefault && containdefault) {
517         throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
518       }
519       hasdefault = containdefault;
520     }
521   }
522
523   boolean checkSwitchBlockNode(Descriptor md, SymbolTable nametable, SwitchBlockNode sbn) {
524     Vector<SwitchLabelNode> slnv = sbn.getSwitchConditions();
525     int defaultb = 0;
526     for(int i = 0; i < slnv.size(); i++) {
527       if(slnv.elementAt(i).isdefault) {
528         defaultb++;
529       } else {
530         checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
531       }
532     }
533     if(defaultb > 1) {
534       throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
535     } else {
536       loopstack.push(sbn);
537       checkBlockNode(md, nametable, sbn.getSwitchBlockStatement());
538       loopstack.pop();
539       return (defaultb > 0);
540     }
541   }
542
543   void checkConstantExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
544     switch(en.kind()) {
545     case Kind.FieldAccessNode:
546       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
547       return;
548
549     case Kind.LiteralNode:
550       checkLiteralNode(md,nametable,(LiteralNode)en,td);
551       return;
552
553     case Kind.NameNode:
554       checkNameNode(md,nametable,(NameNode)en,td);
555       return;
556
557     case Kind.OpNode:
558       checkOpNode(md, nametable, (OpNode)en, td);
559       return;
560     }
561     throw new Error();
562   }
563
564   void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
565     switch(en.kind()) {
566     case Kind.AssignmentNode:
567       checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
568       return;
569
570     case Kind.CastNode:
571       checkCastNode(md,nametable,(CastNode)en,td);
572       return;
573
574     case Kind.CreateObjectNode:
575       checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
576       return;
577
578     case Kind.FieldAccessNode:
579       checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
580       return;
581
582     case Kind.ArrayAccessNode:
583       checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
584       return;
585
586     case Kind.LiteralNode:
587       checkLiteralNode(md,nametable,(LiteralNode)en,td);
588       return;
589
590     case Kind.MethodInvokeNode:
591       checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
592       return;
593
594     case Kind.NameNode:
595       checkNameNode(md,nametable,(NameNode)en,td);
596       return;
597
598     case Kind.OpNode:
599       checkOpNode(md,nametable,(OpNode)en,td);
600       return;
601
602     case Kind.OffsetNode:
603       checkOffsetNode(md, nametable, (OffsetNode)en, td);
604       return;
605
606     case Kind.TertiaryNode:
607       checkTertiaryNode(md, nametable, (TertiaryNode)en, td);
608       return;
609
610     case Kind.InstanceOfNode:
611       checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
612       return;
613
614     case Kind.ArrayInitializerNode:
615       checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en, td);
616       return;
617
618     case Kind.ClassTypeNode:
619       checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
620       return;
621     }
622     throw new Error();
623   }
624
625   void checkClassTypeNode(Descriptor md, SymbolTable nametable, ClassTypeNode tn, TypeDescriptor td) {
626     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getType());
627   }
628
629   void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
630     /* Get type descriptor */
631     if (cn.getType()==null) {
632       NameDescriptor typenamed=cn.getTypeName().getName();
633       TypeDescriptor ntd=new TypeDescriptor(getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typenamed.toString()));
634       cn.setType(ntd);
635     }
636
637     /* Check the type descriptor */
638     TypeDescriptor cast_type=cn.getType();
639     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),cast_type);
640
641     /* Type check */
642     if (td!=null) {
643       if (!typeutil.isSuperorType(td,cast_type))
644         throw new Error("Cast node returns "+cast_type+", but need "+td);
645     }
646
647     ExpressionNode en=cn.getExpression();
648     checkExpressionNode(md, nametable, en, null);
649     TypeDescriptor etd=en.getType();
650     if (typeutil.isSuperorType(cast_type,etd))     /* Cast trivially succeeds */
651       return;
652
653     if (typeutil.isSuperorType(etd,cast_type))     /* Cast may succeed */
654       return;
655     if (typeutil.isCastable(etd, cast_type))
656       return;
657
658     //rough hack to handle interfaces...should clean up
659     if (etd.isClass()&&cast_type.isClass()) {
660       ClassDescriptor cdetd=etd.getClassDesc();
661       ClassDescriptor cdcast_type=cast_type.getClassDesc();
662
663       if (cdetd.isInterface()&&!cdcast_type.getModifier().isFinal())
664         return;
665       
666       if (cdcast_type.isInterface()&&!cdetd.getModifier().isFinal())
667         return;
668     }
669     /* Different branches */
670     /* TODO: change if add interfaces */
671     throw new Error("Cast will always fail\n"+cn.printNode(0));
672   }
673
674   //FieldDescriptor checkFieldAccessNodeForParentNode( Descriptor md, SymbolTable na )
675   void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
676     ExpressionNode left=fan.getExpression();
677     checkExpressionNode(md,nametable,left,null);
678     TypeDescriptor ltd=left.getType();
679     if (!ltd.isArray())
680       checkClass(ltd.getClassDesc(), INIT);
681     String fieldname=fan.getFieldName();
682
683     FieldDescriptor fd=null;
684     if (ltd.isArray()&&fieldname.equals("length"))
685       fd=FieldDescriptor.arrayLength;
686     else if(((left instanceof NameNode) && ((NameNode)left).isSuper())
687             ||((left instanceof FieldAccessNode) && ((FieldAccessNode)left).isSuper())){
688       fd = (FieldDescriptor) ltd.getClassDesc().getSuperDesc().getFieldTable().get(fieldname);
689     } else {
690       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
691     }
692     if(ltd.isClassNameRef()) {
693       // the field access is using a class name directly
694       if (fd==null) {
695        // check if it is to access a surrounding class in an inner class
696        if(fieldname.equals("this") || fieldname.equals("super")) {
697            ClassDescriptor icd = ((VarDescriptor)nametable.get("this")).getType().getClassDesc();
698            if(icd.isInnerClass()) {
699                NameNode nn = new NameNode(new NameDescriptor("this"));
700                nn.setVar((VarDescriptor)nametable.get("this"));
701                fan.setExpression(nn);
702                if(icd.getSurroundingDesc()==ltd.getClassDesc()) {
703                    // this is a surrounding class access inside an inner class
704                    fan.setExpression(nn);
705                    fan.setFieldName("this$0");
706                    fd = (FieldDescriptor)icd.getFieldTable().get("this$0");
707                } else if(icd==ltd.getClassDesc()) {
708                    // this is an inner class this operation 
709                    fd = new FieldDescriptor(new Modifiers(),new TypeDescriptor(icd),"this",null,false);
710                }
711                if(fieldname.equals("super")) {
712                    fan.setIsSuper();
713                }
714                fan.setField(fd);
715                return;
716            }
717        } 
718        ClassDescriptor surroundingCls=ltd.getClassDesc().getSurroundingDesc();
719        
720        while(surroundingCls!=null) {
721          fd=(FieldDescriptor) surroundingCls.getFieldTable().get(fieldname);
722          if (fd!=null) {
723            fan.left=new ClassTypeNode(new TypeDescriptor(surroundingCls));
724            break;
725          }
726          surroundingCls=surroundingCls.getSurroundingDesc();
727        }
728        
729        // check if it is to access an enum field
730        Iterator it_enum = ltd.getClassDesc().getEnum();
731        while(it_enum.hasNext()) {
732          ClassDescriptor ecd = (ClassDescriptor)it_enum.next();
733          if(ecd.getSymbol().equals(ltd.getClassDesc().getSymbol()+"$"+fieldname)) {
734            // this is an enum field access
735            if(!ecd.isStatic() && !ecd.getModifier().isStatic() && !ecd.getModifier().isPublic()) {
736              throw new Error(fieldname + " is not a public/static enum field in "+fan.printNode(0)+" in "+md);
737            }
738            TypeDescriptor tp = new TypeDescriptor(ecd);
739            tp.setClassNameRef();
740            fd=new FieldDescriptor(ecd.getModifier(), tp, ltd.getClassDesc().getSymbol()+"$"+fieldname, null, false);;
741            fd.setIsEnumClass();
742            break;
743          }
744        }
745       }
746
747       if(ltd.getClassDesc().isEnum()) {
748         int value = ltd.getClassDesc().getEnumConstant(fieldname);
749         if(-1 == value) {
750           // check if this field is an enum constant
751           throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
752         }
753         fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
754         fd.setAsEnum();
755         fd.setEnumValue(value);
756       } else if(fd == null) {
757         throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
758       } else if(fd.isStatic()) {
759         // check if this field is a static field
760         if(fd.getExpressionNode() != null) {
761           checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
762         }
763       } else {
764         throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
765       }
766     }
767
768     if (fd==null){
769         if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
770             ClassDescriptor cd = ((MethodDescriptor)md).getClassDesc();
771             FieldAccessNode theFieldNode =      fieldAccessExpression( cd, fieldname, fan.getNumLine() );
772             if( null != theFieldNode ) {
773                 //fan = theFieldNode;
774                 checkFieldAccessNode( md, nametable, theFieldNode, td );
775                 fan.setField( theFieldNode.getField() );
776                 fan.setExpression( theFieldNode.getExpression() );
777                 //TypeDescriptor td1 = fan.getType();
778                 //td1.toString();
779                 return;         
780             }   
781         }
782         throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
783     }
784
785     if (fd.getType().iswrapper()) {
786       FieldAccessNode fan2=new FieldAccessNode(left, fieldname);
787       fan2.setNumLine(left.getNumLine());
788       fan2.setField(fd);
789       fan.left=fan2;
790       fan.fieldname="value";
791
792       ExpressionNode leftwr=fan.getExpression();
793       TypeDescriptor ltdwr=leftwr.getType();
794       String fieldnamewr=fan.getFieldName();
795       FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
796       fan.setField(fdwr);
797       if (fdwr==null)
798         throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
799     } else {
800       fan.setField(fd);
801     }
802     if (td!=null) {
803       if (!typeutil.isSuperorType(td,fan.getType()))
804         throw new Error("Field node returns "+fan.getType()+", but need "+td);
805     }
806   }
807
808   void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
809     ExpressionNode left=aan.getExpression();
810     checkExpressionNode(md,nametable,left,null);
811
812     checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
813     TypeDescriptor ltd=left.getType();
814     if (ltd.dereference().iswrapper()) {
815       aan.wrappertype=((FieldDescriptor)ltd.dereference().getClassDesc().getFieldTable().get("value")).getType();
816     }
817
818     if (td!=null)
819       if (!typeutil.isSuperorType(td,aan.getType()))
820         throw new Error("Field node returns "+aan.getType()+", but need "+td);
821   }
822
823   void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
824     /* Resolve the type */
825     Object o=ln.getValue();
826     if (ln.getTypeString().equals("null")) {
827       ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
828     } else if (o instanceof Integer) {
829       ln.setType(new TypeDescriptor(TypeDescriptor.INT));
830     } else if (o instanceof Long) {
831       ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
832     } else if (o instanceof Float) {
833       ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
834     } else if (o instanceof Boolean) {
835       ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
836     } else if (o instanceof Double) {
837       ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
838     } else if (o instanceof Character) {
839       ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
840     } else if (o instanceof String) {
841       ln.setType(new TypeDescriptor(getClass(null, TypeUtil.StringClass)));
842     }
843
844     if (td!=null)
845       if (!typeutil.isSuperorType(td,ln.getType())) {
846         Long l = ln.evaluate();
847         if((ln.getType().isByte() || ln.getType().isShort()
848             || ln.getType().isChar() || ln.getType().isInt())
849            && (l != null)
850            && (td.isByte() || td.isShort() || td.isChar()
851                || td.isInt() || td.isLong())) {
852           long lnvalue = l.longValue();
853           if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
854              || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
855              || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
856              || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
857              || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
858             throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
859           }
860         } else {
861           throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
862         }
863       }
864   }
865
866   FieldDescriptor recurseSurroundingClasses( ClassDescriptor icd, String varname ) {
867         if( null == icd || false == icd.isInnerClass() )
868             return null;
869       
870         ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
871         if( null == surroundingDesc )
872             return null;
873       
874         SymbolTable fieldTable = surroundingDesc.getFieldTable();
875         FieldDescriptor fd = ( FieldDescriptor ) fieldTable.get( varname );
876         if( null != fd )
877             return fd;
878         return recurseSurroundingClasses( surroundingDesc, varname );
879   }
880   
881   FieldAccessNode fieldAccessExpression( ClassDescriptor icd, String varname, int linenum ) {
882         FieldDescriptor fd = recurseSurroundingClasses( icd, varname );
883         if( null == fd )
884                 return null;
885
886         ClassDescriptor cd = fd.getClassDescriptor();
887         if(icd.getInStaticContext()) {
888           // if the inner class is in a static context, it does not have the this$0 
889           // pointer to its surrounding class. Instead, it might have reference to 
890           // its static surrounding method/block is there is any and it can refer 
891           // to static fields in its surrounding class too.
892           if(fd.isStatic()) {
893             NameNode nn = new NameNode(new NameDescriptor(cd.getSymbol()));
894             nn.setNumLine(linenum);
895             FieldAccessNode theFieldNode = new FieldAccessNode(nn,varname);
896             theFieldNode.setNumLine(linenum);
897             return theFieldNode;
898           } else {
899             throw new Error("Error: access non-static field " + cd.getSymbol() + "." + fd.getSymbol() + " in an inner class " + icd.getSymbol() + " that is declared in a static context");
900           }
901         }
902         int depth = 1;
903         int startingDepth = icd.getInnerDepth();
904
905         if( true == cd.isInnerClass() ) 
906                 depth = cd.getInnerDepth();
907
908         String composed = "this";
909         NameDescriptor runningDesc = new NameDescriptor( "this" );;
910         
911         for ( int index = startingDepth; index > depth; --index ) {
912                 composed = "this$" + String.valueOf( index - 1  );      
913                 runningDesc = new NameDescriptor( runningDesc, composed );
914         }
915         if( false == cd.isInnerClass() )
916                 runningDesc = new NameDescriptor( runningDesc, "this$" + String.valueOf(0) ); //all the way up.
917         NameDescriptor idDesc = new NameDescriptor( runningDesc, varname );
918         
919         
920         FieldAccessNode theFieldNode = ( FieldAccessNode )translateNameDescriptorintoExpression( idDesc, linenum );
921         return theFieldNode;
922   }
923   
924   Descriptor searchSurroundingNameTable(ClassDescriptor cd, String varname) {
925     Descriptor d = null;
926     if(cd.getInline()&&this.trialcheck) {
927       d = cd.getSurroundingNameTable().get(varname);
928     } else {
929       return d;
930     }
931     if(null == d) {
932       d = searchSurroundingNameTable(cd.getSurroundingDesc(), varname);
933     }
934     if(null != d) {
935       if(!this.inlineClass2LiveVars.containsKey(cd)) {
936         this.inlineClass2LiveVars.put(cd, new Vector<VarDescriptor>());
937       }
938       Vector<VarDescriptor> vars = this.inlineClass2LiveVars.get(cd);
939       if(!vars.contains((VarDescriptor)d)) {
940         vars.add((VarDescriptor)d);
941       }
942     }
943     return d;
944   }
945
946   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
947     NameDescriptor nd=nn.getName();
948     if (nd.getBase()!=null) {
949       /* Big hack */
950       /* Rewrite NameNode */
951       ExpressionNode en=translateNameDescriptorintoExpression(nd,nn.getNumLine());
952       nn.setExpression(en);
953       checkExpressionNode(md,nametable,en,td);
954     } else {
955       String varname=nd.toString();
956       if(varname.equals("this") || varname.equals("super")) {
957         // "this"
958         nn.setVar((VarDescriptor)nametable.get("this"));
959         if(varname.equals("super")) {
960             nn.setIsSuper();
961         }
962         return;
963       }
964       Descriptor d=(Descriptor)nametable.get(varname);
965       if (d==null) {
966         ClassDescriptor cd = null;
967         //check the inner class case first.
968         if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
969                 cd = ((MethodDescriptor)md).getClassDesc();
970                 FieldAccessNode theFieldNode =  fieldAccessExpression( cd, varname, nn.getNumLine() );
971                 if( null != theFieldNode ) {
972                         nn.setExpression(( ExpressionNode )theFieldNode);
973                         checkExpressionNode(md,nametable,( ExpressionNode )theFieldNode,td);
974                         return;         
975                 } else {
976                     // for the trial check of an inline class, cache the unknown var
977                     d = searchSurroundingNameTable(cd, varname);
978                 }
979         }
980         if(null==d) {
981         if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
982           // this is a static block, all the accessed fields should be static field
983           cd = ((MethodDescriptor)md).getClassDesc();
984           SymbolTable fieldtbl = cd.getFieldTable();
985           FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
986           if((fd == null) || (!fd.isStatic())) {
987             // no such field in the class, check if this is a class
988             if(varname.equals("this")) {
989               throw new Error("Error: access this obj in a static block");
990             }
991             cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
992             if(cd != null) {
993               // this is a class name
994               nn.setClassDesc(cd);
995               return;
996             } else {
997               throw new Error("Name "+varname+" should not be used in static block: "+md);
998             }
999           } else {
1000             // this is a static field
1001             nn.setField(fd);
1002             nn.setClassDesc(cd);
1003             return;
1004           }
1005         } else {
1006           // check if the var is a static field of the class
1007           if(md instanceof MethodDescriptor) {
1008             cd = ((MethodDescriptor)md).getClassDesc();
1009             FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
1010             if((fd != null) && (fd.isStatic())) {
1011               nn.setField(fd);
1012               nn.setClassDesc(cd);
1013               if (td!=null)
1014                 if (!typeutil.isSuperorType(td,nn.getType()))
1015                   throw new Error("Field node returns "+nn.getType()+", but need "+td);
1016               return;
1017             } else if(fd != null) {
1018               throw new Error("Name "+varname+" should not be used in " + md);
1019             }
1020           }
1021           cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
1022           if(cd != null) {
1023             // this is a class name
1024             nn.setClassDesc(cd);
1025             return;
1026           } else {
1027             throw new Error("Name "+varname+" undefined in: "+md);          
1028           }
1029         }
1030         }
1031       }
1032
1033       if (d instanceof VarDescriptor) {
1034         nn.setVar(d);
1035       } else if (d instanceof FieldDescriptor) {
1036         FieldDescriptor fd=(FieldDescriptor)d;
1037         if (fd.getType().iswrapper()) {
1038           String id=nd.getIdentifier();
1039           NameDescriptor base=nd.getBase();
1040           NameNode n=new NameNode(nn.getName());
1041           n.setNumLine(nn.getNumLine());
1042           n.setField(fd);
1043           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
1044           FieldAccessNode fan=new FieldAccessNode(n,"value");
1045           fan.setNumLine(n.getNumLine());
1046           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
1047           fan.setField(fdval);
1048           nn.setExpression(fan);
1049         } else {
1050           nn.setField(fd);
1051           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
1052         }
1053       } else if (d instanceof TagVarDescriptor) {
1054         nn.setVar(d);
1055       } else throw new Error("Wrong type of descriptor");
1056       if (td!=null)
1057         if (!typeutil.isSuperorType(td,nn.getType()))
1058           throw new Error("Field node returns "+nn.getType()+", but need "+td);
1059     }
1060   }
1061
1062   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
1063     TypeDescriptor ltd=ofn.td;
1064     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),ltd);
1065
1066     String fieldname = ofn.fieldname;
1067     FieldDescriptor fd=null;
1068     if (ltd.isArray()&&fieldname.equals("length")) {
1069       fd=FieldDescriptor.arrayLength;
1070     } else {
1071       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
1072     }
1073
1074     ofn.setField(fd);
1075     checkField(ltd.getClassDesc(), fd);
1076
1077     if (fd==null)
1078       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
1079
1080     if (td!=null) {
1081       if (!typeutil.isSuperorType(td, ofn.getType())) {
1082         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
1083       }
1084     }
1085   }
1086
1087
1088   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
1089     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1090     checkExpressionNode(md, nametable, tn.getTrueExpr(), td);
1091     checkExpressionNode(md, nametable, tn.getFalseExpr(), td);
1092   }
1093
1094   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
1095     if (td!=null&&!td.isBoolean())
1096       throw new Error("Expecting type "+td+"for instanceof expression");
1097
1098     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getExprType());
1099     checkExpressionNode(md, nametable, tn.getExpr(), null);
1100   }
1101
1102   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
1103     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
1104       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td.dereference());
1105     }
1106     if (td==null)
1107         throw new Error();
1108     
1109     ain.setType(td);
1110   }
1111
1112   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
1113     // Need to first check the lside to decide the correct type of the rside
1114     // TODO: Need check on validity of operation here
1115     if (!((an.getDest() instanceof FieldAccessNode)||
1116           (an.getDest() instanceof ArrayAccessNode)||
1117           (an.getDest() instanceof NameNode)))
1118       throw new Error("Bad lside in "+an.printNode(0));
1119     checkExpressionNode(md, nametable, an.getDest(), null);
1120     boolean postinc=true;
1121     if (an.getOperation().getBaseOp()==null||
1122         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
1123          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
1124       postinc=false;
1125     if (!postinc) {
1126       if(an.getSrc() instanceof ArrayInitializerNode) {
1127         checkExpressionNode(md, nametable, an.getSrc(), an.getDest().getType());
1128       } else {
1129         checkExpressionNode(md, nametable, an.getSrc(),td);
1130       }
1131     }
1132
1133     /* We want parameter variables to tasks to be immutable */
1134     if (md instanceof TaskDescriptor) {
1135       if (an.getDest() instanceof NameNode) {
1136         NameNode nn=(NameNode)an.getDest();
1137         if (nn.getVar()!=null) {
1138           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
1139             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
1140         }
1141       }
1142     }
1143
1144     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
1145       //String add
1146       ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1147       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1148       NameDescriptor nd=new NameDescriptor("String");
1149       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1150
1151       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
1152         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1153         rightmin.setNumLine(an.getSrc().getNumLine());
1154         rightmin.addArgument(an.getSrc());
1155         an.right=rightmin;
1156         checkExpressionNode(md, nametable, an.getSrc(), null);
1157       }
1158     }
1159
1160     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
1161       TypeDescriptor dt = an.getDest().getType();
1162       TypeDescriptor st = an.getSrc().getType();
1163       if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
1164         if(dt.getArrayCount() != st.getArrayCount()) {
1165           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1166         } else {
1167           do {
1168             dt = dt.dereference();
1169             st = st.dereference();
1170           } while(dt.isArray());
1171           if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1172              && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1173             return;
1174           } else {
1175             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1176           }
1177         }
1178       } else {
1179         Long l = an.getSrc().evaluate();
1180         if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1181            && (l != null)
1182            && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1183           long lnvalue = l.longValue();
1184           if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
1185              || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
1186              || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
1187              || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
1188              || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
1189             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1190           }
1191         } else {
1192           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1193         }
1194       }
1195     }
1196   }
1197
1198   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
1199     loopstack.push(ln);
1200     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
1201       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1202       checkBlockNode(md, nametable, ln.getBody());
1203     } else {
1204       //For loop case
1205       /* Link in the initializer naming environment */
1206       BlockNode bn=ln.getInitializer();
1207       bn.getVarTable().setParent(nametable);
1208       for(int i=0; i<bn.size(); i++) {
1209         BlockStatementNode bsn=bn.get(i);
1210         checkBlockStatementNode(md, bn.getVarTable(),bsn);
1211       }
1212       //check the condition
1213       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1214       checkBlockNode(md, bn.getVarTable(), ln.getBody());
1215       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
1216     }
1217     loopstack.pop();
1218   }
1219
1220   void InnerClassAddParamToCtor( MethodDescriptor md, ClassDescriptor cd, SymbolTable nametable, 
1221                                  CreateObjectNode con, TypeDescriptor td ) {
1222     if(this.inlineClassWithTrialCheck.contains(cd)) {
1223       // this class has done this with its first trial check
1224       return;
1225     }
1226         TypeDescriptor cdsType = new TypeDescriptor( cd );
1227         ExpressionNode conExp = con.getSurroundingClassExpression();
1228         //System.out.println( "The surrounding class expression si " + con );
1229         if( null == conExp ) {
1230                 if( md.isStatic()) {
1231                         throw new Error("trying to instantiate inner class: " +  con.getType() + " in a static scope" );
1232                 }
1233                 VarDescriptor thisVD = md.getThis();
1234                 if( null == thisVD ) {
1235                         throw new Error( "this pointer is not defined in a non static scope" ); 
1236                 }                       
1237                 if( cdsType.equals( thisVD.getType() ) == false ) {
1238                         throw new Error( "the type of this pointer is different than the type expected for inner class constructor. Initializing the inner class: "                             +  con.getType() + " in the wrong scope" );             
1239                 }       
1240                 //make this into an expression node.
1241                 NameNode nThis=new NameNode( new NameDescriptor( "this" ) );
1242                 con.addArgument( nThis );
1243         }
1244         else {
1245                 //REVISIT : here i am storing the expression as an expressionNode which does not implement type, there is no way for me to semantic check this argument.
1246                 con.addArgument( conExp );
1247         }
1248         //System.out.println( " the modified createObjectNode is " + con.printNode( 0 ) + "\n" );
1249 }
1250   
1251   void trialSemanticCheck(ClassDescriptor cd) {
1252     if(this.inlineClassWithTrialCheck.contains(cd)) {
1253       // this inline class has done trial check
1254       return;
1255     }
1256     if(!cd.getInline()) {
1257       throw new Error("Error! Try to do a trial check on a non-inline class " + cd.getSymbol());
1258     }
1259     boolean settrial = false;
1260     if(!trialcheck) {
1261       trialcheck = true;
1262       settrial = true;
1263     }
1264       
1265     for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
1266       MethodDescriptor md = (MethodDescriptor) method_it.next();
1267       try {
1268         checkMethodBody(cd, md);
1269       } catch (Error e) {
1270         System.out.println("Error in " + md);
1271         throw e;
1272       }
1273     }
1274     this.inlineClassWithTrialCheck.add(cd);
1275     if(settrial) {
1276       trialcheck = false;
1277     }
1278   }
1279   
1280   // add all the live vars that are referred by the inline class in the surrounding 
1281   // context of the inline class into the inline class' field table and pass them to 
1282   // the inline class' constructors
1283   // TODO: BUGFIX. These local vars should be final. But currently we've lost those 
1284   // information, so we cannot have that checked.
1285   void InlineClassAddParamToCtor(MethodDescriptor md, ClassDescriptor cd , SymbolTable nametable, CreateObjectNode con, TypeDescriptor td, TypeDescriptor[] tdarray ) {
1286     if(this.inlineClassWithTrialCheck.contains(cd)) {
1287       // this class has done this with its first trial check
1288       return;
1289     }
1290     // for an inline class, need to first add the original parameters of the CreatObjectNode
1291     // into its anonymous constructor and insert a super(...) into the anonymous constructor
1292     // if its super class is not null
1293     MethodDescriptor cd_constructor = null;
1294     for(Iterator it_methods = cd.getMethods(); it_methods.hasNext();) {
1295       MethodDescriptor imd = (MethodDescriptor)it_methods.next();
1296       if(imd.isConstructor()) {
1297           cd_constructor = imd; // an inline class should only have one anonymous constructor
1298       }
1299     }
1300     MethodInvokeNode min = null;
1301     if(cd.getSuper()!= null) {
1302       // add a super(...) into the anonymous constructor
1303       NameDescriptor nd=new NameDescriptor("super");
1304       min=new MethodInvokeNode(nd);
1305       BlockExpressionNode ben=new BlockExpressionNode(min);
1306       BlockNode bn = state.getMethodBody(cd_constructor);
1307       bn.addFirstBlockStatement(ben);
1308       if(cd.getSuperDesc().isInnerClass()&&!cd.getSuperDesc().isStatic()&&!cd.getSuperDesc().getInStaticContext()) {
1309         // for a super class that is also an inner class with surrounding reference, add the surrounding 
1310         // instance of the child instance as the parent instance's surrounding instance
1311         min.addArgument(new NameNode(new NameDescriptor("surrounding$0")));
1312       }
1313     }
1314     for(int i = 0 ; i < tdarray.length; i++) {
1315       assert(null!=min);
1316       TypeDescriptor itd = tdarray[i];
1317       cd_constructor.addParameter(itd, itd.getSymbol()+"_from_con_node_"+i);
1318       if(null != min) {
1319         min.addArgument(new NameNode(new NameDescriptor(itd.getSymbol()+"_from_con_node_"+i)));
1320       }
1321     }
1322     
1323     // Next add the live vars into the inline class' fields
1324     cd.setSurroundingNameTable(nametable);
1325     // do a round of semantic check trial to get all the live vars required by the inline class
1326     trialSemanticCheck(cd);
1327     Vector<VarDescriptor> vars = this.inlineClass2LiveVars.remove(cd);
1328     if(vars == null) {
1329       return;
1330     }
1331     for(int i = 0; i < vars.size(); i++) {
1332       Descriptor d = vars.elementAt(i);
1333       if(d instanceof VarDescriptor && !d.getSymbol().equals("this")) {
1334         con.addArgument(new NameNode(new NameDescriptor(d.getSymbol())));
1335         cd.addField(new FieldDescriptor(new Modifiers(Modifiers.PUBLIC), ((VarDescriptor)d).getType(), d.getSymbol(), null, false));
1336         cd_constructor.addParameter(((VarDescriptor)d).getType(), d.getSymbol()+"_p");
1337         // add the initialize statement into this constructor
1338         BlockNode obn = state.getMethodBody(cd_constructor);
1339         NameNode nn=new NameNode(new NameDescriptor(d.getSymbol()));
1340         NameNode fn = new NameNode (new NameDescriptor(d.getSymbol()+"_p"));
1341         AssignmentNode an=new AssignmentNode(nn,fn,new AssignOperation(1));
1342         obn.addFirstBlockStatement(new BlockExpressionNode(an));
1343         state.addTreeCode(cd_constructor, obn);
1344       }
1345     }
1346   }
1347   
1348   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con,
1349                              TypeDescriptor td) {
1350     TypeDescriptor[] tdarray = new TypeDescriptor[con.numArgs()];
1351     for (int i = 0; i < con.numArgs(); i++) {
1352       ExpressionNode en = con.getArg(i);
1353       checkExpressionNode(md, nametable, en, null);
1354       tdarray[i] = en.getType();
1355     }
1356
1357     TypeDescriptor typetolookin = con.getType();
1358     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typetolookin);
1359
1360     if (td != null && !typeutil.isSuperorType(td, typetolookin))
1361       throw new Error(typetolookin + " isn't a " + td);
1362
1363     /* Check Array Initializers */
1364     if ((con.getArrayInitializer() != null)) {
1365       checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), typetolookin);
1366     }
1367
1368     /* Check flag effects */
1369     if (con.getFlagEffects() != null) {
1370       FlagEffects fe = con.getFlagEffects();
1371       ClassDescriptor cd = typetolookin.getClassDesc();
1372
1373       for (int j = 0; j < fe.numEffects(); j++) {
1374         FlagEffect flag = fe.getEffect(j);
1375         String name = flag.getName();
1376         FlagDescriptor flag_d = (FlagDescriptor) cd.getFlagTable().get(name);
1377         // Make sure the flag is declared
1378         if (flag_d == null)
1379           throw new Error("Flag descriptor " + name + " undefined in class: " + cd.getSymbol());
1380         if (flag_d.getExternal())
1381           throw new Error("Attempting to modify external flag: " + name);
1382         flag.setFlag(flag_d);
1383       }
1384       for (int j = 0; j < fe.numTagEffects(); j++) {
1385         TagEffect tag = fe.getTagEffect(j);
1386         String name = tag.getName();
1387
1388         Descriptor d = (Descriptor) nametable.get(name);
1389         if (d == null)
1390           throw new Error("Tag descriptor " + name + " undeclared");
1391         else if (!(d instanceof TagVarDescriptor))
1392           throw new Error(name + " is not a tag descriptor");
1393         tag.setTag((TagVarDescriptor) d);
1394       }
1395     }
1396
1397     if ((!typetolookin.isClass()) && (!typetolookin.isArray()))
1398       throw new Error("Can't allocate primitive type:" + con.printNode(0));
1399
1400     if (!typetolookin.isArray()) {
1401       // Array's don't need constructor calls
1402       ClassDescriptor classtolookin = typetolookin.getClassDesc();
1403       checkClass(classtolookin, INIT);
1404       if( classtolookin.isInnerClass() ) {
1405         // for inner class that is declared in a static context, it does not have 
1406         // lexically enclosing instances
1407         if(!classtolookin.getInStaticContext()) {
1408             InnerClassAddParamToCtor( (MethodDescriptor)md, ((MethodDescriptor)md).getClassDesc() , nametable, con, td );
1409         }
1410         if(classtolookin.getInline()) {
1411           // for an inline anonymous inner class, the live local variables that are 
1412           // referred to by the inline class are passed as parameters of the constructors
1413           // of the inline class
1414           InlineClassAddParamToCtor( (MethodDescriptor)md, classtolookin, nametable, con, td, tdarray );
1415         }
1416         tdarray = new TypeDescriptor[con.numArgs()];
1417         for (int i = 0; i < con.numArgs(); i++) {
1418           ExpressionNode en = con.getArg(i);
1419           checkExpressionNode(md, nametable, en, null);
1420           tdarray[i] = en.getType();
1421         }
1422       }
1423       Set methoddescriptorset = classtolookin.getMethodTable().getSet(classtolookin.getSymbol());
1424       MethodDescriptor bestmd = null;
1425 NextMethod: for (Iterator methodit = methoddescriptorset.iterator(); methodit.hasNext(); ) {
1426         MethodDescriptor currmd = (MethodDescriptor) methodit.next();
1427         /* Need correct number of parameters */
1428         if (con.numArgs() != currmd.numParameters())
1429           continue;
1430         for (int i = 0; i < con.numArgs(); i++) {
1431           if (!typeutil.isSuperorType(currmd.getParamType(i), tdarray[i]))
1432             continue NextMethod;
1433         }
1434         /* Local allocations can't call global allocator */
1435         if (!con.isGlobal() && currmd.isGlobal())
1436           continue;
1437
1438         /* Method okay so far */
1439         if (bestmd == null)
1440           bestmd = currmd;
1441         else {
1442           if (typeutil.isMoreSpecific(currmd, bestmd, true)) {
1443             bestmd = currmd;
1444           } else if (con.isGlobal() && match(currmd, bestmd)) {
1445             if (currmd.isGlobal() && !bestmd.isGlobal())
1446               bestmd = currmd;
1447             else if (currmd.isGlobal() && bestmd.isGlobal())
1448               throw new Error();
1449           } else if (!typeutil.isMoreSpecific(bestmd, currmd, true)) {
1450             throw new Error("No method is most specific:" + bestmd + " and " + currmd);
1451           }
1452
1453           /* Is this more specific than bestmd */
1454         }
1455       }
1456       if (bestmd == null) {
1457         throw new Error("No method found for " + con.printNode(0) + " in " + md);
1458       }
1459       con.setConstructor(bestmd);
1460     }
1461   }
1462
1463
1464   /** Check to see if md1 is the same specificity as md2.*/
1465
1466   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1467     /* Checks if md1 is more specific than md2 */
1468     if (md1.numParameters()!=md2.numParameters())
1469       throw new Error();
1470     for(int i=0; i<md1.numParameters(); i++) {
1471       if (!md2.getParamType(i).equals(md1.getParamType(i)))
1472         return false;
1473     }
1474     if (!md2.getReturnType().equals(md1.getReturnType()))
1475       return false;
1476
1477     if (!md2.getClassDesc().equals(md1.getClassDesc()))
1478       return false;
1479
1480     return true;
1481   }
1482
1483
1484
1485   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd, int numLine) {
1486     String id=nd.getIdentifier();
1487     NameDescriptor base=nd.getBase();
1488     if (base==null) {
1489       NameNode nn=new NameNode(nd);
1490       nn.setNumLine(numLine);
1491       return nn;
1492     } else {
1493       FieldAccessNode fan=new FieldAccessNode(translateNameDescriptorintoExpression(base,numLine),id);
1494       fan.setNumLine(numLine);
1495       return fan;
1496     }
1497   }
1498
1499   MethodDescriptor recurseSurroundingClassesM( ClassDescriptor icd, String varname ) {
1500       if( null == icd || false == icd.isInnerClass() )
1501             return null;
1502     
1503       ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
1504       if( null == surroundingDesc )
1505             return null;
1506     
1507       SymbolTable methodTable = surroundingDesc.getMethodTable();
1508       MethodDescriptor md = ( MethodDescriptor ) methodTable.get( varname );
1509       if( null != md )
1510             return md;
1511       return recurseSurroundingClassesM( surroundingDesc, varname );
1512   }
1513
1514   ExpressionNode methodInvocationExpression( ClassDescriptor icd, MethodDescriptor md, int linenum ) {
1515         ClassDescriptor cd = md.getClassDesc();
1516         int depth = 1;
1517         int startingDepth = icd.getInnerDepth();
1518
1519         if( true == cd.isInnerClass() ) 
1520                 depth = cd.getInnerDepth();
1521
1522         String composed = "this";
1523         NameDescriptor runningDesc = new NameDescriptor( "this" );;
1524         
1525         for ( int index = startingDepth; index > depth; --index ) {
1526                 composed = "this$" + String.valueOf( index - 1  );      
1527                 runningDesc = new NameDescriptor( runningDesc, composed );
1528         }
1529         if( false == cd.isInnerClass() )
1530                 runningDesc = new NameDescriptor( runningDesc, "this$" + String.valueOf(0) ); //all the way up.
1531
1532         return new NameNode(runningDesc);
1533 }
1534
1535   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1536     /*Typecheck subexpressions
1537        and get types for expressions*/
1538
1539     boolean isstatic = false;
1540     if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStatic()) {
1541       isstatic = true;
1542     }
1543     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1544     for(int i=0; i<min.numArgs(); i++) {
1545       ExpressionNode en=min.getArg(i);
1546       checkExpressionNode(md,nametable,en,null);
1547       tdarray[i]=en.getType();
1548
1549       if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1550         tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1551       }
1552     }
1553     TypeDescriptor typetolookin=null;
1554     if (min.getExpression()!=null) {
1555       checkExpressionNode(md,nametable,min.getExpression(),null);
1556       typetolookin=min.getExpression().getType();
1557     } else if (min.getBaseName()!=null) {
1558       String rootname=min.getBaseName().getRoot();
1559       if (rootname.equals("super")) {
1560         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1561         typetolookin=new TypeDescriptor(supercd);
1562         min.setSuper();
1563       } else if (rootname.equals("this")) {
1564         if(isstatic) {
1565           throw new Error("use this object in static method md = "+ md.toString());
1566         }
1567         ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
1568         typetolookin=new TypeDescriptor(cd);
1569       } else if (nametable.get(rootname)!=null) {
1570         //we have an expression
1571         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
1572         checkExpressionNode(md, nametable, min.getExpression(), null);
1573         typetolookin=min.getExpression().getType();
1574       } else {
1575         if(!min.getBaseName().getSymbol().equals("System.out")||state.JNI) {
1576           ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
1577           checkExpressionNode(md, nametable, nn, null);
1578           typetolookin = nn.getType();
1579           if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
1580                && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
1581             // this is not a pure class name, need to add to
1582             min.setExpression(nn);
1583           }
1584         } else {
1585           //we have a type
1586           ClassDescriptor cd = getClass(null, "System");
1587
1588           if (cd==null)
1589             throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
1590           typetolookin=new TypeDescriptor(cd);
1591         }
1592       }
1593     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1594       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1595       min.methodid=supercd.getSymbol();
1596       typetolookin=new TypeDescriptor(supercd);
1597       if(supercd.isInnerClass()&&!supercd.isStatic()&&!supercd.getInStaticContext()) {
1598         // for a super class that is also an inner class with surrounding reference, add the surrounding 
1599         // instance of the child instance as the parent instance's surrounding instance
1600         if(((MethodDescriptor)md).isConstructor()) {
1601           min.addArgument(new NameNode(new NameDescriptor("surrounding$0")));
1602         } else if(((MethodDescriptor)md).getClassDesc().isInnerClass()&&!((MethodDescriptor)md).getClassDesc().isStatic()&&!((MethodDescriptor)md).getClassDesc().getInStaticContext()) {
1603           min.addArgument(new NameNode(new NameDescriptor("this$0")));
1604         }
1605       }
1606       tdarray=new TypeDescriptor[min.numArgs()];
1607       for(int i=0; i<min.numArgs(); i++) {
1608         ExpressionNode en=min.getArg(i);
1609         checkExpressionNode(md,nametable,en,null);
1610         tdarray[i]=en.getType();
1611
1612         if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1613           tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1614         }
1615       }
1616     } else if (md instanceof MethodDescriptor) {
1617       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1618     } else {
1619       /* If this a task descriptor we throw an error at this point */
1620       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1621     }
1622     if (!typetolookin.isClass())
1623       throw new Error("Error with method call to "+min.getMethodName()+" in class "+typetolookin);
1624     ClassDescriptor classtolookin=typetolookin.getClassDesc();
1625     checkClass(classtolookin, REFERENCE);
1626     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1627     MethodDescriptor bestmd=null;
1628 NextMethod:
1629     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext(); ) {
1630       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1631       /* Need correct number of parameters */
1632       if (min.numArgs()!=currmd.numParameters())
1633         continue;
1634       for(int i=0; i<min.numArgs(); i++) {
1635         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1636           if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
1637               && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
1638             // primitive parameters vs object
1639           } else {
1640             continue NextMethod;
1641           }
1642       }
1643       /* Method okay so far */
1644       if (bestmd==null)
1645         bestmd=currmd;
1646       else {
1647         if (typeutil.isMoreSpecific(currmd,bestmd, false)) {
1648           bestmd=currmd;
1649         } else if (!typeutil.isMoreSpecific(bestmd, currmd, false)) {
1650           // if the two methods are inherited from super class/interface, use the super class' as first priority
1651           if(bestmd.getClassDesc().isInterface()&&!currmd.getClassDesc().isInterface()) {
1652             bestmd = currmd;
1653           } else if(!bestmd.getClassDesc().isInterface()&&currmd.getClassDesc().isInterface()) {
1654             // maintain the non-interface one
1655           } else {
1656             throw new Error("No method is most specific:"+bestmd+" and "+currmd);
1657           }
1658         }
1659
1660         /* Is this more specific than bestmd */
1661       }
1662     }
1663     if (bestmd==null) {
1664       // if this is an inner class, need to check the method table for the surrounding class
1665       bestmd = recurseSurroundingClassesM(classtolookin, min.getMethodName());
1666       if(bestmd == null)
1667           throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1668       else {
1669           // set the correct "this" expression here
1670           ExpressionNode en=methodInvocationExpression(classtolookin, bestmd, min.getNumLine());
1671           min.setExpression(en);
1672           checkExpressionNode(md, nametable, min.getExpression(), null);
1673       }
1674     }
1675     min.setMethod(bestmd);
1676
1677     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
1678       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1679     /* Check whether we need to set this parameter to implied this */
1680     if (!isstatic && !bestmd.isStatic()) {
1681       if (min.getExpression()==null) {
1682         ExpressionNode en=new NameNode(new NameDescriptor("this"));
1683         min.setExpression(en);
1684         checkExpressionNode(md, nametable, min.getExpression(), null);
1685       }
1686     }
1687
1688     /* Check if we need to wrap primitive paratmeters to objects */
1689     for(int i=0; i<min.numArgs(); i++) {
1690       if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
1691          && min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
1692         // Shall wrap this primitive parameter as a object
1693         ExpressionNode exp = min.getArg(i);
1694         TypeDescriptor ptd = null;
1695         NameDescriptor nd=null;
1696         if(exp.getType().isInt()) {
1697           nd = new NameDescriptor("Integer");
1698           ptd = state.getTypeDescriptor(nd);
1699         } else if(exp.getType().isLong()) {
1700           nd = new NameDescriptor("Long");
1701           ptd = state.getTypeDescriptor(nd);
1702         }
1703         boolean isglobal = false;
1704         String disjointId = null;
1705         CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
1706         con.addArgument(exp);
1707         checkExpressionNode(md, nametable, con, null);
1708         min.setArgument(con, i);
1709       }
1710     }
1711   }
1712
1713
1714   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1715     checkExpressionNode(md, nametable, on.getLeft(), null);
1716     if (on.getRight()!=null)
1717       checkExpressionNode(md, nametable, on.getRight(), null);
1718     TypeDescriptor ltd=on.getLeft().getType();
1719     TypeDescriptor rtd=on.getRight()!=null?on.getRight().getType():null;
1720     TypeDescriptor lefttype=null;
1721     TypeDescriptor righttype=null;
1722     Operation op=on.getOp();
1723
1724     switch(op.getOp()) {
1725     case Operation.LOGIC_OR:
1726     case Operation.LOGIC_AND:
1727       if (!(rtd.isBoolean()))
1728         throw new Error();
1729       on.setRightType(rtd);
1730
1731     case Operation.LOGIC_NOT:
1732       if (!(ltd.isBoolean()))
1733         throw new Error();
1734       //no promotion
1735       on.setLeftType(ltd);
1736
1737       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1738       break;
1739
1740     case Operation.COMP:
1741       // 5.6.2 Binary Numeric Promotion
1742       //TODO unboxing of reference objects
1743       if (ltd.isDouble())
1744         throw new Error();
1745       else if (ltd.isFloat())
1746         throw new Error();
1747       else if (ltd.isLong())
1748         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1749       else
1750         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1751       on.setLeftType(lefttype);
1752       on.setType(lefttype);
1753       break;
1754
1755     case Operation.BIT_OR:
1756     case Operation.BIT_XOR:
1757     case Operation.BIT_AND:
1758       // 5.6.2 Binary Numeric Promotion
1759       //TODO unboxing of reference objects
1760       if (ltd.isDouble()||rtd.isDouble())
1761         throw new Error();
1762       else if (ltd.isFloat()||rtd.isFloat())
1763         throw new Error();
1764       else if (ltd.isLong()||rtd.isLong())
1765         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1766       // 090205 hack for boolean
1767       else if (ltd.isBoolean()||rtd.isBoolean())
1768         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1769       else
1770         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1771       righttype=lefttype;
1772
1773       on.setLeftType(lefttype);
1774       on.setRightType(righttype);
1775       on.setType(lefttype);
1776       break;
1777
1778     case Operation.ISAVAILABLE:
1779       if (!(ltd.isPtr())) {
1780         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1781       }
1782       lefttype=ltd;
1783       on.setLeftType(lefttype);
1784       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1785       break;
1786
1787     case Operation.EQUAL:
1788     case Operation.NOTEQUAL:
1789       // 5.6.2 Binary Numeric Promotion
1790       //TODO unboxing of reference objects
1791       if (ltd.isBoolean()||rtd.isBoolean()) {
1792         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1793           throw new Error();
1794         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1795       } else if (ltd.isPtr()||rtd.isPtr()) {
1796         if (!(ltd.isPtr()&&rtd.isPtr())) {
1797           if(!rtd.isEnum()) {
1798             throw new Error();
1799           }
1800         }
1801         righttype=rtd;
1802         lefttype=ltd;
1803       } else if (ltd.isDouble()||rtd.isDouble())
1804         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1805       else if (ltd.isFloat()||rtd.isFloat())
1806         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1807       else if (ltd.isLong()||rtd.isLong())
1808         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1809       else
1810         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1811
1812       on.setLeftType(lefttype);
1813       on.setRightType(righttype);
1814       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1815       break;
1816
1817
1818
1819     case Operation.LT:
1820     case Operation.GT:
1821     case Operation.LTE:
1822     case Operation.GTE:
1823       // 5.6.2 Binary Numeric Promotion
1824       //TODO unboxing of reference objects
1825       if (!ltd.isNumber()||!rtd.isNumber()) {
1826         if (!ltd.isNumber())
1827           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1828         if (!rtd.isNumber())
1829           throw new Error("Rightside is not number"+on.printNode(0));
1830       }
1831
1832       if (ltd.isDouble()||rtd.isDouble())
1833         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1834       else if (ltd.isFloat()||rtd.isFloat())
1835         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1836       else if (ltd.isLong()||rtd.isLong())
1837         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1838       else
1839         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1840       righttype=lefttype;
1841       on.setLeftType(lefttype);
1842       on.setRightType(righttype);
1843       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1844       break;
1845
1846     case Operation.ADD:
1847       if (ltd.isString()||rtd.isString()) {
1848         ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1849         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1850         NameDescriptor nd=new NameDescriptor("String");
1851         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1852         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1853           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1854           leftmin.setNumLine(on.getLeft().getNumLine());
1855           leftmin.addArgument(on.getLeft());
1856           on.left=leftmin;
1857           checkExpressionNode(md, nametable, on.getLeft(), null);
1858         }
1859
1860         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1861           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1862           rightmin.setNumLine(on.getRight().getNumLine());
1863           rightmin.addArgument(on.getRight());
1864           on.right=rightmin;
1865           checkExpressionNode(md, nametable, on.getRight(), null);
1866         }
1867
1868         on.setLeftType(stringtd);
1869         on.setRightType(stringtd);
1870         on.setType(stringtd);
1871         break;
1872       }
1873
1874     case Operation.SUB:
1875     case Operation.MULT:
1876     case Operation.DIV:
1877     case Operation.MOD:
1878       // 5.6.2 Binary Numeric Promotion
1879       //TODO unboxing of reference objects
1880       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1881         throw new Error("Error in "+on.printNode(0));
1882
1883       if (ltd.isDouble()||rtd.isDouble())
1884         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1885       else if (ltd.isFloat()||rtd.isFloat())
1886         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1887       else if (ltd.isLong()||rtd.isLong())
1888         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1889       else
1890         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1891       righttype=lefttype;
1892       on.setLeftType(lefttype);
1893       on.setRightType(righttype);
1894       on.setType(lefttype);
1895       break;
1896
1897     case Operation.LEFTSHIFT:
1898     case Operation.RIGHTSHIFT:
1899     case Operation.URIGHTSHIFT:
1900       if (!rtd.isIntegerType())
1901         throw new Error();
1902       //5.6.1 Unary Numeric Promotion
1903       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1904         righttype=new TypeDescriptor(TypeDescriptor.INT);
1905       else
1906         righttype=rtd;
1907
1908       on.setRightType(righttype);
1909       if (!ltd.isIntegerType())
1910         throw new Error();
1911
1912     case Operation.UNARYPLUS:
1913     case Operation.UNARYMINUS:
1914       /*        case Operation.POSTINC:
1915           case Operation.POSTDEC:
1916           case Operation.PREINC:
1917           case Operation.PREDEC:*/
1918       if (!ltd.isNumber())
1919         throw new Error();
1920       //5.6.1 Unary Numeric Promotion
1921       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1922         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1923       else
1924         lefttype=ltd;
1925       on.setLeftType(lefttype);
1926       on.setType(lefttype);
1927       break;
1928
1929     default:
1930       throw new Error(op.toString());
1931     }
1932
1933     if (td!=null)
1934       if (!typeutil.isSuperorType(td, on.getType())) {
1935         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1936       }
1937   }
1938
1939 }