changes + annotation generation
[IRC.git] / Robust / src / IR / Tree / BuildIR.java
1 package IR.Tree;
2 import IR.*;
3 import Util.Lattice;
4 import Util.Pair;
5
6 import java.io.File;
7 import java.util.*;
8 import java.io.*;
9 import java.lang.Throwable;
10 public class BuildIR {
11   State state;
12   private boolean isRunningRecursiveInnerClass;
13   private int m_taskexitnum;
14
15   public BuildIR(State state) {
16     this.state=state;
17     this.m_taskexitnum = 0;
18     this.isRunningRecursiveInnerClass = false;
19   }
20
21   public void buildtree(ParseNode pn, Set toanalyze, String sourcefile) {
22     parseFile(pn, toanalyze, sourcefile);
23
24     // numering the interfaces
25     int if_num = 0;
26     Iterator it_classes = state.getClassSymbolTable().getValueSet().iterator();
27     while(it_classes.hasNext()) {
28       ClassDescriptor cd = (ClassDescriptor)it_classes.next();
29       if(cd.isInterface()) {
30         cd.setInterfaceId(if_num++);
31       }
32     }
33   }
34
35   //This is all single imports and a subset of the
36   //multi imports that have been resolved.
37   ChainHashMap mandatoryImports;
38   //maps class names in file to full name
39   //Note may map a name to an ERROR.
40   ChainHashMap multiimports;
41   String packageName;
42
43   String currsourcefile;
44   Set analyzeset;
45
46   void pushChainMaps() {
47     mandatoryImports=mandatoryImports.makeChild();
48     multiimports=multiimports.makeChild();
49   }
50   
51   void popChainMaps() {
52     mandatoryImports=mandatoryImports.getParent();
53     multiimports=multiimports.getParent();
54   }
55
56   /** Parse the classes in this file */
57   public void parseFile(ParseNode pn, Set toanalyze, String sourcefile) {
58     mandatoryImports = new ChainHashMap();
59     multiimports = new ChainHashMap();
60     currsourcefile=sourcefile;
61     analyzeset=toanalyze;
62
63     if(state.JNI) {
64       //add java.lang as our default multi-import
65       this.addMultiImport(sourcefile, "java.lang", false);
66     }
67
68     ParseNode ipn = pn.getChild("imports").getChild("import_decls_list");
69     if ((ipn != null) && !state.MGC) {
70       ParseNodeVector pnv = ipn.getChildren();
71       for (int i = 0; i < pnv.size(); i++) {
72         ParseNode pnimport = pnv.elementAt(i);
73         NameDescriptor nd = parseName(pnimport.getChild("name"));
74         if (isNode(pnimport, "import_single")) {
75           if (!mandatoryImports.containsKey(nd.getIdentifier())) {
76             // map name to full name (includes package/directory
77             mandatoryImports.put(nd.getIdentifier(), nd.getPathFromRootToHere());
78           } else {
79             throw new Error("An ambiguous class "+ nd.getIdentifier() +" has been found. It is included for " +
80                             ((String)mandatoryImports.get(nd.getIdentifier())) + " and " +
81                             nd.getPathFromRootToHere());
82           }
83         } else {
84           addMultiImport(sourcefile, nd.getPathFromRootToHere(), false);
85         }
86       }
87     }
88
89     ParseNode ppn=pn.getChild("packages").getChild("package");
90     packageName = null;
91     if ((ppn!=null) && !state.MGC){
92       NameDescriptor nd = parseClassName(ppn.getChild("name"));
93       packageName = nd.getPathFromRootToHere();
94       //Trick -> import the package directory as a multi-import and it'll
95       //automatically recognize files in the same directory.
96       addMultiImport(sourcefile, packageName, true);
97     }
98
99     ParseNode tpn=pn.getChild("type_declaration_list");
100     if (tpn != null) {
101       ParseNodeVector pnv = tpn.getChildren();
102       for (int i = 0; i < pnv.size(); i++) {
103         ParseNode type_pn = pnv.elementAt(i);
104         if (isEmpty(type_pn)) /* Skip the semicolon */
105           continue;
106         if (isNode(type_pn, "class_declaration")) {
107           ClassDescriptor cn = parseTypeDecl(type_pn);
108           parseInitializers(cn);
109
110           // for inner classes/enum
111           HashSet tovisit = new HashSet();
112           Iterator it_icds = cn.getInnerClasses();
113           while (it_icds.hasNext()) {
114             tovisit.add(it_icds.next());
115           }
116
117           while (!tovisit.isEmpty()) {
118             ClassDescriptor cd = (ClassDescriptor) tovisit.iterator().next();
119             tovisit.remove(cd);
120             parseInitializers(cd);
121
122             Iterator it_ics = cd.getInnerClasses();
123             while (it_ics.hasNext()) {
124               tovisit.add(it_ics.next());
125             }
126           }
127         } else if (isNode(type_pn, "task_declaration")) {
128           TaskDescriptor td = parseTaskDecl(type_pn);
129           if (toanalyze != null)
130             toanalyze.add(td);
131           state.addTask(td);
132         } else if (isNode(type_pn, "interface_declaration")) {
133           // TODO add version for normal Java later
134           ClassDescriptor cn = parseInterfaceDecl(type_pn, null);
135         } else if (isNode(type_pn, "enum_declaration")) {
136           // TODO add version for normal Java later
137           ClassDescriptor cn = parseEnumDecl(null, type_pn);
138
139         } else if(isNode(type_pn,"annotation_type_declaration")) {
140           ClassDescriptor cn=parseAnnotationTypeDecl(type_pn);
141         } else {
142           throw new Error(type_pn.getLabel());
143         }
144       }
145     }
146   }
147
148
149   //This kind of breaks away from tradition a little bit by doing the file checks here
150   // instead of in Semantic check, but doing it here is easier because we have a mapping early on
151   // if I wait until semantic check, I have to change ALL the type descriptors to match the new
152   // mapping and that's both ugly and tedious.
153   private void addMultiImport(String currentSource, String importPath, boolean isPackageDirectory) {
154     boolean found = false;
155     for (int j = 0; j < state.classpath.size(); j++) {
156       String path = (String) state.classpath.get(j);
157       File folder = new File(path, importPath.replace('.', '/'));
158       if (folder.exists()) {
159         found = true;
160         for (String file : folder.list()) {
161           // if the file is of type *.java add to multiImport list.
162           if (file.lastIndexOf('.') != -1 && file.substring(file.lastIndexOf('.')).equalsIgnoreCase(".java")) {
163             String classname = file.substring(0, file.length() - 5);
164             // single imports have precedence over multi-imports
165             if (!mandatoryImports.containsKey(classname)) {
166               //package files have precedence over multi-imports.
167               if (multiimports.containsKey(classname)  && !isPackageDirectory) {
168                 // put error in for later, in case we try to import
169                 multiimports.put(classname, new Error("Error: class " + classname + " is defined more than once in a multi-import in " + currentSource));
170               } else {
171                 multiimports.put(classname, importPath + "." + classname);
172               }
173             }
174           }
175         }
176       }
177     }
178
179     if(!found) {
180       throw new Error("Import package " + importPath + " in  " + currentSource
181                       + " cannot be resolved.");
182     }
183   }
184
185   public void parseInitializers(ClassDescriptor cn) {
186     Vector fv=cn.getFieldVec();
187     Iterator methodit = cn.getMethods();
188     HashMap<MethodDescriptor, Integer> md2pos = new HashMap<MethodDescriptor, Integer>();
189     while(methodit.hasNext()) {
190       MethodDescriptor currmd=(MethodDescriptor)methodit.next();
191       if(currmd.isConstructor()) {
192         BlockNode bn=state.getMethodBody(currmd);
193         // if there are super(...) invokation, the initializers should be invoked after that
194         int i = 0;
195         for(; i < bn.size(); i++) {
196           if(Kind.BlockExpressionNode==bn.get(i).kind()
197                   &&(((BlockExpressionNode)bn.get(i)).getExpression() instanceof MethodInvokeNode)
198                   &&((MethodInvokeNode)(((BlockExpressionNode)bn.get(i)).getExpression())).getMethodName().equals("super")) {
199             break;
200           }
201         }
202         if(i==bn.size()) {
203           md2pos.put(currmd, 0);
204         } else {
205           md2pos.put(currmd, i+1);
206         }
207       }
208     }
209     int pos = 0;
210     for(int i=0; i<fv.size(); i++) {
211       FieldDescriptor fd=(FieldDescriptor)fv.get(i);
212       if(fd.getExpressionNode()!=null) {
213         methodit = cn.getMethods();
214         while(methodit.hasNext()) {
215           MethodDescriptor currmd=(MethodDescriptor)methodit.next();
216           if(currmd.isConstructor()) {
217             int offset = md2pos.get(currmd);
218             BlockNode bn=state.getMethodBody(currmd);
219             NameNode nn=new NameNode(new NameDescriptor(fd.getSymbol()));
220             AssignmentNode an=new AssignmentNode(nn,fd.getExpressionNode(),new AssignOperation(1));
221             bn.addBlockStatementAt(new BlockExpressionNode(an), pos+offset);
222           }
223         }
224         pos++;
225       }
226     }
227   }
228   
229   private ClassDescriptor parseEnumDecl(ClassDescriptor cn, ParseNode pn) {    
230     String basename=pn.getChild("name").getTerminal();
231     String classname=(cn!=null)?cn.getClassName()+"$"+basename:basename;
232     ClassDescriptor ecd=new ClassDescriptor(cn!=null?cn.getPackage():null, classname, false);
233     
234     if (cn!=null) {
235       if (packageName==null)
236         cn.getSingleImportMappings().put(basename,classname);
237       else
238         cn.getSingleImportMappings().put(basename,packageName+"."+classname);
239     }
240
241     pushChainMaps();
242     ecd.setImports(mandatoryImports, multiimports);
243     ecd.setAsEnum();
244     if(cn != null) {
245       ecd.setSurroundingClass(cn.getSymbol());
246       ecd.setSurrounding(cn);
247       cn.addEnum(ecd);
248     }
249     if (!(ecd.getSymbol().equals(TypeUtil.ObjectClass)||
250           ecd.getSymbol().equals(TypeUtil.TagClass))) {
251       ecd.setSuper(TypeUtil.ObjectClass);
252     }
253     ecd.setModifiers(parseModifiersList(pn.getChild("modifiers")));
254     parseEnumBody(ecd, pn.getChild("enumbody"));
255
256     addClass2State(ecd);
257
258     popChainMaps();
259     return ecd;
260   }
261
262   private void parseEnumBody(ClassDescriptor cn, ParseNode pn) {
263     ParseNode decls=pn.getChild("enum_constants_list");
264     if (decls!=null) {
265       ParseNodeVector pnv=decls.getChildren();
266       for(int i=0; i<pnv.size(); i++) {
267         ParseNode decl=pnv.elementAt(i);
268         if (isNode(decl,"enum_constant")) {
269           parseEnumConstant(cn,decl);
270         } else throw new Error();
271       }
272     }
273   }
274
275   private void parseEnumConstant(ClassDescriptor cn, ParseNode pn) {
276     cn.addEnumConstant(pn.getChild("name").getTerminal());
277   }
278
279   private ClassDescriptor parseAnnotationTypeDecl(ParseNode pn) {
280     ClassDescriptor cn=new ClassDescriptor(pn.getChild("name").getTerminal(), true);
281     pushChainMaps();
282     cn.setImports(mandatoryImports, multiimports);
283     ParseNode modifiers=pn.getChild("modifiers");
284     if(modifiers!=null) {
285       cn.setModifiers(parseModifiersList(modifiers));
286     }
287     parseAnnotationTypeBody(cn,pn.getChild("body"));
288     popChainMaps();
289
290     addClass2State(cn);
291
292     return cn;
293   }
294
295   private void parseAnnotationTypeBody(ClassDescriptor cn, ParseNode pn) {
296     ParseNode list_node=pn.getChild("annotation_type_element_list");
297     if(list_node!=null) {
298       ParseNodeVector pnv = list_node.getChildren();
299       for (int i = 0; i < pnv.size(); i++) {
300         ParseNode element_node = pnv.elementAt(i);
301         if (isNode(element_node, "annotation_type_element_declaration")) {
302           ParseNodeVector elementProps = element_node.getChildren();
303           String identifier=null;
304           TypeDescriptor type=null;
305           Modifiers modifiers=new Modifiers();
306           for(int eidx=0; eidx<elementProps.size(); eidx++) {
307             ParseNode prop_node=elementProps.elementAt(eidx);
308             if(isNode(prop_node,"name")) {
309               identifier=prop_node.getTerminal();
310             } else if(isNode(prop_node,"type")) {
311               type=parseTypeDescriptor(prop_node);
312             } else if(isNode(prop_node,"modifier")) {
313               modifiers=parseModifiersList(prop_node);
314             }
315           }
316           cn.addField(new FieldDescriptor(modifiers, type, identifier, null, false));
317         }
318       }
319     }
320   }
321
322   public ClassDescriptor parseInterfaceDecl(ParseNode pn, ClassDescriptor outerclass) {
323     String basename=pn.getChild("name").getTerminal();
324     String classname=((outerclass==null)?"":(outerclass.getClassName()+"$"))+basename;
325     if (outerclass!=null) {
326       if (packageName==null)
327         outerclass.getSingleImportMappings().put(basename,classname);
328       else
329         outerclass.getSingleImportMappings().put(basename,packageName+"."+classname);
330     }
331     ClassDescriptor cn= new ClassDescriptor(packageName, classname, true);
332
333     pushChainMaps();
334     cn.setImports(mandatoryImports, multiimports);
335     //cn.setAsInterface();
336     if (!isEmpty(pn.getChild("superIF").getTerminal())) {
337       /* parse inherited interface name */
338       ParseNode snlist=pn.getChild("superIF").getChild("extend_interface_list");
339       ParseNodeVector pnv=snlist.getChildren();
340       for(int i=0; i<pnv.size(); i++) {
341         ParseNode decl=pnv.elementAt(i);
342         if (isNode(decl,"type")) {
343           NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
344           cn.addSuperInterface(nd.toString());
345         } else if (isNode(decl, "interface_declaration")) {
346           ClassDescriptor innercn = parseInterfaceDecl(decl, cn);
347         } else throw new Error();
348       }
349     }
350     cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
351     parseInterfaceBody(cn, pn.getChild("interfacebody"));
352     addClass2State(cn);
353     popChainMaps();
354     return cn;
355   }
356
357   private void parseInterfaceBody(ClassDescriptor cn, ParseNode pn) {
358     assert(cn.isInterface());
359     ParseNode decls=pn.getChild("interface_member_declaration_list");
360     if (decls!=null) {
361       ParseNodeVector pnv=decls.getChildren();
362       for(int i=0; i<pnv.size(); i++) {
363         ParseNode decl=pnv.elementAt(i);
364         if (isNode(decl,"constant")) {
365           parseInterfaceConstant(cn,decl);
366         } else if (isNode(decl,"method")) {
367           parseInterfaceMethod(cn,decl.getChild("method_declaration"));
368         } else if (isNode(decl, "interface_declaration")) {
369           parseInterfaceDecl(decl, cn);
370         } else throw new Error(decl.PPrint(2, true));
371       }
372     }
373   }
374
375
376
377   private void parseInterfaceConstant(ClassDescriptor cn, ParseNode pn) {
378     if (pn!=null) {
379       parseFieldDecl(cn,pn.getChild("field_declaration"));
380       return;
381     }
382     throw new Error();
383   }
384
385   private void parseInterfaceMethod(ClassDescriptor cn, ParseNode pn) {
386     ParseNode headern=pn.getChild("header");
387     ParseNode bodyn=pn.getChild("body");
388     MethodDescriptor md=parseMethodHeader(headern.getChild("method_header"));
389     md.getModifiers().addModifier(Modifiers.PUBLIC);
390     md.getModifiers().addModifier(Modifiers.ABSTRACT);
391     try {
392       BlockNode bn=parseBlock(cn, md, md.isStatic()||md.isStaticBlock(), bodyn);
393       cn.addMethod(md);
394       state.addTreeCode(md,bn);
395     } catch (Exception e) {
396       System.out.println("Error with method:"+md.getSymbol());
397       e.printStackTrace();
398       throw new Error();
399     } catch (Error e) {
400       System.out.println("Error with method:"+md.getSymbol());
401       e.printStackTrace();
402       throw new Error();
403     }
404   }
405
406   public TaskDescriptor parseTaskDecl(ParseNode pn) {
407     TaskDescriptor td=new TaskDescriptor(pn.getChild("name").getTerminal());
408     ParseNode bodyn=pn.getChild("body");
409     BlockNode bn=parseBlock(null, null, false, bodyn);
410     parseParameterList(td, pn);
411     state.addTreeCode(td,bn);
412     if (pn.getChild("flag_effects_list")!=null)
413       td.addFlagEffects(parseFlags(pn.getChild("flag_effects_list")));
414     return td;
415   }
416
417   public Vector parseFlags(ParseNode pn) {
418     Vector vfe=new Vector();
419     ParseNodeVector pnv=pn.getChildren();
420     for(int i=0; i<pnv.size(); i++) {
421       ParseNode fn=pnv.elementAt(i);
422       FlagEffects fe=parseFlagEffects(fn);
423       vfe.add(fe);
424     }
425     return vfe;
426   }
427
428   public FlagEffects parseFlagEffects(ParseNode pn) {
429     if (isNode(pn,"flag_effect")) {
430       String flagname=pn.getChild("name").getTerminal();
431       FlagEffects fe=new FlagEffects(flagname);
432       if (pn.getChild("flag_list")!=null)
433         parseFlagEffect(fe, pn.getChild("flag_list"));
434       if (pn.getChild("tag_list")!=null)
435         parseTagEffect(fe, pn.getChild("tag_list"));
436       return fe;
437     } else throw new Error();
438   }
439
440   public void parseTagEffect(FlagEffects fes, ParseNode pn) {
441     ParseNodeVector pnv=pn.getChildren();
442     for(int i=0; i<pnv.size(); i++) {
443       ParseNode pn2=pnv.elementAt(i);
444       boolean status=true;
445       if (isNode(pn2,"not")) {
446         status=false;
447         pn2=pn2.getChild("name");
448       }
449       String name=pn2.getTerminal();
450       fes.addTagEffect(new TagEffect(name,status));
451     }
452   }
453
454   public void parseFlagEffect(FlagEffects fes, ParseNode pn) {
455     ParseNodeVector pnv=pn.getChildren();
456     for(int i=0; i<pnv.size(); i++) {
457       ParseNode pn2=pnv.elementAt(i);
458       boolean status=true;
459       if (isNode(pn2,"not")) {
460         status=false;
461         pn2=pn2.getChild("name");
462       }
463       String name=pn2.getTerminal();
464       fes.addEffect(new FlagEffect(name,status));
465     }
466   }
467
468   public FlagExpressionNode parseFlagExpression(ParseNode pn) {
469     if (isNode(pn,"or")) {
470       ParseNodeVector pnv=pn.getChildren();
471       ParseNode left=pnv.elementAt(0);
472       ParseNode right=pnv.elementAt(1);
473       return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_OR));
474     } else if (isNode(pn,"and")) {
475       ParseNodeVector pnv=pn.getChildren();
476       ParseNode left=pnv.elementAt(0);
477       ParseNode right=pnv.elementAt(1);
478       return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_AND));
479     } else if (isNode(pn, "not")) {
480       ParseNodeVector pnv=pn.getChildren();
481       ParseNode left=pnv.elementAt(0);
482       return new FlagOpNode(parseFlagExpression(left), new Operation(Operation.LOGIC_NOT));
483
484     } else if (isNode(pn,"name")) {
485       return new FlagNode(pn.getTerminal());
486     } else {
487       throw new Error();
488     }
489   }
490
491   public Vector parseChecks(ParseNode pn) {
492     Vector ccs=new Vector();
493     ParseNodeVector pnv=pn.getChildren();
494     for(int i=0; i<pnv.size(); i++) {
495       ParseNode fn=pnv.elementAt(i);
496       ConstraintCheck cc=parseConstraintCheck(fn);
497       ccs.add(cc);
498     }
499     return ccs;
500   }
501
502   public ConstraintCheck parseConstraintCheck(ParseNode pn) {
503     if (isNode(pn,"cons_check")) {
504       String specname=pn.getChild("name").getChild("identifier").getTerminal();
505       Vector[] args=parseConsArgumentList(pn);
506       ConstraintCheck cc=new ConstraintCheck(specname);
507       for(int i=0; i<args[0].size(); i++) {
508         cc.addVariable((String)args[0].get(i));
509         cc.addArgument((ExpressionNode)args[1].get(i));
510       }
511       return cc;
512     } else throw new Error();
513   }
514
515   public void parseParameterList(TaskDescriptor td, ParseNode pn) {
516
517     boolean optional;
518     ParseNode paramlist=pn.getChild("task_parameter_list");
519     if (paramlist==null)
520       return;
521     ParseNodeVector pnv=paramlist.getChildren();
522     for(int i=0; i<pnv.size(); i++) {
523       ParseNode paramn=pnv.elementAt(i);
524       if(paramn.getChild("optional")!=null) {
525         optional = true;
526         paramn = paramn.getChild("optional").getFirstChild();
527         System.out.println("OPTIONAL FOUND!!!!!!!");
528       } else { optional = false;
529                System.out.println("NOT OPTIONAL"); }
530
531       TypeDescriptor type=parseTypeDescriptor(paramn);
532
533       String paramname=paramn.getChild("single").getTerminal();
534       FlagExpressionNode fen=null;
535       if (paramn.getChild("flag")!=null)
536         fen=parseFlagExpression(paramn.getChild("flag").getFirstChild());
537
538       ParseNode tagnode=paramn.getChild("tag");
539
540       TagExpressionList tel=null;
541       if (tagnode!=null) {
542         tel=parseTagExpressionList(tagnode);
543       }
544
545       td.addParameter(type,paramname,fen, tel, optional);
546     }
547   }
548
549   public TagExpressionList parseTagExpressionList(ParseNode pn) {
550     //BUG FIX: change pn.getChildren() to pn.getChild("tag_expression_list").getChildren()
551     //To test, feed in any input program that uses tags
552     ParseNodeVector pnv=pn.getChild("tag_expression_list").getChildren();
553     TagExpressionList tel=new TagExpressionList();
554     for(int i=0; i<pnv.size(); i++) {
555       ParseNode tn=pnv.elementAt(i);
556       String type=tn.getChild("type").getTerminal();
557       String name=tn.getChild("single").getTerminal();
558       tel.addTag(type, name);
559     }
560     return tel;
561   }
562
563   private void addClass2State(ClassDescriptor cn) {
564     if (analyzeset != null)
565       analyzeset.add(cn);
566     cn.setSourceFileName(currsourcefile);
567     state.addClass(cn);
568     // create this$n representing a final reference to the next surrounding class. each inner class should have whatever inner class
569     // pointers the surrounding class has + a pointer to the surrounding class.
570     if( true )
571     {
572       this.isRunningRecursiveInnerClass = true; //fOR dEBUGGING PURPOSES IN ORDER TO DUMP STRINGS WHILE IN THIS CODE PATH
573       addOuterClassReferences( cn, cn, 0 );
574       addOuterClassParam( cn, cn, 0 );
575       this.isRunningRecursiveInnerClass = false;
576     }
577   }
578   
579   public ClassDescriptor parseTypeDecl(ParseNode pn) {
580     ClassDescriptor cn=new ClassDescriptor(packageName, pn.getChild("name").getTerminal(), false);
581     pushChainMaps();
582     cn.setImports(mandatoryImports, multiimports);
583     if (!isEmpty(pn.getChild("super").getTerminal())) {
584       /* parse superclass name */
585       ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
586       NameDescriptor nd=parseClassName(snn);
587       cn.setSuper(nd.toString());
588     } else {
589       if (!(cn.getSymbol().equals(TypeUtil.ObjectClass)||
590             cn.getSymbol().equals(TypeUtil.TagClass)))
591         cn.setSuper(TypeUtil.ObjectClass);
592     }
593     // check inherited interfaces
594     if (!isEmpty(pn.getChild("superIF").getTerminal())) {
595       /* parse inherited interface name */
596       ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list");
597       ParseNodeVector pnv=snlist.getChildren();
598       for(int i=0; i<pnv.size(); i++) {
599         ParseNode decl=pnv.elementAt(i);
600         if (isNode(decl,"type")) {
601           NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
602           cn.addSuperInterface(nd.toString());
603         }
604       }
605     }
606     cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
607     parseClassBody(cn, pn.getChild("classbody"));
608
609     boolean hasConstructor = false;
610     for(Iterator method_it=cn.getMethods(); method_it.hasNext(); ) {
611       MethodDescriptor md=(MethodDescriptor)method_it.next();
612       hasConstructor |= md.isConstructor();
613     }
614     if((!hasConstructor) && (!cn.isEnum())) {
615       // add a default constructor for this class
616       MethodDescriptor md = new MethodDescriptor(new Modifiers(Modifiers.PUBLIC),
617                                                  cn.getSymbol(), false);
618       BlockNode bn=new BlockNode();
619       state.addTreeCode(md,bn);
620       md.setDefaultConstructor();
621       cn.addMethod(md);
622     }
623
624
625     popChainMaps();
626
627     cn.setSourceFileName(currsourcefile);
628     
629     addClass2State(cn);
630
631     return cn;
632   }
633
634 private void initializeOuterMember( MethodDescriptor md, String fieldName, String formalParameter ) {
635          BlockNode obn = state.getMethodBody(md);
636          NameNode nn=new NameNode( new NameDescriptor( fieldName ) );
637          NameNode fn = new NameNode ( new NameDescriptor( formalParameter ) );
638           //nn.setNumLine(en.getNumLine())
639          AssignmentNode an=new AssignmentNode(nn,fn,new AssignOperation(1));
640          //an.setNumLine(pn.getLine());
641          obn.addFirstBlockStatement(new BlockExpressionNode(an));
642         // System.out.print( "The code inserted is : " + obn.printNode( 0 ) + "\n" );
643          state.addTreeCode(md, obn);
644 }
645
646 private void addOuterClassParam( ClassDescriptor cn, ClassDescriptor ocn, int depth )
647 {
648         Iterator nullCheckItr = cn.getInnerClasses();
649         if( false == nullCheckItr.hasNext() )
650                 return;
651
652         //create a typedescriptor of type cn
653         TypeDescriptor theTypeDesc = new TypeDescriptor( ocn );
654         
655         for(Iterator it=cn.getInnerClasses(); it.hasNext(); ) {
656                 ClassDescriptor icd=(ClassDescriptor)it.next();
657                 if(icd.isStatic()||icd.getInStaticContext()) {
658                     continue;
659                 }
660                 
661                 //iterate over all ctors of I.Cs and add a new param
662                 for(Iterator method_it=icd.getMethods(); method_it.hasNext(); ) {
663                          MethodDescriptor md=(MethodDescriptor)method_it.next();
664                          if( md.isConstructor() ){
665                                 md.addParameter( theTypeDesc, "surrounding___DOLLAR___" + String.valueOf(depth) );      
666                                 initializeOuterMember( md, "this___DOLLAR___" + String.valueOf( depth ), "surrounding___DOLLAR___" + String.valueOf(depth) );
667                                 //System.out.println( "The added param is " + md.toString() + "\n" );
668                         }
669                 }
670                 addOuterClassParam( icd, ocn, depth + 1 );
671                 
672         }
673         
674 }
675 private void addOuterClassReferences( ClassDescriptor cn, ClassDescriptor ocn, int depth )
676 {
677         //SYMBOLTABLE does not have a length or empty method, hence could not define a hasInnerClasses method in classDescriptor
678         Iterator nullCheckItr = cn.getInnerClasses();
679         if( false == nullCheckItr.hasNext() )
680                 return;
681
682         String tempCopy = ocn.getClassName();
683         //MESSY HACK FOLLOWS
684         int i = 0;
685
686         ParseNode theNode = new ParseNode( "field_declaration" );
687         theNode.addChild("modifier").addChild( new ParseNode( "modifier_list" ) ).addChild("final");
688         ParseNode theTypeNode = new ParseNode("type");
689         ParseNode tempChildNode = theTypeNode.addChild("class").addChild( "name" );
690                 //tempChildNode.addChild("base").addChild( new ParseNode("empty") );
691         tempChildNode.addChild("identifier").addChild ( tempCopy );
692         theNode.addChild("type").addChild( theTypeNode );
693         ParseNode variableDeclaratorID = new ParseNode("single");
694         String theStr = "this___DOLLAR___" + String.valueOf( depth );
695         variableDeclaratorID.addChild( theStr );
696         ParseNode variableDeclarator = new ParseNode( "variable_declarator" );
697         variableDeclarator.addChild( variableDeclaratorID );
698         ParseNode variableDeclaratorList = new ParseNode("variable_declarators_list");
699         variableDeclaratorList.addChild( variableDeclarator );
700         theNode.addChild("variables").addChild( variableDeclaratorList );
701
702         for(Iterator it=cn.getInnerClasses(); it.hasNext(); ) {
703                 ClassDescriptor icd=(ClassDescriptor)it.next();
704                 if(icd.isStatic() || icd.getInStaticContext()) {
705                   continue;
706                 }
707                 parseFieldDecl( icd, theNode );         
708                 /*if( true ) {
709                         SymbolTable fieldTable = icd.getFieldTable();
710                         //System.out.println( fieldTable.toString() );
711                 }*/
712                 icd.setInnerDepth( depth + 1 );
713                 addOuterClassReferences( icd, ocn, depth + 1 ); 
714         }
715 }
716
717   private void parseClassBody(ClassDescriptor cn, ParseNode pn) {
718     ParseNode decls=pn.getChild("class_body_declaration_list");
719     if (decls!=null) {
720       ParseNodeVector pnv=decls.getChildren();
721       for(int i=0; i<pnv.size(); i++) {
722         ParseNode decl=pnv.elementAt(i);
723         if (isNode(decl,"member")) {
724           parseClassMember(cn,decl);
725         } else if (isNode(decl,"constructor")) {
726           parseConstructorDecl(cn,decl.getChild("constructor_declaration"));
727         } else if (isNode(decl, "static_block")) {
728           parseStaticBlockDecl(cn, decl.getChild("static_block_declaration"));
729         } else if (isNode(decl,"block")) {
730         } else throw new Error();
731       }
732     }
733   }
734
735   private void parseClassMember(ClassDescriptor cn, ParseNode pn) {
736     ParseNode fieldnode=pn.getChild("field");
737     if (fieldnode!=null) {
738       //System.out.println( pn.PPrint( 0, true ) );
739       parseFieldDecl(cn,fieldnode.getChild("field_declaration"));
740       return;
741     }
742     ParseNode methodnode=pn.getChild("method");
743     if (methodnode!=null) {
744       parseMethodDecl(cn,methodnode.getChild("method_declaration"));
745       return;
746     }
747     ParseNode innerclassnode=pn.getChild("inner_class_declaration");
748     if (innerclassnode!=null) {
749       parseInnerClassDecl(cn,innerclassnode);
750       return;
751     }
752      ParseNode innerinterfacenode=pn.getChild("interface_declaration");
753     if (innerinterfacenode!=null) {
754       parseInterfaceDecl(innerinterfacenode, cn);
755       return;
756     }
757
758     ParseNode enumnode=pn.getChild("enum_declaration");
759     if (enumnode!=null) {
760       ClassDescriptor ecn=parseEnumDecl(cn,enumnode);
761       return;
762     }
763     ParseNode flagnode=pn.getChild("flag");
764     if (flagnode!=null) {
765       parseFlagDecl(cn, flagnode.getChild("flag_declaration"));
766       return;
767     }
768     // in case there are empty node
769     ParseNode emptynode=pn.getChild("empty");
770     if(emptynode != null) {
771       return;
772     }
773     System.out.println("Unrecognized node:"+pn.PPrint(2,true));
774     throw new Error();
775   }
776
777 //10/9/2011 changed this function to enable creation of default constructor for inner classes.
778 //the change was refactoring this function with the corresponding version for normal classes. sganapat
779   private ClassDescriptor parseInnerClassDecl(ClassDescriptor cn, ParseNode pn) {
780     String basename=pn.getChild("name").getTerminal();
781     String classname=cn.getClassName()+"$"+basename;
782
783     if (cn.getPackage()==null)
784       cn.getSingleImportMappings().put(basename,classname);
785     else
786       cn.getSingleImportMappings().put(basename,cn.getPackage()+"."+classname);
787     
788     ClassDescriptor icn=new ClassDescriptor(cn.getPackage(), classname, false);
789     pushChainMaps();
790     icn.setImports(mandatoryImports, multiimports);
791     icn.setSurroundingClass(cn.getSymbol());
792     icn.setSurrounding(cn);
793     cn.addInnerClass(icn);
794
795      if (!isEmpty(pn.getChild("super").getTerminal())) {
796       /* parse superclass name */
797       ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
798       NameDescriptor nd=parseClassName(snn);
799       icn.setSuper(nd.toString());
800     } else {
801       if (!(icn.getSymbol().equals(TypeUtil.ObjectClass)||
802             icn.getSymbol().equals(TypeUtil.TagClass)))
803         icn.setSuper(TypeUtil.ObjectClass);
804     }
805     // check inherited interfaces
806     if (!isEmpty(pn.getChild("superIF").getTerminal())) {
807       /* parse inherited interface name */
808       ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list");
809       ParseNodeVector pnv=snlist.getChildren();
810       for(int i=0; i<pnv.size(); i++) {
811         ParseNode decl=pnv.elementAt(i);
812         if (isNode(decl,"type")) {
813           NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
814           icn.addSuperInterface(nd.toString());
815         }
816       }
817     }
818     icn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
819
820    if (!icn.isStatic())
821      icn.setAsInnerClass();
822
823     parseClassBody(icn, pn.getChild("classbody"));
824
825     boolean hasConstructor = false;
826     for(Iterator method_it=icn.getMethods(); method_it.hasNext(); ) {
827       MethodDescriptor md=(MethodDescriptor)method_it.next();
828       hasConstructor |= md.isConstructor();
829     }
830 //sganapat adding change to allow proper construction of inner class objects
831     if((!hasConstructor) && (!icn.isEnum())) {
832       // add a default constructor for this class
833       MethodDescriptor md = new MethodDescriptor(new Modifiers(Modifiers.PUBLIC),
834                                                  icn.getSymbol(), false);
835       BlockNode bn=new BlockNode();
836       state.addTreeCode(md,bn);
837       md.setDefaultConstructor();
838       icn.addMethod(md);
839    }
840     popChainMaps();
841
842     addClass2State(icn);
843
844     return icn;
845   }
846
847   private TypeDescriptor parseTypeDescriptor(ParseNode pn) {
848     ParseNode tn=pn.getChild("type");
849     String type_st=tn.getTerminal();
850     if(type_st.equals("byte")) {
851       return state.getTypeDescriptor(TypeDescriptor.BYTE);
852     } else if(type_st.equals("short")) {
853       return state.getTypeDescriptor(TypeDescriptor.SHORT);
854     } else if(type_st.equals("boolean")) {
855       return state.getTypeDescriptor(TypeDescriptor.BOOLEAN);
856     } else if(type_st.equals("int")) {
857       return state.getTypeDescriptor(TypeDescriptor.INT);
858     } else if(type_st.equals("long")) {
859       return state.getTypeDescriptor(TypeDescriptor.LONG);
860     } else if(type_st.equals("char")) {
861       return state.getTypeDescriptor(TypeDescriptor.CHAR);
862     } else if(type_st.equals("float")) {
863       return state.getTypeDescriptor(TypeDescriptor.FLOAT);
864     } else if(type_st.equals("double")) {
865       return state.getTypeDescriptor(TypeDescriptor.DOUBLE);
866     } else if(type_st.equals("class")) {
867       ParseNode nn=tn.getChild("class");
868       return state.getTypeDescriptor(parseClassName(nn.getChild("name")));
869     } else if(type_st.equals("array")) {
870       ParseNode nn=tn.getChild("array");
871       TypeDescriptor td=parseTypeDescriptor(nn.getChild("basetype"));
872       Integer numdims=(Integer)nn.getChild("dims").getLiteral();
873       for(int i=0; i<numdims.intValue(); i++)
874         td=td.makeArray(state);
875       return td;
876     } else {
877       System.out.println(pn.PPrint(2, true));
878       throw new Error();
879     }
880   }
881
882   //Needed to separate out top level call since if a base exists,
883   //we do not want to apply our resolveName function (i.e. deal with imports)
884   //otherwise, if base == null, we do just want to resolve name.
885   private NameDescriptor parseClassName(ParseNode nn) {
886     
887
888     ParseNode base=nn.getChild("base");
889     ParseNode id=nn.getChild("identifier");
890     String classname = id.getTerminal();
891     if (base==null) {
892       return new NameDescriptor(resolveName(classname));
893     }
894     return new NameDescriptor(parseClassNameRecursive(base.getChild("name")),classname);
895   }
896
897   private NameDescriptor parseClassNameRecursive(ParseNode nn) {
898     ParseNode base=nn.getChild("base");
899     ParseNode id=nn.getChild("identifier");
900     String classname = id.getTerminal();
901     if (base==null) {
902       return new NameDescriptor(classname);
903     }
904     return new NameDescriptor(parseClassNameRecursive(base.getChild("name")),classname);
905   }
906
907   //This will get the mapping of a terminal class name
908   //to a canonical classname (with imports/package locations in them)
909   private String resolveName(String terminal) {
910     
911     if(mandatoryImports.containsKey(terminal)) {
912       return (String) mandatoryImports.get(terminal);
913     } else {
914       if(multiimports.containsKey(terminal)) {
915         //Test for error
916         Object o = multiimports.get(terminal);
917         if(o instanceof Error) {
918           throw new Error("Class " + terminal + " is ambiguous. Cause: more than 1 package import contain the same class.");
919         } else {
920           //At this point, if we found a unique class
921           //we can treat it as a single, mandatory import.
922           mandatoryImports.put(terminal, o);
923           return (String) o;
924         }
925       }
926     }
927
928     return terminal;
929   }
930
931   //only function difference between this and parseName() is that this
932   //does not look for a import mapping.
933   private NameDescriptor parseName(ParseNode nn) {
934     ParseNode base=nn.getChild("base");
935     ParseNode id=nn.getChild("identifier");
936     if (base==null) {
937       return new NameDescriptor(id.getTerminal());
938     }
939     return new NameDescriptor(parseName(base.getChild("name")),id.getTerminal());
940   }
941
942   private void parseFlagDecl(ClassDescriptor cn,ParseNode pn) {
943     String name=pn.getChild("name").getTerminal();
944     FlagDescriptor flag=new FlagDescriptor(name);
945     if (pn.getChild("external")!=null)
946       flag.makeExternal();
947     cn.addFlag(flag);
948   }
949
950   private void parseFieldDecl(ClassDescriptor cn,ParseNode pn) {
951     ParseNode mn=pn.getChild("modifier");
952     Modifiers m=parseModifiersList(mn);
953     if(cn.isInterface()) {
954       // TODO add version for normal Java later
955       // Can only be PUBLIC or STATIC or FINAL
956       if((m.isAbstract()) || (m.isAtomic()) || (m.isNative())
957          || (m.isSynchronized())) {
958         throw new Error("Error: field in Interface " + cn.getSymbol() + "can only be PUBLIC or STATIC or FINAL");
959       }
960       m.addModifier(Modifiers.PUBLIC);
961       m.addModifier(Modifiers.STATIC);
962       m.addModifier(Modifiers.FINAL);
963     }
964
965     ParseNode tn=pn.getChild("type");
966     TypeDescriptor t=parseTypeDescriptor(tn);
967     ParseNode vn=pn.getChild("variables").getChild("variable_declarators_list");
968     ParseNodeVector pnv=vn.getChildren();
969     boolean isglobal=pn.getChild("global")!=null;
970
971     for(int i=0; i<pnv.size(); i++) {
972       ParseNode vardecl=pnv.elementAt(i);
973       ParseNode tmp=vardecl;
974       TypeDescriptor arrayt=t;
975        if( this.isRunningRecursiveInnerClass && false )
976         {       
977                 System.out.println( "the length of the list is " + String.valueOf( pnv.size() ) );
978                 System.out.println( "\n the parse node is \n" + tmp.PPrint( 0, true ) );
979         }
980       while (tmp.getChild("single")==null) {
981         arrayt=arrayt.makeArray(state);
982         tmp=tmp.getChild("array");
983       }
984       String identifier=tmp.getChild("single").getTerminal();
985       ParseNode epn=vardecl.getChild("initializer");
986
987       ExpressionNode en=null;
988       
989       if (epn!=null) {
990         en=parseExpression(cn, null, m.isStatic(), epn.getFirstChild());
991         en.setNumLine(epn.getFirstChild().getLine());
992         if(m.isStatic()) {
993           // for static field, the initializer should be considered as a
994           // static block
995           boolean isfirst = false;
996           MethodDescriptor md = (MethodDescriptor)cn.getMethodTable().getFromSameScope("staticblocks");
997           if(md == null) {
998             // the first static block for this class
999             Modifiers m_i=new Modifiers();
1000             m_i.addModifier(Modifiers.STATIC);
1001             md = new MethodDescriptor(m_i, "staticblocks", false);
1002             md.setAsStaticBlock();
1003             isfirst = true;
1004           }
1005           if(isfirst) {
1006             cn.addMethod(md);
1007           }
1008           cn.incStaticBlocks();
1009           BlockNode bn=new BlockNode();
1010           NameNode nn=new NameNode(new NameDescriptor(identifier));
1011           nn.setNumLine(en.getNumLine());
1012           AssignmentNode an=new AssignmentNode(nn,en,new AssignOperation(1));
1013           an.setNumLine(pn.getLine());
1014           bn.addBlockStatement(new BlockExpressionNode(an));
1015           if(isfirst) {
1016             state.addTreeCode(md,bn);
1017           } else {
1018             BlockNode obn = state.getMethodBody(md);
1019             for(int ii = 0; ii < bn.size(); ii++) {
1020               BlockStatementNode bsn = bn.get(ii);
1021               obn.addBlockStatement(bsn);
1022             }
1023             state.addTreeCode(md, obn);
1024             bn = null;
1025           }
1026           en = null;
1027         }
1028       }
1029
1030       FieldDescriptor fd=new FieldDescriptor(m, arrayt, identifier, en, isglobal);
1031       fd.setLineNum(tmp.getLine());
1032       cn.addField(fd);
1033       assignAnnotationsToType(m,arrayt);
1034     }
1035   }
1036
1037   private void assignAnnotationsToType(Modifiers modifiers, TypeDescriptor type) {
1038     Vector<AnnotationDescriptor> annotations=modifiers.getAnnotations();
1039     for(int i=0; i<annotations.size(); i++) {
1040       // it only supports a marker annotation
1041       AnnotationDescriptor an=annotations.elementAt(i);
1042       type.addAnnotationMarker(an);
1043     }
1044   }
1045
1046   int innerCount=0;
1047
1048   private ExpressionNode parseExpression(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1049     if (isNode(pn,"assignment"))
1050         {
1051           //System.out.println( "parsing a field decl in my class that has assignment in initialization " + pn.PPrint( 0, true ) + "\n");
1052       return parseAssignmentExpression(cn, md, isStaticContext, pn);
1053         }
1054     else if (isNode(pn,"logical_or")||isNode(pn,"logical_and")||
1055              isNode(pn,"bitwise_or")||isNode(pn,"bitwise_xor")||
1056              isNode(pn,"bitwise_and")||isNode(pn,"equal")||
1057              isNode(pn,"not_equal")||isNode(pn,"comp_lt")||
1058              isNode(pn,"comp_lte")||isNode(pn,"comp_gt")||
1059              isNode(pn,"comp_gte")||isNode(pn,"leftshift")||
1060              isNode(pn,"rightshift")||isNode(pn,"sub")||
1061              isNode(pn,"urightshift")||isNode(pn,"sub")||
1062              isNode(pn,"add")||isNode(pn,"mult")||
1063              isNode(pn,"div")||isNode(pn,"mod")) {
1064       ParseNodeVector pnv=pn.getChildren();
1065       ParseNode left=pnv.elementAt(0);
1066       ParseNode right=pnv.elementAt(1);
1067       Operation op=new Operation(pn.getLabel());
1068       OpNode on=new OpNode(parseExpression(cn, md, isStaticContext, left),parseExpression(cn, md, isStaticContext,  right),op);
1069       on.setNumLine(pn.getLine());
1070       return on;
1071     } else if (isNode(pn,"unaryplus")||
1072                isNode(pn,"unaryminus")||
1073                isNode(pn,"not")||
1074                isNode(pn,"comp")) {
1075       ParseNode left=pn.getFirstChild();
1076       Operation op=new Operation(pn.getLabel());
1077       OpNode on=new OpNode(parseExpression(cn, md, isStaticContext, left),op);
1078       on.setNumLine(pn.getLine());
1079       return on;
1080     } else if (isNode(pn,"postinc")||
1081                isNode(pn,"postdec")) {
1082       ParseNode left=pn.getFirstChild();
1083       AssignOperation op=new AssignOperation(pn.getLabel());
1084       AssignmentNode an=new AssignmentNode(parseExpression(cn, md, isStaticContext, left),null,op);
1085       an.setNumLine(pn.getLine());
1086       return an;
1087
1088     } else if (isNode(pn,"preinc")||
1089                isNode(pn,"predec")) {
1090       ParseNode left=pn.getFirstChild();
1091       AssignOperation op=isNode(pn,"preinc")?new AssignOperation(AssignOperation.PLUSEQ):new AssignOperation(AssignOperation.MINUSEQ);
1092       AssignmentNode an=new AssignmentNode(parseExpression(cn, md, isStaticContext, left),
1093                                            new LiteralNode("integer",new Integer(1)),op);
1094       an.setNumLine(pn.getLine());
1095       return an;
1096     } else if (isNode(pn,"literal")) {
1097       String literaltype=pn.getTerminal();
1098       ParseNode literalnode=pn.getChild(literaltype);
1099       Object literal_obj=literalnode.getLiteral();
1100       LiteralNode ln=new LiteralNode(literaltype, literal_obj);
1101       ln.setNumLine(pn.getLine());
1102       return ln;
1103     } else if (isNode(pn, "createobject")) {
1104       TypeDescriptor td = parseTypeDescriptor(pn);
1105
1106       Vector args = parseArgumentList(cn, md, isStaticContext, pn);
1107       boolean isglobal = pn.getChild("global") != null || pn.getChild("scratch") != null;
1108       String disjointId = null;
1109       if (pn.getChild("disjoint") != null) {
1110         disjointId = pn.getChild("disjoint").getTerminal();
1111       }
1112       ParseNode idChild = (pn.getChild( "id" ));
1113       ParseNode baseChild = (pn.getChild( "base" ));
1114       
1115       CreateObjectNode con = new CreateObjectNode(td, isglobal, disjointId);
1116       if( null != idChild && null != idChild.getFirstChild() ) {
1117         idChild = idChild.getFirstChild();
1118         //System.out.println( "\nThe object passed has this expression " + idChild.PPrint( 0, true ) );
1119         ExpressionNode en = parseExpression(cn, md, isStaticContext, idChild ); 
1120         //System.out.println( "\nThe object passed has this expression " + en.printNode( 0 ) );
1121         con.setSurroundingExpression( en );
1122       }
1123       else if( null != baseChild  && null != baseChild.getFirstChild()  ) {
1124         baseChild = baseChild.getFirstChild();
1125         //System.out.println( "\nThe object passed has this expression " + baseChild.PPrint( 0, true ) );
1126         ExpressionNode en = parseExpression(cn, md, isStaticContext, baseChild ); 
1127         //System.out.println( "\nThe object passed has this expression " + en.printNode( 0 ) );
1128         con.setSurroundingExpression( en );     
1129       }
1130       con.setNumLine(pn.getLine());
1131       for (int i = 0; i < args.size(); i++) {
1132         con.addArgument((ExpressionNode) args.get(i));
1133       }
1134       /* Could have flag set or tag added here */
1135       if (pn.getChild("flag_list") != null || pn.getChild("tag_list") != null) {
1136         FlagEffects fe = new FlagEffects(null);
1137         if (pn.getChild("flag_list") != null)
1138           parseFlagEffect(fe, pn.getChild("flag_list"));
1139
1140         if (pn.getChild("tag_list") != null)
1141           parseTagEffect(fe, pn.getChild("tag_list"));
1142         con.addFlagEffects(fe);
1143       }
1144
1145       return con;
1146     } else if (isNode(pn,"createobjectcls")) {
1147       TypeDescriptor td=parseTypeDescriptor(pn);
1148       innerCount++;
1149       ClassDescriptor cnnew=new ClassDescriptor(packageName,td.getSymbol()+"$"+innerCount, false);
1150       pushChainMaps();
1151       cnnew.setImports(mandatoryImports, multiimports);
1152       cnnew.setSuper(td.getSymbol());
1153       cnnew.setInline();
1154       // the inline anonymous class does not have modifiers, it cannot be static 
1155       // it is always implicit final
1156       cnnew.setModifiers(new Modifiers(Modifiers.FINAL));
1157       cnnew.setAsInnerClass();
1158       cnnew.setSurroundingClass(cn.getSymbol());
1159       cnnew.setSurrounding(cn);
1160       cn.addInnerClass(cnnew);
1161       // Note that if the inner class is declared in a static context, it does NOT 
1162       // have lexically enclosing instances.
1163       if((null!=md)&&(md.isStatic()||md.isStaticBlock())) {
1164         cnnew.setSurroundingBlock(md);
1165         cnnew.setInStaticContext();
1166       } else if (isStaticContext) {
1167         cnnew.setInStaticContext();
1168       }
1169       parseClassBody(cnnew, pn.getChild("decl").getChild("classbody"));
1170       boolean hasConstructor = false;
1171       for(Iterator method_it=cnnew.getMethods(); method_it.hasNext(); ) {
1172           MethodDescriptor cmd=(MethodDescriptor)method_it.next();
1173           hasConstructor |= cmd.isConstructor();
1174       }
1175       if(hasConstructor) {
1176           // anonymous class should not have explicit constructors
1177           throw new Error("Error! Anonymous class " + cnnew.getSymbol() + " in " + cn.getSymbol() + " has explicit constructors!");
1178       } else if(!cnnew.isEnum()) {
1179           // add a default constructor for this class
1180           MethodDescriptor cmd = new MethodDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL),cnnew.getSymbol(), false);
1181           BlockNode bn=new BlockNode();
1182           state.addTreeCode(cmd,bn);
1183           cmd.setDefaultConstructor();
1184           cnnew.addMethod(cmd);
1185       }
1186       TypeDescriptor tdnew=state.getTypeDescriptor(cnnew.getSymbol());
1187
1188       Vector args=parseArgumentList(cn, md, isStaticContext, pn);
1189       ParseNode idChild = pn.getChild( "id" );
1190       ParseNode baseChild = pn.getChild( "base" );
1191       //System.out.println("\n to print idchild and basechild for ");
1192       /*if( null != idChild )
1193         System.out.println( "\n trying to create an inner class and the id child passed is "  + idChild.PPrint( 0, true ) );
1194       if( null != baseChild )
1195         System.out.println( "\n trying to create an inner class and the base child passed is "  + baseChild.PPrint( 0, true ) );*/
1196       CreateObjectNode con=new CreateObjectNode(tdnew, false, null);
1197       con.setNumLine(pn.getLine());
1198       for(int i=0; i<args.size(); i++) {
1199         con.addArgument((ExpressionNode)args.get(i));
1200       }
1201       popChainMaps();
1202
1203       addClass2State(cnnew);
1204
1205       return con;
1206     } else if (isNode(pn,"createarray")) {
1207       //System.out.println(pn.PPrint(3,true));
1208       boolean isglobal=pn.getChild("global")!=null||
1209                         pn.getChild("scratch")!=null;
1210       String disjointId=null;
1211       if( pn.getChild("disjoint") != null) {
1212         disjointId = pn.getChild("disjoint").getTerminal();
1213       }
1214       TypeDescriptor td=parseTypeDescriptor(pn);
1215       Vector args=parseDimExprs(cn, md, isStaticContext, pn);
1216       int num=0;
1217       if (pn.getChild("dims_opt").getLiteral()!=null)
1218         num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
1219       for(int i=0; i<(args.size()+num); i++)
1220         td=td.makeArray(state);
1221       CreateObjectNode con=new CreateObjectNode(td, isglobal, disjointId);
1222       con.setNumLine(pn.getLine());
1223       for(int i=0; i<args.size(); i++) {
1224         con.addArgument((ExpressionNode)args.get(i));
1225       }
1226       return con;
1227     }
1228     if (isNode(pn,"createarray2")) {
1229       TypeDescriptor td=parseTypeDescriptor(pn);
1230       int num=0;
1231       if (pn.getChild("dims_opt").getLiteral()!=null)
1232         num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
1233       for(int i=0; i<num; i++)
1234         td=td.makeArray(state);
1235       CreateObjectNode con=new CreateObjectNode(td, false, null);
1236       con.setNumLine(pn.getLine());
1237       ParseNode ipn = pn.getChild("initializer");
1238       Vector initializers=parseVariableInitializerList(cn, md, isStaticContext, ipn);
1239       ArrayInitializerNode ain = new ArrayInitializerNode(initializers);
1240       ain.setNumLine(pn.getLine());
1241       con.addArrayInitializer(ain);
1242       return con;
1243     } else if (isNode(pn,"name")) {
1244       NameDescriptor nd=parseName(pn);
1245       NameNode nn=new NameNode(nd);
1246       nn.setNumLine(pn.getLine());
1247       return nn;
1248     } else if (isNode(pn,"this")) {
1249       NameDescriptor nd=new NameDescriptor("this");
1250       NameNode nn=new NameNode(nd);
1251       nn.setNumLine(pn.getLine());
1252       return nn;
1253     } else if (isNode(pn,"parentclass")) {
1254       NameDescriptor nd=new NameDescriptor(pn.getChild("name").getFirstChild().getFirstChild().getTerminal());
1255       NameNode nn=new NameNode(nd);
1256       nn.setNumLine(pn.getLine());
1257         //because inner classes pass right thru......
1258       FieldAccessNode fan=new FieldAccessNode(nn,"this");
1259       fan.setNumLine(pn.getLine());
1260       return fan;
1261     } else if (isNode(pn,"isavailable")) {
1262       NameDescriptor nd=new NameDescriptor(pn.getTerminal());
1263       NameNode nn=new NameNode(nd);
1264       nn.setNumLine(pn.getLine());
1265       return new OpNode(nn,null,new Operation(Operation.ISAVAILABLE));
1266     } else if (isNode(pn,"methodinvoke1")) {
1267       NameDescriptor nd=parseName(pn.getChild("name"));
1268       Vector args=parseArgumentList(cn, md, isStaticContext, pn);
1269       MethodInvokeNode min=new MethodInvokeNode(nd);
1270       min.setNumLine(pn.getLine());
1271       for(int i=0; i<args.size(); i++) {
1272         min.addArgument((ExpressionNode)args.get(i));
1273       }
1274       return min;
1275     } else if (isNode(pn,"methodinvoke2")) {
1276       String methodid=pn.getChild("id").getTerminal();
1277       ExpressionNode exp=parseExpression(cn, md, isStaticContext, pn.getChild("base").getFirstChild());
1278       Vector args=parseArgumentList(cn, md, isStaticContext, pn);
1279       MethodInvokeNode min=new MethodInvokeNode(methodid,exp);
1280       min.setNumLine(pn.getLine());
1281       for(int i=0; i<args.size(); i++) {
1282         min.addArgument((ExpressionNode)args.get(i));
1283       }
1284       return min;
1285     } else if (isNode(pn,"fieldaccess")) {
1286       ExpressionNode en=parseExpression(cn, md, isStaticContext, pn.getChild("base").getFirstChild());
1287       String fieldname=pn.getChild("field").getTerminal();
1288
1289       FieldAccessNode fan=new FieldAccessNode(en,fieldname);
1290       fan.setNumLine(pn.getLine());
1291       return fan;
1292     } else if (isNode(pn,"superfieldaccess")) {
1293         ExpressionNode en=new NameNode(new NameDescriptor("super"));
1294         String fieldname=pn.getChild("field").getTerminal();
1295
1296         FieldAccessNode fan=new FieldAccessNode(en,fieldname);
1297         fan.setNumLine(pn.getLine());
1298         return fan;
1299     } else if (isNode(pn,"supernamefieldaccess")) {
1300         ExpressionNode en=parseExpression(cn, md, isStaticContext, pn.getChild("base").getFirstChild());
1301         ExpressionNode exp = new FieldAccessNode(en, "super");
1302         exp.setNumLine(pn.getLine());
1303         String fieldname=pn.getChild("field").getTerminal();
1304
1305         FieldAccessNode fan=new FieldAccessNode(exp,fieldname);
1306         fan.setNumLine(pn.getLine());
1307         return fan;
1308     } else if (isNode(pn,"arrayaccess")) {
1309       ExpressionNode en=parseExpression(cn, md, isStaticContext, pn.getChild("base").getFirstChild());
1310       ExpressionNode index=parseExpression(cn, md, isStaticContext, pn.getChild("index").getFirstChild());
1311       ArrayAccessNode aan=new ArrayAccessNode(en,index);
1312       aan.setNumLine(pn.getLine());
1313       return aan;
1314     } else if (isNode(pn,"cast1")) {
1315       try {
1316         CastNode castn=new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(cn, md, isStaticContext, pn.getChild("exp").getFirstChild()));
1317         castn.setNumLine(pn.getLine());
1318         return castn;
1319       } catch (Exception e) {
1320         System.out.println(pn.PPrint(1,true));
1321         e.printStackTrace();
1322         throw new Error();
1323       }
1324     } else if (isNode(pn,"cast2")) {
1325       CastNode castn=new CastNode(parseExpression(cn, md, isStaticContext, pn.getChild("type").getFirstChild()),parseExpression(cn, md, isStaticContext, pn.getChild("exp").getFirstChild()));
1326       castn.setNumLine(pn.getLine());
1327       return castn;
1328     } else if (isNode(pn, "getoffset")) {
1329       TypeDescriptor td=parseTypeDescriptor(pn);
1330       String fieldname = pn.getChild("field").getTerminal();
1331       //System.out.println("Checking the values of: "+ " td.toString()= " + td.toString()+ "  fieldname= " + fieldname);
1332       return new OffsetNode(td, fieldname);
1333     } else if (isNode(pn, "tert")) {
1334
1335       TertiaryNode tn=new TertiaryNode(parseExpression(cn, md, isStaticContext, pn.getChild("cond").getFirstChild()),
1336                                        parseExpression(cn, md, isStaticContext, pn.getChild("trueexpr").getFirstChild()),
1337                                        parseExpression(cn, md, isStaticContext, pn.getChild("falseexpr").getFirstChild()) );
1338       tn.setNumLine(pn.getLine());
1339
1340       return tn;
1341     } else if (isNode(pn, "instanceof")) {
1342       ExpressionNode exp=parseExpression(cn, md, isStaticContext, pn.getChild("exp").getFirstChild());
1343       TypeDescriptor t=parseTypeDescriptor(pn);
1344       InstanceOfNode ion=new InstanceOfNode(exp,t);
1345       ion.setNumLine(pn.getLine());
1346       return ion;
1347     } else if (isNode(pn, "array_initializer")) {
1348       Vector initializers=parseVariableInitializerList(cn, md, isStaticContext, pn);
1349       return new ArrayInitializerNode(initializers);
1350     } else if (isNode(pn, "class_type")) {
1351       TypeDescriptor td=parseTypeDescriptor(pn);
1352       ClassTypeNode ctn=new ClassTypeNode(td);
1353       ctn.setNumLine(pn.getLine());
1354       return ctn;
1355     } else if (isNode(pn, "empty")) {
1356       return null;
1357     } else {
1358       System.out.println("---------------------");
1359       System.out.println(pn.PPrint(3,true));
1360       throw new Error();
1361     }
1362   }
1363
1364   private Vector parseDimExprs(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1365     Vector arglist=new Vector();
1366     ParseNode an=pn.getChild("dim_exprs");
1367     if (an==null)       /* No argument list */
1368       return arglist;
1369     ParseNodeVector anv=an.getChildren();
1370     for(int i=0; i<anv.size(); i++) {
1371       arglist.add(parseExpression(cn, md, isStaticContext, anv.elementAt(i)));
1372     }
1373     return arglist;
1374   }
1375
1376   private Vector parseArgumentList(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1377     Vector arglist=new Vector();
1378     ParseNode an=pn.getChild("argument_list");
1379     if (an==null)       /* No argument list */
1380       return arglist;
1381     ParseNodeVector anv=an.getChildren();
1382     for(int i=0; i<anv.size(); i++) {
1383       arglist.add(parseExpression(cn, md, isStaticContext, anv.elementAt(i)));
1384     }
1385     return arglist;
1386   }
1387
1388   private Vector[] parseConsArgumentList(ParseNode pn) {
1389     Vector arglist=new Vector();
1390     Vector varlist=new Vector();
1391     ParseNode an=pn.getChild("cons_argument_list");
1392     if (an==null)       /* No argument list */
1393       return new Vector[] {varlist, arglist};
1394     ParseNodeVector anv=an.getChildren();
1395     for(int i=0; i<anv.size(); i++) {
1396       ParseNode cpn=anv.elementAt(i);
1397       ParseNode var=cpn.getChild("var");
1398       ParseNode exp=cpn.getChild("exp").getFirstChild();
1399       varlist.add(var.getTerminal());
1400       arglist.add(parseExpression(null, null, false, exp));
1401     }
1402     return new Vector[] {varlist, arglist};
1403   }
1404
1405   private Vector parseVariableInitializerList(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1406     Vector varInitList=new Vector();
1407     ParseNode vin=pn.getChild("var_init_list");
1408     if (vin==null)       /* No argument list */
1409       return varInitList;
1410     ParseNodeVector vinv=vin.getChildren();
1411     for(int i=0; i<vinv.size(); i++) {
1412       varInitList.add(parseExpression(cn, md, isStaticContext, vinv.elementAt(i)));
1413     }
1414     return varInitList;
1415   }
1416
1417   private ExpressionNode parseAssignmentExpression(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1418     AssignOperation ao=new AssignOperation(pn.getChild("op").getTerminal());
1419     ParseNodeVector pnv=pn.getChild("args").getChildren();
1420
1421     AssignmentNode an=new AssignmentNode(parseExpression(cn, md, isStaticContext, pnv.elementAt(0)),parseExpression(cn, md, isStaticContext, pnv.elementAt(1)),ao);
1422     an.setNumLine(pn.getLine());
1423     return an;
1424   }
1425
1426
1427   private void parseMethodDecl(ClassDescriptor cn, ParseNode pn) {
1428     ParseNode headern=pn.getChild("method_header");
1429     ParseNode bodyn=pn.getChild("body");
1430     MethodDescriptor md=parseMethodHeader(headern);
1431     try {
1432       BlockNode bn=parseBlock(cn, md, md.isStatic()||md.isStaticBlock(), bodyn);
1433       bn.setNumLine(pn.getLine()); // assume that method header is located at the beginning of method body
1434       cn.addMethod(md);
1435       state.addTreeCode(md,bn);
1436
1437       // this is a hack for investigating new language features
1438       // at the AST level, someday should evolve into a nice compiler
1439       // option *wink*
1440       //if( cn.getSymbol().equals( ***put a class in here like:     "Test" ) &&
1441       //    md.getSymbol().equals( ***put your method in here like: "main" )
1442       //) {
1443       //  bn.setStyle( BlockNode.NORMAL );
1444       //  System.out.println( bn.printNode( 0 ) );
1445       //}
1446
1447     } catch (Exception e) {
1448       System.out.println("Error with method:"+md.getSymbol());
1449       e.printStackTrace();
1450       throw new Error();
1451     } catch (Error e) {
1452       System.out.println("Error with method:"+md.getSymbol());
1453       e.printStackTrace();
1454       throw new Error();
1455     }
1456   }
1457
1458   private void parseConstructorDecl(ClassDescriptor cn, ParseNode pn) {
1459     ParseNode mn=pn.getChild("modifiers");
1460     Modifiers m=parseModifiersList(mn);
1461     ParseNode cdecl=pn.getChild("constructor_declarator");
1462     boolean isglobal=cdecl.getChild("global")!=null;
1463     String name=resolveName(cn.getSymbol());
1464     MethodDescriptor md=new MethodDescriptor(m, name, isglobal);
1465     ParseNode paramnode=cdecl.getChild("parameters");
1466     parseParameterList(md,paramnode);
1467     ParseNode bodyn0=pn.getChild("body");
1468     ParseNode bodyn=bodyn0.getChild("constructor_body");
1469     cn.addMethod(md);
1470     BlockNode bn=null;
1471     if (bodyn!=null&&bodyn.getChild("block_statement_list")!=null)
1472       bn=parseBlock(cn, md, md.isStatic()||md.isStaticBlock(), bodyn);
1473     else
1474       bn=new BlockNode();
1475     if (bodyn!=null&&bodyn.getChild("superinvoke")!=null) {
1476       ParseNode sin=bodyn.getChild("superinvoke");
1477       NameDescriptor nd=new NameDescriptor("super");
1478       Vector args=parseArgumentList(cn, md, true, sin);
1479       MethodInvokeNode min=new MethodInvokeNode(nd);
1480       min.setNumLine(sin.getLine());
1481       for(int i=0; i<args.size(); i++) {
1482         min.addArgument((ExpressionNode)args.get(i));
1483       }
1484       BlockExpressionNode ben=new BlockExpressionNode(min);
1485       bn.addFirstBlockStatement(ben);
1486
1487     } else if (bodyn!=null&&bodyn.getChild("explconstrinv")!=null) {
1488       ParseNode eci=bodyn.getChild("explconstrinv");
1489       NameDescriptor nd=new NameDescriptor(cn.getSymbol());
1490       Vector args=parseArgumentList(cn, md, true, eci);
1491       MethodInvokeNode min=new MethodInvokeNode(nd);
1492       min.setNumLine(eci.getLine());
1493       for(int i=0; i<args.size(); i++) {
1494         min.addArgument((ExpressionNode)args.get(i));
1495       }
1496       BlockExpressionNode ben=new BlockExpressionNode(min);
1497       ben.setNumLine(eci.getLine());
1498       bn.addFirstBlockStatement(ben);
1499     }
1500     state.addTreeCode(md,bn);
1501   }
1502
1503   private void parseStaticBlockDecl(ClassDescriptor cn, ParseNode pn) {
1504     // Each class maintains one MethodDecscriptor which combines all its
1505     // static blocks in their declaration order
1506     boolean isfirst = false;
1507     MethodDescriptor md = (MethodDescriptor)cn.getMethodTable().getFromSameScope("staticblocks");
1508     if(md == null) {
1509       // the first static block for this class
1510       Modifiers m_i=new Modifiers();
1511       m_i.addModifier(Modifiers.STATIC);
1512       md = new MethodDescriptor(m_i, "staticblocks", false);
1513       md.setAsStaticBlock();
1514       isfirst = true;
1515     }
1516     ParseNode bodyn=pn.getChild("body");
1517     if(isfirst) {
1518       cn.addMethod(md);
1519     }
1520     cn.incStaticBlocks();
1521     BlockNode bn=null;
1522     if (bodyn!=null&&bodyn.getChild("block_statement_list")!=null)
1523       bn=parseBlock(cn, md, true, bodyn);
1524     else
1525       bn=new BlockNode();
1526     if(isfirst) {
1527       state.addTreeCode(md,bn);
1528     } else {
1529       BlockNode obn = state.getMethodBody(md);
1530       for(int i = 0; i < bn.size(); i++) {
1531         BlockStatementNode bsn = bn.get(i);
1532         obn.addBlockStatement(bsn);
1533       }
1534       state.addTreeCode(md, obn);
1535       bn = null;
1536     }
1537   }
1538
1539   public BlockNode parseBlock(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1540     this.m_taskexitnum = 0;
1541     if (pn==null||isEmpty(pn.getTerminal()))
1542       return new BlockNode();
1543     ParseNode bsn=pn.getChild("block_statement_list");
1544     return parseBlockHelper(cn, md, isStaticContext, bsn);
1545   }
1546
1547   private BlockNode parseBlockHelper(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1548     ParseNodeVector pnv=pn.getChildren();
1549     BlockNode bn=new BlockNode();
1550     for(int i=0; i<pnv.size(); i++) {
1551       Vector bsv=parseBlockStatement(cn, md, isStaticContext, pnv.elementAt(i));
1552       for(int j=0; j<bsv.size(); j++) {
1553         bn.addBlockStatement((BlockStatementNode)bsv.get(j));
1554       }
1555     }
1556     return bn;
1557   }
1558
1559   public BlockNode parseSingleBlock(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn, String label){
1560     BlockNode bn=new BlockNode();
1561     Vector bsv=parseBlockStatement(cn, md, isStaticContext, pn,label);
1562     for(int j=0; j<bsv.size(); j++) {
1563       bn.addBlockStatement((BlockStatementNode)bsv.get(j));
1564     }
1565     bn.setStyle(BlockNode.NOBRACES);
1566     return bn;
1567   }
1568   
1569   public BlockNode parseSingleBlock(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn) {
1570     return parseSingleBlock(cn, md, isStaticContext, pn, null);
1571   }
1572
1573   public Vector parseSESEBlock(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, Vector parentbs, ParseNode pn) {
1574     ParseNodeVector pnv=pn.getChildren();
1575     Vector bv=new Vector();
1576     for(int i=0; i<pnv.size(); i++) {
1577       bv.addAll(parseBlockStatement(cn, md, isStaticContext, pnv.elementAt(i)));
1578     }
1579     return bv;
1580   }
1581   
1582   public Vector parseBlockStatement(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn){
1583     return parseBlockStatement(cn, md, isStaticContext, pn,null);
1584   }
1585
1586   public Vector parseBlockStatement(ClassDescriptor cn, MethodDescriptor md, boolean isStaticContext, ParseNode pn, String label) {
1587     Vector blockstatements=new Vector();
1588     if (isNode(pn,"tag_declaration")) {
1589       String name=pn.getChild("single").getTerminal();
1590       String type=pn.getChild("type").getTerminal();
1591
1592       TagDeclarationNode tdn=new TagDeclarationNode(name, type);
1593       tdn.setNumLine(pn.getLine());
1594
1595       blockstatements.add(tdn);
1596     } else if (isNode(pn,"local_variable_declaration")) {
1597
1598       TypeDescriptor t=parseTypeDescriptor(pn);
1599       ParseNode vn=pn.getChild("variable_declarators_list");
1600       ParseNodeVector pnv=vn.getChildren();
1601       for(int i=0; i<pnv.size(); i++) {
1602         ParseNode vardecl=pnv.elementAt(i);
1603
1604
1605         ParseNode tmp=vardecl;
1606         TypeDescriptor arrayt=t;
1607
1608         while (tmp.getChild("single")==null) {
1609           arrayt=arrayt.makeArray(state);
1610           tmp=tmp.getChild("array");
1611         }
1612         String identifier=tmp.getChild("single").getTerminal();
1613
1614         ParseNode epn=vardecl.getChild("initializer");
1615
1616
1617         ExpressionNode en=null;
1618         if (epn!=null)
1619           en=parseExpression(cn, md, isStaticContext, epn.getFirstChild());
1620
1621         DeclarationNode dn=new DeclarationNode(new VarDescriptor(arrayt, identifier),en);
1622         dn.setNumLine(tmp.getLine());
1623         
1624         ParseNode mn=pn.getChild("modifiers");
1625         if(mn!=null) {
1626           // here, modifers parse node has the list of annotations
1627           Modifiers m=parseModifiersList(mn);
1628           assignAnnotationsToType(m, arrayt);
1629         }
1630
1631         blockstatements.add(dn);
1632       }
1633     } else if (isNode(pn,"nop")) {
1634       /* Do Nothing */
1635     } else if (isNode(pn,"expression")) {
1636       BlockExpressionNode ben=new BlockExpressionNode(parseExpression(cn, md, isStaticContext, pn.getFirstChild()));
1637       ben.setNumLine(pn.getLine());
1638       blockstatements.add(ben);
1639     } else if (isNode(pn,"ifstatement")) {
1640       IfStatementNode isn=new IfStatementNode(parseExpression(cn, md, isStaticContext, pn.getChild("condition").getFirstChild()),
1641                                               parseSingleBlock(cn, md, isStaticContext, pn.getChild("statement").getFirstChild()),
1642                                               pn.getChild("else_statement")!=null?parseSingleBlock(cn, md, isStaticContext, pn.getChild("else_statement").getFirstChild()):null);
1643       isn.setNumLine(pn.getLine());
1644
1645       blockstatements.add(isn);
1646     } else if (isNode(pn,"switch_statement")) {
1647       // TODO add version for normal Java later
1648       SwitchStatementNode ssn=new SwitchStatementNode(parseExpression(cn, md, isStaticContext, pn.getChild("condition").getFirstChild()),
1649                                                       parseSingleBlock(cn, md, isStaticContext, pn.getChild("statement").getFirstChild()));
1650       ssn.setNumLine(pn.getLine());
1651       blockstatements.add(ssn);
1652     } else if (isNode(pn,"switch_block_list")) {
1653       // TODO add version for normal Java later
1654       ParseNodeVector pnv=pn.getChildren();
1655       for(int i=0; i<pnv.size(); i++) {
1656         ParseNode sblockdecl=pnv.elementAt(i);
1657
1658         if(isNode(sblockdecl, "switch_block")) {
1659           ParseNode lpn=sblockdecl.getChild("switch_labels").getChild("switch_label_list");
1660           ParseNodeVector labelv=lpn.getChildren();
1661           Vector<SwitchLabelNode> slv = new Vector<SwitchLabelNode>();
1662           for(int j=0; j<labelv.size(); j++) {
1663             ParseNode labeldecl=labelv.elementAt(j);
1664             if(isNode(labeldecl, "switch_label")) {
1665               SwitchLabelNode sln=new SwitchLabelNode(parseExpression(cn, md, isStaticContext, labeldecl.getChild("constant_expression").getFirstChild()), false);
1666               sln.setNumLine(labeldecl.getLine());
1667               slv.addElement(sln);
1668             } else if(isNode(labeldecl, "default_switch_label")) {
1669               SwitchLabelNode sln=new SwitchLabelNode(null, true);
1670               sln.setNumLine(labeldecl.getLine());
1671               slv.addElement(sln);
1672             }
1673           }
1674
1675           SwitchBlockNode sbn=new SwitchBlockNode(slv,
1676                                                   parseSingleBlock(cn, md, isStaticContext, sblockdecl.getChild("switch_statements").getFirstChild()));
1677           sbn.setNumLine(sblockdecl.getLine());
1678
1679           blockstatements.add(sbn);
1680
1681         }
1682       }
1683     } else if (isNode(pn, "trycatchstatement")) {
1684       // TODO add version for normal Java later
1685       // Do not fully support exceptions now. Only make sure that if there are no
1686       // exceptions thrown, the execution is right
1687       ParseNode tpn = pn.getChild("tryblock").getFirstChild();
1688       BlockNode bn=parseBlockHelper(cn, md, isStaticContext, tpn);
1689       blockstatements.add(new SubBlockNode(bn));
1690
1691       ParseNode fbk = pn.getChild("finallyblock");
1692       if(fbk != null) {
1693         ParseNode fpn = fbk.getFirstChild();
1694         BlockNode fbn=parseBlockHelper(cn, md, isStaticContext, fpn);
1695         blockstatements.add(new SubBlockNode(fbn));
1696       }
1697     } else if (isNode(pn, "throwstatement")) {
1698       // TODO Simply return here
1699       //blockstatements.add(new ReturnNode());
1700     } else if (isNode(pn,"taskexit")) {
1701       Vector vfe=null;
1702       if (pn.getChild("flag_effects_list")!=null)
1703         vfe=parseFlags(pn.getChild("flag_effects_list"));
1704       Vector ccs=null;
1705       if (pn.getChild("cons_checks")!=null)
1706         ccs=parseChecks(pn.getChild("cons_checks"));
1707       TaskExitNode ten=new TaskExitNode(vfe, ccs, this.m_taskexitnum++);
1708       ten.setNumLine(pn.getLine());
1709       blockstatements.add(ten);
1710     } else if (isNode(pn,"atomic")) {
1711       BlockNode bn=parseBlockHelper(cn, md, isStaticContext, pn);
1712       AtomicNode an=new AtomicNode(bn);
1713       an.setNumLine(pn.getLine());
1714       blockstatements.add(an);
1715     } else if (isNode(pn,"synchronized")) {
1716       BlockNode bn=parseBlockHelper(cn, md, isStaticContext, pn.getChild("block"));
1717       ExpressionNode en=parseExpression(cn, md, isStaticContext, pn.getChild("expr").getFirstChild());
1718       SynchronizedNode sn=new SynchronizedNode(en, bn);
1719       sn.setNumLine(pn.getLine());
1720       blockstatements.add(sn);
1721     } else if (isNode(pn,"return")) {
1722       if (isEmpty(pn.getTerminal()))
1723         blockstatements.add(new ReturnNode());
1724       else {
1725         ExpressionNode en=parseExpression(cn, md, isStaticContext, pn.getFirstChild());
1726         ReturnNode rn=new ReturnNode(en);
1727         rn.setNumLine(pn.getLine());
1728         blockstatements.add(rn);
1729       }
1730     } else if (isNode(pn,"block_statement_list")) {
1731       BlockNode bn=parseBlockHelper(cn, md, isStaticContext, pn);
1732       blockstatements.add(new SubBlockNode(bn));
1733     } else if (isNode(pn,"empty")) {
1734       /* nop */
1735     } else if (isNode(pn,"statement_expression_list")) {
1736       ParseNodeVector pnv=pn.getChildren();
1737       BlockNode bn=new BlockNode();
1738       for(int i=0; i<pnv.size(); i++) {
1739         ExpressionNode en=parseExpression(cn, md, isStaticContext, pnv.elementAt(i));
1740         blockstatements.add(new BlockExpressionNode(en));
1741       }
1742       bn.setStyle(BlockNode.EXPRLIST);
1743     } else if (isNode(pn,"forstatement")) {
1744       BlockNode init=parseSingleBlock(cn, md, isStaticContext, pn.getChild("initializer").getFirstChild());
1745       BlockNode update=parseSingleBlock(cn, md, isStaticContext, pn.getChild("update").getFirstChild());
1746       ExpressionNode condition=parseExpression(cn, md, isStaticContext, pn.getChild("condition").getFirstChild());
1747       BlockNode body=parseSingleBlock(cn, md, isStaticContext, pn.getChild("statement").getFirstChild());
1748       if(condition == null) {
1749         // no condition clause, make a 'true' expression as the condition
1750         condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
1751       }
1752       LoopNode ln=new LoopNode(init,condition,update,body,label);
1753       ln.setNumLine(pn.getLine());
1754       blockstatements.add(ln);
1755     } else if (isNode(pn,"whilestatement")) {
1756       ExpressionNode condition=parseExpression(cn, md, isStaticContext, pn.getChild("condition").getFirstChild());
1757       BlockNode body=parseSingleBlock(cn, md, isStaticContext, pn.getChild("statement").getFirstChild());
1758       if(condition == null) {
1759         // no condition clause, make a 'true' expression as the condition
1760         condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
1761       }
1762       blockstatements.add(new LoopNode(condition,body,LoopNode.WHILELOOP,label));
1763     } else if (isNode(pn,"dowhilestatement")) {
1764       ExpressionNode condition=parseExpression(cn, md, isStaticContext, pn.getChild("condition").getFirstChild());
1765       BlockNode body=parseSingleBlock(cn, md, isStaticContext, pn.getChild("statement").getFirstChild());
1766       if(condition == null) {
1767         // no condition clause, make a 'true' expression as the condition
1768         condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
1769       }
1770       blockstatements.add(new LoopNode(condition,body,LoopNode.DOWHILELOOP,label));
1771     } else if (isNode(pn,"sese")) {
1772       ParseNode pnID=pn.getChild("identifier");
1773       String stID=null;
1774       if( pnID != null ) {
1775         stID=pnID.getFirstChild().getTerminal();
1776       }
1777       SESENode start=new SESENode(stID);
1778       start.setNumLine(pn.getLine());
1779       SESENode end  =new SESENode(stID);
1780       start.setEnd(end);
1781       end.setStart(start);
1782       blockstatements.add(start);
1783       blockstatements.addAll(parseSESEBlock(cn, md, isStaticContext, blockstatements,pn.getChild("body").getFirstChild()));
1784       blockstatements.add(end);
1785     } else if (isNode(pn,"continue")) {
1786       ContinueBreakNode cbn=new ContinueBreakNode(false);
1787       cbn.setNumLine(pn.getLine());
1788       blockstatements.add(cbn);
1789     } else if (isNode(pn,"break")) {
1790       ContinueBreakNode cbn=new ContinueBreakNode(true);
1791       cbn.setNumLine(pn.getLine());
1792       blockstatements.add(cbn);
1793       ParseNode idopt_pn=pn.getChild("identifier_opt");
1794       ParseNode name_pn=idopt_pn.getChild("name");
1795       // name_pn.getTerminal() gives you the label
1796
1797     } else if (isNode(pn,"genreach")) {
1798       String graphName = pn.getChild("graphName").getTerminal();
1799       blockstatements.add(new GenReachNode(graphName) );
1800
1801     } else if (isNode(pn,"gen_def_reach")) {
1802       String outputName = pn.getChild("outputName").getTerminal();
1803       blockstatements.add(new GenDefReachNode(outputName) );
1804
1805     } else if(isNode(pn,"labeledstatement")) {
1806       String labeledstatement = pn.getChild("name").getTerminal();
1807       BlockNode bn=parseSingleBlock(cn, md, isStaticContext, pn.getChild("statement").getFirstChild(),labeledstatement);
1808       blockstatements.add(new SubBlockNode(bn));
1809     } else {
1810       System.out.println("---------------");
1811       System.out.println(pn.PPrint(3,true));
1812       throw new Error();
1813     }
1814     return blockstatements;
1815   }
1816
1817   public MethodDescriptor parseMethodHeader(ParseNode pn) {
1818     ParseNode mn=pn.getChild("modifiers");
1819     Modifiers m=parseModifiersList(mn);
1820
1821     ParseNode tn=pn.getChild("returntype");
1822     TypeDescriptor returntype;
1823     if (tn!=null)
1824       returntype=parseTypeDescriptor(tn);
1825     else
1826       returntype=new TypeDescriptor(TypeDescriptor.VOID);
1827
1828     ParseNode pmd=pn.getChild("method_declarator");
1829     String name=pmd.getChild("name").getTerminal();
1830     MethodDescriptor md=new MethodDescriptor(m, returntype, name);
1831     md.setLineNum(pmd.getLine());
1832     
1833     ParseNode paramnode=pmd.getChild("parameters");
1834     parseParameterList(md,paramnode);
1835     return md;
1836   }
1837
1838   public void parseParameterList(MethodDescriptor md, ParseNode pn) {
1839     ParseNode paramlist=pn.getChild("formal_parameter_list");
1840     if (paramlist==null)
1841       return;
1842     ParseNodeVector pnv=paramlist.getChildren();
1843     for(int i=0; i<pnv.size(); i++) {
1844       ParseNode paramn=pnv.elementAt(i);
1845
1846       if (isNode(paramn, "tag_parameter")) {
1847         String paramname=paramn.getChild("single").getTerminal();
1848         TypeDescriptor type=new TypeDescriptor(TypeDescriptor.TAG);
1849         md.addTagParameter(type, paramname);
1850       } else  {
1851
1852         TypeDescriptor type=parseTypeDescriptor(paramn);
1853
1854         ParseNode tmp=paramn;
1855         while (tmp.getChild("single")==null) {
1856           type=type.makeArray(state);
1857           tmp=tmp.getChild("array");
1858         }
1859         String paramname=tmp.getChild("single").getTerminal();
1860
1861         md.addParameter(type, paramname);
1862         if(isNode(paramn, "annotation_parameter")) {
1863           ParseNode listnode=paramn.getChild("annotation_list");
1864           parseParameterAnnotation(listnode,type);
1865         }
1866
1867       }
1868     }
1869   }
1870
1871   public Modifiers parseModifiersList(ParseNode pn) {
1872     Modifiers m=new Modifiers();
1873     ParseNode modlist=pn.getChild("modifier_list");
1874     if (modlist!=null) {
1875       ParseNodeVector pnv=modlist.getChildren();
1876       for(int i=0; i<pnv.size(); i++) {
1877         ParseNode modn=pnv.elementAt(i);
1878         if (isNode(modn,"public"))
1879           m.addModifier(Modifiers.PUBLIC);
1880         else if (isNode(modn,"protected"))
1881           m.addModifier(Modifiers.PROTECTED);
1882         else if (isNode(modn,"private"))
1883           m.addModifier(Modifiers.PRIVATE);
1884         else if (isNode(modn,"static"))
1885           m.addModifier(Modifiers.STATIC);
1886         else if (isNode(modn,"final"))
1887           m.addModifier(Modifiers.FINAL);
1888         else if (isNode(modn,"native"))
1889           m.addModifier(Modifiers.NATIVE);
1890         else if (isNode(modn,"synchronized"))
1891           m.addModifier(Modifiers.SYNCHRONIZED);
1892         else if (isNode(modn,"atomic"))
1893           m.addModifier(Modifiers.ATOMIC);
1894         else if (isNode(modn,"abstract"))
1895           m.addModifier(Modifiers.ABSTRACT);
1896         else if (isNode(modn,"volatile"))
1897           m.addModifier(Modifiers.VOLATILE);
1898         else if (isNode(modn,"transient"))
1899           m.addModifier(Modifiers.TRANSIENT);
1900         else if(isNode(modn,"annotation_list"))
1901           parseAnnotationList(modn,m);
1902         else {
1903           throw new Error("Unrecognized Modifier:"+modn.getLabel());
1904         }
1905       }
1906     }
1907     return m;
1908   }
1909
1910   private void parseAnnotationList(ParseNode pn, Modifiers m) {
1911     ParseNodeVector pnv = pn.getChildren();
1912     for (int i = 0; i < pnv.size(); i++) {
1913       ParseNode body_list = pnv.elementAt(i);
1914       if (isNode(body_list, "annotation_body")) {
1915         ParseNode body_node = body_list.getFirstChild();
1916         if (isNode(body_node, "marker_annotation")) {
1917           m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal()));
1918         } else if (isNode(body_node, "single_annotation")) {
1919           m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal(),
1920                                                    body_node.getChild("element_value").getTerminal()));
1921         } else if (isNode(body_node, "normal_annotation")) {
1922           throw new Error("Annotation with multiple data members is not supported yet.");
1923         }
1924       }
1925     }
1926   }
1927
1928   private void parseParameterAnnotation(ParseNode pn,TypeDescriptor type) {
1929     ParseNodeVector pnv = pn.getChildren();
1930     for (int i = 0; i < pnv.size(); i++) {
1931       ParseNode body_list = pnv.elementAt(i);
1932       if (isNode(body_list, "annotation_body")) {
1933         ParseNode body_node = body_list.getFirstChild();
1934         if (isNode(body_node, "marker_annotation")) {
1935           type.addAnnotationMarker(new AnnotationDescriptor(body_node.getChild("name").getTerminal()));
1936         } else if (isNode(body_node, "single_annotation")) {
1937           type.addAnnotationMarker(new AnnotationDescriptor(body_node.getChild("name").getTerminal(),
1938                                                    body_node.getChild("element_value").getTerminal()));
1939         } else if (isNode(body_node, "normal_annotation")) {
1940           throw new Error("Annotation with multiple data members is not supported yet.");
1941         }
1942       }
1943     }
1944   }
1945
1946   private boolean isNode(ParseNode pn, String label) {
1947     if (pn.getLabel().equals(label))
1948       return true;
1949     else return false;
1950   }
1951
1952   private static boolean isEmpty(ParseNode pn) {
1953     if (pn.getLabel().equals("empty"))
1954       return true;
1955     else
1956       return false;
1957   }
1958
1959   private static boolean isEmpty(String s) {
1960     if (s.equals("empty"))
1961       return true;
1962     else
1963       return false;
1964   }
1965
1966   /** Throw an exception if something is unexpected */
1967   private void check(ParseNode pn, String label) {
1968     if (pn == null) {
1969       throw new Error(pn+ "IE: Expected '" + label + "', got null");
1970     }
1971     if (!pn.getLabel().equals(label)) {
1972       throw new Error(pn+ "IE: Expected '" + label + "', got '"+pn.getLabel()+"'");
1973     }
1974   }
1975 }