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