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