adding a test case
[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___DOLLAR___0");
706                    fd = (FieldDescriptor)icd.getFieldTable().get("this___DOLLAR___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 = 0;
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         composed = "this___DOLLAR___" + String.valueOf(startingDepth-depth-1);
912         runningDesc = new NameDescriptor(runningDesc, composed);
913         NameDescriptor idDesc = new NameDescriptor( runningDesc, varname );
914         
915         
916         FieldAccessNode theFieldNode = ( FieldAccessNode )translateNameDescriptorintoExpression( idDesc, linenum );
917         return theFieldNode;
918   }
919   
920   Descriptor searchSurroundingNameTable(ClassDescriptor cd, String varname) {
921     Descriptor d = null;
922     if(cd.getInline()&&this.trialcheck) {
923       d = cd.getSurroundingNameTable().get(varname);
924     } else {
925       return d;
926     }
927     if(null == d) {
928       d = searchSurroundingNameTable(cd.getSurroundingDesc(), varname);
929     }
930     if(null != d) {
931       if(!this.inlineClass2LiveVars.containsKey(cd)) {
932         this.inlineClass2LiveVars.put(cd, new Vector<VarDescriptor>());
933       }
934       Vector<VarDescriptor> vars = this.inlineClass2LiveVars.get(cd);
935       if(!vars.contains((VarDescriptor)d)) {
936         vars.add((VarDescriptor)d);
937       }
938     }
939     return d;
940   }
941
942   void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
943     NameDescriptor nd=nn.getName();
944     if (nd.getBase()!=null) {
945       /* Big hack */
946       /* Rewrite NameNode */
947       ExpressionNode en=translateNameDescriptorintoExpression(nd,nn.getNumLine());
948       nn.setExpression(en);
949       checkExpressionNode(md,nametable,en,td);
950     } else {
951       String varname=nd.toString();
952       if(varname.equals("this") || varname.equals("super")) {
953         // "this"
954         nn.setVar((VarDescriptor)nametable.get("this"));
955         if(varname.equals("super")) {
956             nn.setIsSuper();
957         }
958         return;
959       }
960       Descriptor d=(Descriptor)nametable.get(varname);
961       if (d==null) {
962         ClassDescriptor cd = null;
963         //check the inner class case first.
964         if((md instanceof MethodDescriptor) && false == ((MethodDescriptor)md).isStaticBlock()) {
965                 cd = ((MethodDescriptor)md).getClassDesc();
966                 FieldAccessNode theFieldNode =  fieldAccessExpression( cd, varname, nn.getNumLine() );
967                 if( null != theFieldNode ) {
968                         nn.setExpression(( ExpressionNode )theFieldNode);
969                         checkExpressionNode(md,nametable,( ExpressionNode )theFieldNode,td);
970                         return;         
971                 } else {
972                     // for the trial check of an inline class, cache the unknown var
973                     d = searchSurroundingNameTable(cd, varname);
974                 }
975         }
976         if(null==d) {
977         if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
978           // this is a static block, all the accessed fields should be static field
979           cd = ((MethodDescriptor)md).getClassDesc();
980           SymbolTable fieldtbl = cd.getFieldTable();
981           FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
982           if((fd == null) || (!fd.isStatic())) {
983             // no such field in the class, check if this is a class
984             if(varname.equals("this")) {
985               throw new Error("Error: access this obj in a static block");
986             }
987             cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
988             if(cd != null) {
989               // this is a class name
990               nn.setClassDesc(cd);
991               return;
992             } else {
993               throw new Error("Name "+varname+" should not be used in static block: "+md);
994             }
995           } else {
996             // this is a static field
997             nn.setField(fd);
998             nn.setClassDesc(cd);
999             return;
1000           }
1001         } else {
1002           // check if the var is a static field of the class
1003           if(md instanceof MethodDescriptor) {
1004             cd = ((MethodDescriptor)md).getClassDesc();
1005             FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
1006             if((fd != null) && (fd.isStatic())) {
1007               nn.setField(fd);
1008               nn.setClassDesc(cd);
1009               if (td!=null)
1010                 if (!typeutil.isSuperorType(td,nn.getType()))
1011                   throw new Error("Field node returns "+nn.getType()+", but need "+td);
1012               return;
1013             } else if(fd != null) {
1014               throw new Error("Name "+varname+" should not be used in " + md);
1015             }
1016           }
1017           cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
1018           if(cd != null) {
1019             // this is a class name
1020             nn.setClassDesc(cd);
1021             return;
1022           } else {
1023             throw new Error("Name "+varname+" undefined in: "+md);          
1024           }
1025         }
1026         }
1027       }
1028
1029       if (d instanceof VarDescriptor) {
1030         nn.setVar(d);
1031       } else if (d instanceof FieldDescriptor) {
1032         FieldDescriptor fd=(FieldDescriptor)d;
1033         if (fd.getType().iswrapper()) {
1034           String id=nd.getIdentifier();
1035           NameDescriptor base=nd.getBase();
1036           NameNode n=new NameNode(nn.getName());
1037           n.setNumLine(nn.getNumLine());
1038           n.setField(fd);
1039           n.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
1040           FieldAccessNode fan=new FieldAccessNode(n,"value");
1041           fan.setNumLine(n.getNumLine());
1042           FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
1043           fan.setField(fdval);
1044           nn.setExpression(fan);
1045         } else {
1046           nn.setField(fd);
1047           nn.setVar((VarDescriptor)nametable.get("this"));        /* Need a pointer to this */
1048         }
1049       } else if (d instanceof TagVarDescriptor) {
1050         nn.setVar(d);
1051       } else throw new Error("Wrong type of descriptor");
1052       if (td!=null)
1053         if (!typeutil.isSuperorType(td,nn.getType()))
1054           throw new Error("Field node returns "+nn.getType()+", but need "+td);
1055     }
1056   }
1057
1058   void checkOffsetNode(Descriptor md, SymbolTable nameTable, OffsetNode ofn, TypeDescriptor td) {
1059     TypeDescriptor ltd=ofn.td;
1060     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null),ltd);
1061
1062     String fieldname = ofn.fieldname;
1063     FieldDescriptor fd=null;
1064     if (ltd.isArray()&&fieldname.equals("length")) {
1065       fd=FieldDescriptor.arrayLength;
1066     } else {
1067       fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
1068     }
1069
1070     ofn.setField(fd);
1071     checkField(ltd.getClassDesc(), fd);
1072
1073     if (fd==null)
1074       throw new Error("Unknown field "+fieldname + " in "+ofn.printNode(1)+" in "+md);
1075
1076     if (td!=null) {
1077       if (!typeutil.isSuperorType(td, ofn.getType())) {
1078         throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
1079       }
1080     }
1081   }
1082
1083
1084   void checkTertiaryNode(Descriptor md, SymbolTable nametable, TertiaryNode tn, TypeDescriptor td) {
1085     checkExpressionNode(md, nametable, tn.getCond(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1086     checkExpressionNode(md, nametable, tn.getTrueExpr(), td);
1087     checkExpressionNode(md, nametable, tn.getFalseExpr(), td);
1088   }
1089
1090   void checkInstanceOfNode(Descriptor md, SymbolTable nametable, InstanceOfNode tn, TypeDescriptor td) {
1091     if (td!=null&&!td.isBoolean())
1092       throw new Error("Expecting type "+td+"for instanceof expression");
1093
1094     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), tn.getExprType());
1095     checkExpressionNode(md, nametable, tn.getExpr(), null);
1096   }
1097
1098   void checkArrayInitializerNode(Descriptor md, SymbolTable nametable, ArrayInitializerNode ain, TypeDescriptor td) {
1099     for( int i = 0; i < ain.numVarInitializers(); ++i ) {
1100       checkExpressionNode(md, nametable, ain.getVarInitializer(i), td.dereference());
1101     }
1102     if (td==null)
1103         throw new Error();
1104     
1105     ain.setType(td);
1106   }
1107
1108   void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
1109     // Need to first check the lside to decide the correct type of the rside
1110     // TODO: Need check on validity of operation here
1111     if (!((an.getDest() instanceof FieldAccessNode)||
1112           (an.getDest() instanceof ArrayAccessNode)||
1113           (an.getDest() instanceof NameNode)))
1114       throw new Error("Bad lside in "+an.printNode(0));
1115     checkExpressionNode(md, nametable, an.getDest(), null);
1116     boolean postinc=true;
1117     if (an.getOperation().getBaseOp()==null||
1118         (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
1119          an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
1120       postinc=false;
1121     if (!postinc) {
1122       if(an.getSrc() instanceof ArrayInitializerNode) {
1123         checkExpressionNode(md, nametable, an.getSrc(), an.getDest().getType());
1124       } else {
1125         checkExpressionNode(md, nametable, an.getSrc(),td);
1126       }
1127     }
1128
1129     /* We want parameter variables to tasks to be immutable */
1130     if (md instanceof TaskDescriptor) {
1131       if (an.getDest() instanceof NameNode) {
1132         NameNode nn=(NameNode)an.getDest();
1133         if (nn.getVar()!=null) {
1134           if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
1135             throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
1136         }
1137       }
1138     }
1139
1140     if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
1141       //String add
1142       ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1143       TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1144       NameDescriptor nd=new NameDescriptor("String");
1145       NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1146
1147       if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
1148         MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1149         rightmin.setNumLine(an.getSrc().getNumLine());
1150         rightmin.addArgument(an.getSrc());
1151         an.right=rightmin;
1152         checkExpressionNode(md, nametable, an.getSrc(), null);
1153       }
1154     }
1155
1156     if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
1157       TypeDescriptor dt = an.getDest().getType();
1158       TypeDescriptor st = an.getSrc().getType();
1159       if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
1160         if(dt.getArrayCount() != st.getArrayCount()) {
1161           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1162         } else {
1163           do {
1164             dt = dt.dereference();
1165             st = st.dereference();
1166           } while(dt.isArray());
1167           if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1168              && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1169             return;
1170           } else {
1171             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1172           }
1173         }
1174       } else {
1175         Long l = an.getSrc().evaluate();
1176         if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
1177            && (l != null)
1178            && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
1179           long lnvalue = l.longValue();
1180           if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
1181              || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
1182              || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
1183              || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
1184              || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
1185             throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1186           }
1187         } else {
1188           throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
1189         }
1190       }
1191     }
1192   }
1193
1194   void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
1195     loopstack.push(ln);
1196     if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
1197       checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1198       checkBlockNode(md, nametable, ln.getBody());
1199     } else {
1200       //For loop case
1201       /* Link in the initializer naming environment */
1202       BlockNode bn=ln.getInitializer();
1203       bn.getVarTable().setParent(nametable);
1204       for(int i=0; i<bn.size(); i++) {
1205         BlockStatementNode bsn=bn.get(i);
1206         checkBlockStatementNode(md, bn.getVarTable(),bsn);
1207       }
1208       //check the condition
1209       checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
1210       checkBlockNode(md, bn.getVarTable(), ln.getBody());
1211       checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
1212     }
1213     loopstack.pop();
1214   }
1215
1216   void InnerClassAddParamToCtor( MethodDescriptor md, ClassDescriptor cd, SymbolTable nametable, 
1217                                  CreateObjectNode con, TypeDescriptor td ) {
1218     if(this.inlineClassWithTrialCheck.contains(cd)) {
1219       // this class has done this with its first trial check
1220       return;
1221     }
1222         TypeDescriptor cdsType = new TypeDescriptor( cd );
1223         ExpressionNode conExp = con.getSurroundingClassExpression();
1224         //System.out.println( "The surrounding class expression si " + con );
1225         if( null == conExp ) {
1226                 if( md.isStatic()) {
1227                         throw new Error("trying to instantiate inner class: " +  con.getType() + " in a static scope" );
1228                 }
1229                 VarDescriptor thisVD = md.getThis();
1230                 if( null == thisVD ) {
1231                         throw new Error( "this pointer is not defined in a non static scope" ); 
1232                 }                       
1233                 if( cdsType.equals( thisVD.getType() ) == false ) {
1234                         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" );             
1235                 }       
1236                 //make this into an expression node.
1237                 NameNode nThis=new NameNode( new NameDescriptor( "this" ) );
1238                 con.addArgument( nThis );
1239                 if(cd.isInnerClass()&&!cd.isStatic()) {
1240                   // add all the ith lexically enclosing instance if applicable
1241                   Iterator it_fields = cd.getFields();
1242                   int index = 0;
1243                   while(it_fields.hasNext()) {
1244                     FieldDescriptor fd = (FieldDescriptor)(it_fields.next());
1245                     if(fd.getSymbol().startsWith("this___DOLLAR___")) {
1246                       con.addArgument(new NameNode(new NameDescriptor("this___DOLLAR___"+index)));
1247                       index++;
1248                     }
1249                   }
1250                 }
1251         }
1252         else {
1253                 //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.
1254                 con.addArgument( conExp );
1255         }
1256         //System.out.println( " the modified createObjectNode is " + con.printNode( 0 ) + "\n" );
1257 }
1258   
1259   void trialSemanticCheck(ClassDescriptor cd) {
1260     if(this.inlineClassWithTrialCheck.contains(cd)) {
1261       // this inline class has done trial check
1262       return;
1263     }
1264     if(!cd.getInline()) {
1265       throw new Error("Error! Try to do a trial check on a non-inline class " + cd.getSymbol());
1266     }
1267     boolean settrial = false;
1268     if(!trialcheck) {
1269       trialcheck = true;
1270       settrial = true;
1271     }
1272       
1273     for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
1274       MethodDescriptor md = (MethodDescriptor) method_it.next();
1275       try {
1276         checkMethodBody(cd, md);
1277       } catch (Error e) {
1278         System.out.println("Error in " + md);
1279         throw e;
1280       }
1281     }
1282     this.inlineClassWithTrialCheck.add(cd);
1283     if(settrial) {
1284       trialcheck = false;
1285     }
1286   }
1287   
1288   // add all the live vars that are referred by the inline class in the surrounding 
1289   // context of the inline class into the inline class' field table and pass them to 
1290   // the inline class' constructors
1291   // TODO: BUGFIX. These local vars should be final. But currently we've lost those 
1292   // information, so we cannot have that checked.
1293   void InlineClassAddParamToCtor(MethodDescriptor md, ClassDescriptor cd , SymbolTable nametable, CreateObjectNode con, TypeDescriptor td, TypeDescriptor[] tdarray ) {
1294     if(this.inlineClassWithTrialCheck.contains(cd)) {
1295       // this class has done this with its first trial check
1296       return;
1297     }
1298     // for an inline class, need to first add the original parameters of the CreatObjectNode
1299     // into its anonymous constructor and insert a super(...) into the anonymous constructor
1300     // if its super class is not null
1301     MethodDescriptor cd_constructor = null;
1302     for(Iterator it_methods = cd.getMethods(); it_methods.hasNext();) {
1303       MethodDescriptor imd = (MethodDescriptor)it_methods.next();
1304       if(imd.isConstructor()) {
1305           cd_constructor = imd; // an inline class should only have one anonymous constructor
1306       }
1307     }
1308     MethodInvokeNode min = null;
1309     if(cd.getSuper()!= null) {
1310       // add a super(...) into the anonymous constructor
1311       NameDescriptor nd=new NameDescriptor("super");
1312       min=new MethodInvokeNode(nd);
1313       BlockExpressionNode ben=new BlockExpressionNode(min);
1314       BlockNode bn = state.getMethodBody(cd_constructor);
1315       bn.addFirstBlockStatement(ben);
1316       if(cd.getSuperDesc().isInnerClass()&&!cd.getSuperDesc().isStatic()&&!cd.getSuperDesc().getInStaticContext()) {
1317         // for a super class that is also an inner class with surrounding reference, add the surrounding 
1318         // instance of the child instance as the parent instance's surrounding instance
1319         min.addArgument(new NameNode(new NameDescriptor("surrounding___DOLLAR___0")));
1320       }
1321     }
1322     for(int i = 0 ; i < tdarray.length; i++) {
1323       assert(null!=min);
1324       TypeDescriptor itd = tdarray[i];
1325       cd_constructor.addParameter(itd, itd.getSymbol()+"_from_con_node_"+i);
1326       if(null != min) {
1327         min.addArgument(new NameNode(new NameDescriptor(itd.getSymbol()+"_from_con_node_"+i)));
1328       }
1329     }
1330     
1331     // Next add the live vars into the inline class' fields
1332     cd.setSurroundingNameTable(nametable);
1333     // do a round of semantic check trial to get all the live vars required by the inline class
1334     trialSemanticCheck(cd);
1335     Vector<VarDescriptor> vars = this.inlineClass2LiveVars.remove(cd);
1336     if(vars == null) {
1337       return;
1338     }
1339     for(int i = 0; i < vars.size(); i++) {
1340       Descriptor d = vars.elementAt(i);
1341       if(d instanceof VarDescriptor && !d.getSymbol().equals("this")) {
1342         con.addArgument(new NameNode(new NameDescriptor(d.getSymbol())));
1343         cd.addField(new FieldDescriptor(new Modifiers(Modifiers.PUBLIC), ((VarDescriptor)d).getType(), d.getSymbol(), null, false));
1344         cd_constructor.addParameter(((VarDescriptor)d).getType(), d.getSymbol()+"_p");
1345         // add the initialize statement into this constructor
1346         BlockNode obn = state.getMethodBody(cd_constructor);
1347         NameNode nn=new NameNode(new NameDescriptor(d.getSymbol()));
1348         NameNode fn = new NameNode (new NameDescriptor(d.getSymbol()+"_p"));
1349         AssignmentNode an=new AssignmentNode(nn,fn,new AssignOperation(1));
1350         obn.addFirstBlockStatement(new BlockExpressionNode(an));
1351         state.addTreeCode(cd_constructor, obn);
1352       }
1353     }
1354   }
1355   
1356   void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con,
1357                              TypeDescriptor td) {
1358     TypeDescriptor[] tdarray = new TypeDescriptor[con.numArgs()];
1359     for (int i = 0; i < con.numArgs(); i++) {
1360       ExpressionNode en = con.getArg(i);
1361       checkExpressionNode(md, nametable, en, null);
1362       tdarray[i] = en.getType();
1363     }
1364
1365     TypeDescriptor typetolookin = con.getType();
1366     checkTypeDescriptor(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), typetolookin);
1367
1368     if (td != null && !typeutil.isSuperorType(td, typetolookin))
1369       throw new Error(typetolookin + " isn't a " + td);
1370
1371     /* Check Array Initializers */
1372     if ((con.getArrayInitializer() != null)) {
1373       checkArrayInitializerNode(md, nametable, con.getArrayInitializer(), typetolookin);
1374     }
1375
1376     /* Check flag effects */
1377     if (con.getFlagEffects() != null) {
1378       FlagEffects fe = con.getFlagEffects();
1379       ClassDescriptor cd = typetolookin.getClassDesc();
1380
1381       for (int j = 0; j < fe.numEffects(); j++) {
1382         FlagEffect flag = fe.getEffect(j);
1383         String name = flag.getName();
1384         FlagDescriptor flag_d = (FlagDescriptor) cd.getFlagTable().get(name);
1385         // Make sure the flag is declared
1386         if (flag_d == null)
1387           throw new Error("Flag descriptor " + name + " undefined in class: " + cd.getSymbol());
1388         if (flag_d.getExternal())
1389           throw new Error("Attempting to modify external flag: " + name);
1390         flag.setFlag(flag_d);
1391       }
1392       for (int j = 0; j < fe.numTagEffects(); j++) {
1393         TagEffect tag = fe.getTagEffect(j);
1394         String name = tag.getName();
1395
1396         Descriptor d = (Descriptor) nametable.get(name);
1397         if (d == null)
1398           throw new Error("Tag descriptor " + name + " undeclared");
1399         else if (!(d instanceof TagVarDescriptor))
1400           throw new Error(name + " is not a tag descriptor");
1401         tag.setTag((TagVarDescriptor) d);
1402       }
1403     }
1404
1405     if ((!typetolookin.isClass()) && (!typetolookin.isArray()))
1406       throw new Error("Can't allocate primitive type:" + con.printNode(0));
1407
1408     if (!typetolookin.isArray()) {
1409       // Array's don't need constructor calls
1410       ClassDescriptor classtolookin = typetolookin.getClassDesc();
1411       checkClass(classtolookin, INIT);
1412       if( classtolookin.isInnerClass() ) {
1413         // for inner class that is declared in a static context, it does not have 
1414         // lexically enclosing instances
1415         if(!classtolookin.getInStaticContext()) {
1416             InnerClassAddParamToCtor( (MethodDescriptor)md, ((MethodDescriptor)md).getClassDesc() , nametable, con, td );
1417         }
1418         if(classtolookin.getInline()) {
1419           // for an inline anonymous inner class, the live local variables that are 
1420           // referred to by the inline class are passed as parameters of the constructors
1421           // of the inline class
1422           InlineClassAddParamToCtor( (MethodDescriptor)md, classtolookin, nametable, con, td, tdarray );
1423         }
1424         tdarray = new TypeDescriptor[con.numArgs()];
1425         for (int i = 0; i < con.numArgs(); i++) {
1426           ExpressionNode en = con.getArg(i);
1427           checkExpressionNode(md, nametable, en, null);
1428           tdarray[i] = en.getType();
1429         }
1430       }
1431       Set methoddescriptorset = classtolookin.getMethodTable().getSet(classtolookin.getSymbol());
1432       MethodDescriptor bestmd = null;
1433 NextMethod: for (Iterator methodit = methoddescriptorset.iterator(); methodit.hasNext(); ) {
1434         MethodDescriptor currmd = (MethodDescriptor) methodit.next();
1435         /* Need correct number of parameters */
1436         if (con.numArgs() != currmd.numParameters())
1437           continue;
1438         for (int i = 0; i < con.numArgs(); i++) {
1439           if (!typeutil.isSuperorType(currmd.getParamType(i), tdarray[i]))
1440             continue NextMethod;
1441         }
1442         /* Local allocations can't call global allocator */
1443         if (!con.isGlobal() && currmd.isGlobal())
1444           continue;
1445
1446         /* Method okay so far */
1447         if (bestmd == null)
1448           bestmd = currmd;
1449         else {
1450           if (typeutil.isMoreSpecific(currmd, bestmd, true)) {
1451             bestmd = currmd;
1452           } else if (con.isGlobal() && match(currmd, bestmd)) {
1453             if (currmd.isGlobal() && !bestmd.isGlobal())
1454               bestmd = currmd;
1455             else if (currmd.isGlobal() && bestmd.isGlobal())
1456               throw new Error();
1457           } else if (!typeutil.isMoreSpecific(bestmd, currmd, true)) {
1458             throw new Error("No method is most specific:" + bestmd + " and " + currmd);
1459           }
1460
1461           /* Is this more specific than bestmd */
1462         }
1463       }
1464       if (bestmd == null) {
1465         throw new Error("No method found for " + con.printNode(0) + " in " + md);
1466       }
1467       con.setConstructor(bestmd);
1468     }
1469   }
1470
1471
1472   /** Check to see if md1 is the same specificity as md2.*/
1473
1474   boolean match(MethodDescriptor md1, MethodDescriptor md2) {
1475     /* Checks if md1 is more specific than md2 */
1476     if (md1.numParameters()!=md2.numParameters())
1477       throw new Error();
1478     for(int i=0; i<md1.numParameters(); i++) {
1479       if (!md2.getParamType(i).equals(md1.getParamType(i)))
1480         return false;
1481     }
1482     if (!md2.getReturnType().equals(md1.getReturnType()))
1483       return false;
1484
1485     if (!md2.getClassDesc().equals(md1.getClassDesc()))
1486       return false;
1487
1488     return true;
1489   }
1490
1491
1492
1493   ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd, int numLine) {
1494     String id=nd.getIdentifier();
1495     NameDescriptor base=nd.getBase();
1496     if (base==null) {
1497       NameNode nn=new NameNode(nd);
1498       nn.setNumLine(numLine);
1499       return nn;
1500     } else {
1501       FieldAccessNode fan=new FieldAccessNode(translateNameDescriptorintoExpression(base,numLine),id);
1502       fan.setNumLine(numLine);
1503       return fan;
1504     }
1505   }
1506
1507   MethodDescriptor recurseSurroundingClassesM( ClassDescriptor icd, String varname ) {
1508       if( null == icd || false == icd.isInnerClass() )
1509             return null;
1510     
1511       ClassDescriptor surroundingDesc = icd.getSurroundingDesc();
1512       if( null == surroundingDesc )
1513             return null;
1514     
1515       SymbolTable methodTable = surroundingDesc.getMethodTable();
1516       MethodDescriptor md = ( MethodDescriptor ) methodTable.get( varname );
1517       if( null != md )
1518             return md;
1519       return recurseSurroundingClassesM( surroundingDesc, varname );
1520   }
1521
1522   ExpressionNode methodInvocationExpression( ClassDescriptor icd, MethodDescriptor md, int linenum ) {
1523         ClassDescriptor cd = md.getClassDesc();
1524         int depth = 1;
1525         int startingDepth = icd.getInnerDepth();
1526
1527         if( true == cd.isInnerClass() ) 
1528                 depth = cd.getInnerDepth();
1529
1530         String composed = "this";
1531         NameDescriptor runningDesc = new NameDescriptor( "this" );;
1532         
1533         for ( int index = startingDepth; index > depth; --index ) {
1534                 composed = "this___DOLLAR___" + String.valueOf( index - 1  );   
1535                 runningDesc = new NameDescriptor( runningDesc, composed );
1536         }
1537         if( false == cd.isInnerClass() )
1538                 runningDesc = new NameDescriptor( runningDesc, "this___DOLLAR___" + String.valueOf(0) ); //all the way up.
1539
1540         return new NameNode(runningDesc);
1541 }
1542
1543   void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
1544     /*Typecheck subexpressions
1545        and get types for expressions*/
1546
1547     boolean isstatic = false;
1548     if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStatic()) {
1549       isstatic = true;
1550     }
1551     TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
1552     for(int i=0; i<min.numArgs(); i++) {
1553       ExpressionNode en=min.getArg(i);
1554       checkExpressionNode(md,nametable,en,null);
1555       tdarray[i]=en.getType();
1556
1557       if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1558         tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1559       }
1560     }
1561     TypeDescriptor typetolookin=null;
1562     if (min.getExpression()!=null) {
1563       checkExpressionNode(md,nametable,min.getExpression(),null);
1564       typetolookin=min.getExpression().getType();
1565     } else if (min.getBaseName()!=null) {
1566       String rootname=min.getBaseName().getRoot();
1567       if (rootname.equals("super")) {
1568         ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1569         typetolookin=new TypeDescriptor(supercd);
1570         min.setSuper();
1571       } else if (rootname.equals("this")) {
1572         if(isstatic) {
1573           throw new Error("use this object in static method md = "+ md.toString());
1574         }
1575         ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
1576         typetolookin=new TypeDescriptor(cd);
1577       } else if (nametable.get(rootname)!=null) {
1578         //we have an expression
1579         min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
1580         checkExpressionNode(md, nametable, min.getExpression(), null);
1581         typetolookin=min.getExpression().getType();
1582       } else {
1583         if(!min.getBaseName().getSymbol().equals("System.out")||state.JNI) {
1584           ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
1585           checkExpressionNode(md, nametable, nn, null);
1586           typetolookin = nn.getType();
1587           if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
1588                && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
1589             // this is not a pure class name, need to add to
1590             min.setExpression(nn);
1591           }
1592         } else {
1593           //we have a type
1594           ClassDescriptor cd = getClass(null, "System");
1595
1596           if (cd==null)
1597             throw new Error("md = "+ md.toString()+ "  "+min.getBaseName()+" undefined");
1598           typetolookin=new TypeDescriptor(cd);
1599         }
1600       }
1601     } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
1602       ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
1603       min.methodid=supercd.getSymbol();
1604       typetolookin=new TypeDescriptor(supercd);
1605       if(supercd.isInnerClass()&&!supercd.isStatic()&&!supercd.getInStaticContext()) {
1606         // for a super class that is also an inner class with surrounding reference, add the surrounding 
1607         // instance of the child instance as the parent instance's surrounding instance
1608         if(((MethodDescriptor)md).isConstructor()) {
1609           min.addArgument(new NameNode(new NameDescriptor("surrounding___DOLLAR___0")));
1610         } else if(((MethodDescriptor)md).getClassDesc().isInnerClass()&&!((MethodDescriptor)md).getClassDesc().isStatic()&&!((MethodDescriptor)md).getClassDesc().getInStaticContext()) {
1611           min.addArgument(new NameNode(new NameDescriptor("this___DOLLAR___0")));
1612         }
1613       }
1614       tdarray=new TypeDescriptor[min.numArgs()];
1615       for(int i=0; i<min.numArgs(); i++) {
1616         ExpressionNode en=min.getArg(i);
1617         checkExpressionNode(md,nametable,en,null);
1618         tdarray[i]=en.getType();
1619
1620         if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
1621           tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
1622         }
1623       }
1624     } else if (md instanceof MethodDescriptor) {
1625       typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
1626     } else {
1627       /* If this a task descriptor we throw an error at this point */
1628       throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
1629     }
1630     if (!typetolookin.isClass())
1631       throw new Error("Error with method call to "+min.getMethodName()+" in class "+typetolookin);
1632     ClassDescriptor classtolookin=typetolookin.getClassDesc();
1633     checkClass(classtolookin, REFERENCE);
1634     Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
1635     MethodDescriptor bestmd=null;
1636 NextMethod:
1637     for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext(); ) {
1638       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
1639       /* Need correct number of parameters */
1640       if (min.numArgs()!=currmd.numParameters())
1641         continue;
1642       for(int i=0; i<min.numArgs(); i++) {
1643         if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
1644           if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
1645               && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
1646             // primitive parameters vs object
1647           } else {
1648             continue NextMethod;
1649           }
1650       }
1651       /* Method okay so far */
1652       if (bestmd==null)
1653         bestmd=currmd;
1654       else {
1655         if (typeutil.isMoreSpecific(currmd,bestmd, false)) {
1656           bestmd=currmd;
1657         } else if (!typeutil.isMoreSpecific(bestmd, currmd, false)) {
1658           // if the two methods are inherited from super class/interface, use the super class' as first priority
1659           if(bestmd.getClassDesc().isInterface()&&!currmd.getClassDesc().isInterface()) {
1660             bestmd = currmd;
1661           } else if(!bestmd.getClassDesc().isInterface()&&currmd.getClassDesc().isInterface()) {
1662             // maintain the non-interface one
1663           } else {
1664             throw new Error("No method is most specific:"+bestmd+" and "+currmd);
1665           }
1666         }
1667
1668         /* Is this more specific than bestmd */
1669       }
1670     }
1671     if (bestmd==null) {
1672       // if this is an inner class, need to check the method table for the surrounding class
1673       bestmd = recurseSurroundingClassesM(classtolookin, min.getMethodName());
1674       if(bestmd == null)
1675           throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
1676       else {
1677           // set the correct "this" expression here
1678           ExpressionNode en=methodInvocationExpression(classtolookin, bestmd, min.getNumLine());
1679           min.setExpression(en);
1680           checkExpressionNode(md, nametable, min.getExpression(), null);
1681       }
1682     }
1683     min.setMethod(bestmd);
1684
1685     if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td,  min.getType()))
1686       throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
1687     /* Check whether we need to set this parameter to implied this */
1688     if (!isstatic && !bestmd.isStatic()) {
1689       if (min.getExpression()==null) {
1690         ExpressionNode en=new NameNode(new NameDescriptor("this"));
1691         min.setExpression(en);
1692         checkExpressionNode(md, nametable, min.getExpression(), null);
1693       }
1694     }
1695
1696     /* Check if we need to wrap primitive paratmeters to objects */
1697     for(int i=0; i<min.numArgs(); i++) {
1698       if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
1699          && min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
1700         // Shall wrap this primitive parameter as a object
1701         ExpressionNode exp = min.getArg(i);
1702         TypeDescriptor ptd = null;
1703         NameDescriptor nd=null;
1704         if(exp.getType().isInt()) {
1705           nd = new NameDescriptor("Integer");
1706           ptd = state.getTypeDescriptor(nd);
1707         } else if(exp.getType().isLong()) {
1708           nd = new NameDescriptor("Long");
1709           ptd = state.getTypeDescriptor(nd);
1710         }
1711         boolean isglobal = false;
1712         String disjointId = null;
1713         CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
1714         con.addArgument(exp);
1715         checkExpressionNode(md, nametable, con, null);
1716         min.setArgument(con, i);
1717       }
1718     }
1719   }
1720
1721
1722   void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
1723     checkExpressionNode(md, nametable, on.getLeft(), null);
1724     if (on.getRight()!=null)
1725       checkExpressionNode(md, nametable, on.getRight(), null);
1726     TypeDescriptor ltd=on.getLeft().getType();
1727     TypeDescriptor rtd=on.getRight()!=null?on.getRight().getType():null;
1728     TypeDescriptor lefttype=null;
1729     TypeDescriptor righttype=null;
1730     Operation op=on.getOp();
1731
1732     switch(op.getOp()) {
1733     case Operation.LOGIC_OR:
1734     case Operation.LOGIC_AND:
1735       if (!(rtd.isBoolean()))
1736         throw new Error();
1737       on.setRightType(rtd);
1738
1739     case Operation.LOGIC_NOT:
1740       if (!(ltd.isBoolean()))
1741         throw new Error();
1742       //no promotion
1743       on.setLeftType(ltd);
1744
1745       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1746       break;
1747
1748     case Operation.COMP:
1749       // 5.6.2 Binary Numeric Promotion
1750       //TODO unboxing of reference objects
1751       if (ltd.isDouble())
1752         throw new Error();
1753       else if (ltd.isFloat())
1754         throw new Error();
1755       else if (ltd.isLong())
1756         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1757       else
1758         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1759       on.setLeftType(lefttype);
1760       on.setType(lefttype);
1761       break;
1762
1763     case Operation.BIT_OR:
1764     case Operation.BIT_XOR:
1765     case Operation.BIT_AND:
1766       // 5.6.2 Binary Numeric Promotion
1767       //TODO unboxing of reference objects
1768       if (ltd.isDouble()||rtd.isDouble())
1769         throw new Error();
1770       else if (ltd.isFloat()||rtd.isFloat())
1771         throw new Error();
1772       else if (ltd.isLong()||rtd.isLong())
1773         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1774       // 090205 hack for boolean
1775       else if (ltd.isBoolean()||rtd.isBoolean())
1776         lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1777       else
1778         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1779       righttype=lefttype;
1780
1781       on.setLeftType(lefttype);
1782       on.setRightType(righttype);
1783       on.setType(lefttype);
1784       break;
1785
1786     case Operation.ISAVAILABLE:
1787       if (!(ltd.isPtr())) {
1788         throw new Error("Can't use isavailable on non-pointers/non-parameters.");
1789       }
1790       lefttype=ltd;
1791       on.setLeftType(lefttype);
1792       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1793       break;
1794
1795     case Operation.EQUAL:
1796     case Operation.NOTEQUAL:
1797       // 5.6.2 Binary Numeric Promotion
1798       //TODO unboxing of reference objects
1799       if (ltd.isBoolean()||rtd.isBoolean()) {
1800         if (!(ltd.isBoolean()&&rtd.isBoolean()))
1801           throw new Error();
1802         righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
1803       } else if (ltd.isPtr()||rtd.isPtr()) {
1804         if (!(ltd.isPtr()&&rtd.isPtr())) {
1805           if(!rtd.isEnum()) {
1806             throw new Error();
1807           }
1808         }
1809         righttype=rtd;
1810         lefttype=ltd;
1811       } else if (ltd.isDouble()||rtd.isDouble())
1812         righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1813       else if (ltd.isFloat()||rtd.isFloat())
1814         righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1815       else if (ltd.isLong()||rtd.isLong())
1816         righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1817       else
1818         righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
1819
1820       on.setLeftType(lefttype);
1821       on.setRightType(righttype);
1822       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1823       break;
1824
1825
1826
1827     case Operation.LT:
1828     case Operation.GT:
1829     case Operation.LTE:
1830     case Operation.GTE:
1831       // 5.6.2 Binary Numeric Promotion
1832       //TODO unboxing of reference objects
1833       if (!ltd.isNumber()||!rtd.isNumber()) {
1834         if (!ltd.isNumber())
1835           throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
1836         if (!rtd.isNumber())
1837           throw new Error("Rightside is not number"+on.printNode(0));
1838       }
1839
1840       if (ltd.isDouble()||rtd.isDouble())
1841         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1842       else if (ltd.isFloat()||rtd.isFloat())
1843         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1844       else if (ltd.isLong()||rtd.isLong())
1845         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1846       else
1847         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1848       righttype=lefttype;
1849       on.setLeftType(lefttype);
1850       on.setRightType(righttype);
1851       on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
1852       break;
1853
1854     case Operation.ADD:
1855       if (ltd.isString()||rtd.isString()) {
1856         ClassDescriptor stringcl=getClass(null, TypeUtil.StringClass);
1857         TypeDescriptor stringtd=new TypeDescriptor(stringcl);
1858         NameDescriptor nd=new NameDescriptor("String");
1859         NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
1860         if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
1861           MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
1862           leftmin.setNumLine(on.getLeft().getNumLine());
1863           leftmin.addArgument(on.getLeft());
1864           on.left=leftmin;
1865           checkExpressionNode(md, nametable, on.getLeft(), null);
1866         }
1867
1868         if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
1869           MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
1870           rightmin.setNumLine(on.getRight().getNumLine());
1871           rightmin.addArgument(on.getRight());
1872           on.right=rightmin;
1873           checkExpressionNode(md, nametable, on.getRight(), null);
1874         }
1875
1876         on.setLeftType(stringtd);
1877         on.setRightType(stringtd);
1878         on.setType(stringtd);
1879         break;
1880       }
1881
1882     case Operation.SUB:
1883     case Operation.MULT:
1884     case Operation.DIV:
1885     case Operation.MOD:
1886       // 5.6.2 Binary Numeric Promotion
1887       //TODO unboxing of reference objects
1888       if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
1889         throw new Error("Error in "+on.printNode(0));
1890
1891       if (ltd.isDouble()||rtd.isDouble())
1892         lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
1893       else if (ltd.isFloat()||rtd.isFloat())
1894         lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
1895       else if (ltd.isLong()||rtd.isLong())
1896         lefttype=new TypeDescriptor(TypeDescriptor.LONG);
1897       else
1898         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1899       righttype=lefttype;
1900       on.setLeftType(lefttype);
1901       on.setRightType(righttype);
1902       on.setType(lefttype);
1903       break;
1904
1905     case Operation.LEFTSHIFT:
1906     case Operation.RIGHTSHIFT:
1907     case Operation.URIGHTSHIFT:
1908       if (!rtd.isIntegerType())
1909         throw new Error();
1910       //5.6.1 Unary Numeric Promotion
1911       if (rtd.isByte()||rtd.isShort()||rtd.isInt())
1912         righttype=new TypeDescriptor(TypeDescriptor.INT);
1913       else
1914         righttype=rtd;
1915
1916       on.setRightType(righttype);
1917       if (!ltd.isIntegerType())
1918         throw new Error();
1919
1920     case Operation.UNARYPLUS:
1921     case Operation.UNARYMINUS:
1922       /*        case Operation.POSTINC:
1923           case Operation.POSTDEC:
1924           case Operation.PREINC:
1925           case Operation.PREDEC:*/
1926       if (!ltd.isNumber())
1927         throw new Error();
1928       //5.6.1 Unary Numeric Promotion
1929       if (ltd.isByte()||ltd.isShort()||ltd.isInt())
1930         lefttype=new TypeDescriptor(TypeDescriptor.INT);
1931       else
1932         lefttype=ltd;
1933       on.setLeftType(lefttype);
1934       on.setType(lefttype);
1935       break;
1936
1937     default:
1938       throw new Error(op.toString());
1939     }
1940
1941     if (td!=null)
1942       if (!typeutil.isSuperorType(td, on.getType())) {
1943         throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
1944       }
1945   }
1946
1947 }