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