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