11 private boolean isRunningRecursiveInnerClass;
12 private int m_taskexitnum;
14 public BuildIR(State state) {
16 this.m_taskexitnum = 0;
17 this.isRunningRecursiveInnerClass = false;
20 public void buildtree(ParseNode pn, Set toanalyze, String sourcefile) {
21 parseFile(pn, toanalyze, sourcefile);
23 // numering the interfaces
25 Iterator it_classes = state.getClassSymbolTable().getValueSet().iterator();
26 while(it_classes.hasNext()) {
27 ClassDescriptor cd = (ClassDescriptor)it_classes.next();
28 if(cd.isInterface()) {
29 cd.setInterfaceId(if_num++);
34 //This is all single imports and a subset of the
35 //multi imports that have been resolved.
36 ChainHashMap mandatoryImports;
37 //maps class names in file to full name
38 //Note may map a name to an ERROR.
39 ChainHashMap multiimports;
42 String currsourcefile;
45 void pushChainMaps() {
46 mandatoryImports=mandatoryImports.makeChild();
47 multiimports=multiimports.makeChild();
51 mandatoryImports=mandatoryImports.getParent();
52 multiimports=multiimports.getParent();
55 /** Parse the classes in this file */
56 public void parseFile(ParseNode pn, Set toanalyze, String sourcefile) {
57 mandatoryImports = new ChainHashMap();
58 multiimports = new ChainHashMap();
59 currsourcefile=sourcefile;
63 //add java.lang as our default multi-import
64 this.addMultiImport(sourcefile, "java.lang", false);
67 ParseNode ipn = pn.getChild("imports").getChild("import_decls_list");
68 if ((ipn != null) && !state.MGC) {
69 ParseNodeVector pnv = ipn.getChildren();
70 for (int i = 0; i < pnv.size(); i++) {
71 ParseNode pnimport = pnv.elementAt(i);
72 NameDescriptor nd = parseName(pnimport.getChild("name"));
73 if (isNode(pnimport, "import_single")) {
74 if (!mandatoryImports.containsKey(nd.getIdentifier())) {
75 // map name to full name (includes package/directory
76 mandatoryImports.put(nd.getIdentifier(), nd.getPathFromRootToHere());
78 throw new Error("An ambiguous class "+ nd.getIdentifier() +" has been found. It is included for " +
79 ((String)mandatoryImports.get(nd.getIdentifier())) + " and " +
80 nd.getPathFromRootToHere());
83 addMultiImport(sourcefile, nd.getPathFromRootToHere(), false);
88 ParseNode ppn=pn.getChild("packages").getChild("package");
90 if ((ppn!=null) && !state.MGC){
91 NameDescriptor nd = parseClassName(ppn.getChild("name"));
92 packageName = nd.getPathFromRootToHere();
93 //Trick -> import the package directory as a multi-import and it'll
94 //automatically recognize files in the same directory.
95 addMultiImport(sourcefile, packageName, true);
98 ParseNode tpn=pn.getChild("type_declaration_list");
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 */
105 if (isNode(type_pn, "class_declaration")) {
106 ClassDescriptor cn = parseTypeDecl(type_pn);
107 parseInitializers(cn);
109 // for inner classes/enum
110 HashSet tovisit = new HashSet();
111 Iterator it_icds = cn.getInnerClasses();
112 while (it_icds.hasNext()) {
113 tovisit.add(it_icds.next());
116 while (!tovisit.isEmpty()) {
117 ClassDescriptor cd = (ClassDescriptor) tovisit.iterator().next();
119 parseInitializers(cd);
121 Iterator it_ics = cd.getInnerClasses();
122 while (it_ics.hasNext()) {
123 tovisit.add(it_ics.next());
126 } else if (isNode(type_pn, "task_declaration")) {
127 TaskDescriptor td = parseTaskDecl(type_pn);
128 if (toanalyze != null)
131 } else if (isNode(type_pn, "interface_declaration")) {
132 // TODO add version for normal Java later
133 ClassDescriptor cn = parseInterfaceDecl(type_pn, null);
134 } else if (isNode(type_pn, "enum_declaration")) {
135 // TODO add version for normal Java later
136 ClassDescriptor cn = parseEnumDecl(null, type_pn);
138 } else if(isNode(type_pn,"annotation_type_declaration")) {
139 ClassDescriptor cn=parseAnnotationTypeDecl(type_pn);
141 throw new Error(type_pn.getLabel());
148 //This kind of breaks away from tradition a little bit by doing the file checks here
149 // instead of in Semantic check, but doing it here is easier because we have a mapping early on
150 // if I wait until semantic check, I have to change ALL the type descriptors to match the new
151 // mapping and that's both ugly and tedious.
152 private void addMultiImport(String currentSource, String importPath, boolean isPackageDirectory) {
153 boolean found = false;
154 for (int j = 0; j < state.classpath.size(); j++) {
155 String path = (String) state.classpath.get(j);
156 File folder = new File(path, importPath.replace('.', '/'));
157 if (folder.exists()) {
159 for (String file : folder.list()) {
160 // if the file is of type *.java add to multiImport list.
161 if (file.lastIndexOf('.') != -1 && file.substring(file.lastIndexOf('.')).equalsIgnoreCase(".java")) {
162 String classname = file.substring(0, file.length() - 5);
163 // single imports have precedence over multi-imports
164 if (!mandatoryImports.containsKey(classname)) {
165 //package files have precedence over multi-imports.
166 if (multiimports.containsKey(classname) && !isPackageDirectory) {
167 // put error in for later, in case we try to import
168 multiimports.put(classname, new Error("Error: class " + classname + " is defined more than once in a multi-import in " + currentSource));
170 multiimports.put(classname, importPath + "." + classname);
179 throw new Error("Import package " + importPath + " in " + currentSource
180 + " cannot be resolved.");
184 public void parseInitializers(ClassDescriptor cn) {
185 Vector fv=cn.getFieldVec();
187 for(int i=0; i<fv.size(); i++) {
188 FieldDescriptor fd=(FieldDescriptor)fv.get(i);
189 if(fd.getExpressionNode()!=null) {
190 Iterator methodit = cn.getMethods();
191 while(methodit.hasNext()) {
192 MethodDescriptor currmd=(MethodDescriptor)methodit.next();
193 if(currmd.isConstructor()) {
194 BlockNode bn=state.getMethodBody(currmd);
195 NameNode nn=new NameNode(new NameDescriptor(fd.getSymbol()));
196 AssignmentNode an=new AssignmentNode(nn,fd.getExpressionNode(),new AssignOperation(1));
197 bn.addBlockStatementAt(new BlockExpressionNode(an), pos);
205 private ClassDescriptor parseEnumDecl(ClassDescriptor cn, ParseNode pn) {
206 String basename=pn.getChild("name").getTerminal();
207 String classname=(cn!=null)?cn.getClassName()+"$"+basename:basename;
208 ClassDescriptor ecd=new ClassDescriptor(cn!=null?cn.getPackage():null, classname, false);
211 if (packageName==null)
212 cn.getSingleImportMappings().put(basename,classname);
214 cn.getSingleImportMappings().put(basename,packageName+"."+classname);
218 ecd.setImports(mandatoryImports, multiimports);
221 ecd.setSurroundingClass(cn.getSymbol());
222 ecd.setSurrounding(cn);
225 if (!(ecd.getSymbol().equals(TypeUtil.ObjectClass)||
226 ecd.getSymbol().equals(TypeUtil.TagClass))) {
227 ecd.setSuper(TypeUtil.ObjectClass);
229 ecd.setModifiers(parseModifiersList(pn.getChild("modifiers")));
230 parseEnumBody(ecd, pn.getChild("enumbody"));
232 if (analyzeset != null)
234 ecd.setSourceFileName(currsourcefile);
241 private void parseEnumBody(ClassDescriptor cn, ParseNode pn) {
242 ParseNode decls=pn.getChild("enum_constants_list");
244 ParseNodeVector pnv=decls.getChildren();
245 for(int i=0; i<pnv.size(); i++) {
246 ParseNode decl=pnv.elementAt(i);
247 if (isNode(decl,"enum_constant")) {
248 parseEnumConstant(cn,decl);
249 } else throw new Error();
254 private void parseEnumConstant(ClassDescriptor cn, ParseNode pn) {
255 cn.addEnumConstant(pn.getChild("name").getTerminal());
258 private ClassDescriptor parseAnnotationTypeDecl(ParseNode pn) {
259 ClassDescriptor cn=new ClassDescriptor(pn.getChild("name").getTerminal(), true);
261 cn.setImports(mandatoryImports, multiimports);
262 ParseNode modifiers=pn.getChild("modifiers");
263 if(modifiers!=null) {
264 cn.setModifiers(parseModifiersList(modifiers));
266 parseAnnotationTypeBody(cn,pn.getChild("body"));
269 if (analyzeset != null)
271 cn.setSourceFileName(currsourcefile);
277 private void parseAnnotationTypeBody(ClassDescriptor cn, ParseNode pn) {
278 ParseNode list_node=pn.getChild("annotation_type_element_list");
279 if(list_node!=null) {
280 ParseNodeVector pnv = list_node.getChildren();
281 for (int i = 0; i < pnv.size(); i++) {
282 ParseNode element_node = pnv.elementAt(i);
283 if (isNode(element_node, "annotation_type_element_declaration")) {
284 ParseNodeVector elementProps = element_node.getChildren();
285 String identifier=null;
286 TypeDescriptor type=null;
287 Modifiers modifiers=new Modifiers();
288 for(int eidx=0; eidx<elementProps.size(); eidx++) {
289 ParseNode prop_node=elementProps.elementAt(eidx);
290 if(isNode(prop_node,"name")) {
291 identifier=prop_node.getTerminal();
292 } else if(isNode(prop_node,"type")) {
293 type=parseTypeDescriptor(prop_node);
294 } else if(isNode(prop_node,"modifier")) {
295 modifiers=parseModifiersList(prop_node);
298 cn.addField(new FieldDescriptor(modifiers, type, identifier, null, false));
304 public ClassDescriptor parseInterfaceDecl(ParseNode pn, ClassDescriptor outerclass) {
305 String basename=pn.getChild("name").getTerminal();
306 String classname=((outerclass==null)?"":(outerclass.getClassName()+"$"))+basename;
307 if (outerclass!=null) {
308 if (packageName==null)
309 outerclass.getSingleImportMappings().put(basename,classname);
311 outerclass.getSingleImportMappings().put(basename,packageName+"."+classname);
313 ClassDescriptor cn= new ClassDescriptor(packageName, classname, true);
316 cn.setImports(mandatoryImports, multiimports);
317 //cn.setAsInterface();
318 if (!isEmpty(pn.getChild("superIF").getTerminal())) {
319 /* parse inherited interface name */
320 ParseNode snlist=pn.getChild("superIF").getChild("extend_interface_list");
321 ParseNodeVector pnv=snlist.getChildren();
322 for(int i=0; i<pnv.size(); i++) {
323 ParseNode decl=pnv.elementAt(i);
324 if (isNode(decl,"type")) {
325 NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
326 cn.addSuperInterface(nd.toString());
327 } else if (isNode(decl, "interface_declaration")) {
328 ClassDescriptor innercn = parseInterfaceDecl(decl, cn);
329 } else throw new Error();
332 cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
333 parseInterfaceBody(cn, pn.getChild("interfacebody"));
334 if (analyzeset != null)
336 cn.setSourceFileName(currsourcefile);
342 private void parseInterfaceBody(ClassDescriptor cn, ParseNode pn) {
343 assert(cn.isInterface());
344 ParseNode decls=pn.getChild("interface_member_declaration_list");
346 ParseNodeVector pnv=decls.getChildren();
347 for(int i=0; i<pnv.size(); i++) {
348 ParseNode decl=pnv.elementAt(i);
349 if (isNode(decl,"constant")) {
350 parseInterfaceConstant(cn,decl);
351 } else if (isNode(decl,"method")) {
352 parseInterfaceMethod(cn,decl.getChild("method_declaration"));
353 } else if (isNode(decl, "interface_declaration")) {
354 parseInterfaceDecl(decl, cn);
355 } else throw new Error(decl.PPrint(2, true));
362 private void parseInterfaceConstant(ClassDescriptor cn, ParseNode pn) {
364 parseFieldDecl(cn,pn.getChild("field_declaration"));
370 private void parseInterfaceMethod(ClassDescriptor cn, ParseNode pn) {
371 ParseNode headern=pn.getChild("header");
372 ParseNode bodyn=pn.getChild("body");
373 MethodDescriptor md=parseMethodHeader(headern.getChild("method_header"));
374 md.getModifiers().addModifier(Modifiers.PUBLIC);
375 md.getModifiers().addModifier(Modifiers.ABSTRACT);
377 BlockNode bn=parseBlock(bodyn);
379 state.addTreeCode(md,bn);
380 } catch (Exception e) {
381 System.out.println("Error with method:"+md.getSymbol());
385 System.out.println("Error with method:"+md.getSymbol());
391 public TaskDescriptor parseTaskDecl(ParseNode pn) {
392 TaskDescriptor td=new TaskDescriptor(pn.getChild("name").getTerminal());
393 ParseNode bodyn=pn.getChild("body");
394 BlockNode bn=parseBlock(bodyn);
395 parseParameterList(td, pn);
396 state.addTreeCode(td,bn);
397 if (pn.getChild("flag_effects_list")!=null)
398 td.addFlagEffects(parseFlags(pn.getChild("flag_effects_list")));
402 public Vector parseFlags(ParseNode pn) {
403 Vector vfe=new Vector();
404 ParseNodeVector pnv=pn.getChildren();
405 for(int i=0; i<pnv.size(); i++) {
406 ParseNode fn=pnv.elementAt(i);
407 FlagEffects fe=parseFlagEffects(fn);
413 public FlagEffects parseFlagEffects(ParseNode pn) {
414 if (isNode(pn,"flag_effect")) {
415 String flagname=pn.getChild("name").getTerminal();
416 FlagEffects fe=new FlagEffects(flagname);
417 if (pn.getChild("flag_list")!=null)
418 parseFlagEffect(fe, pn.getChild("flag_list"));
419 if (pn.getChild("tag_list")!=null)
420 parseTagEffect(fe, pn.getChild("tag_list"));
422 } else throw new Error();
425 public void parseTagEffect(FlagEffects fes, ParseNode pn) {
426 ParseNodeVector pnv=pn.getChildren();
427 for(int i=0; i<pnv.size(); i++) {
428 ParseNode pn2=pnv.elementAt(i);
430 if (isNode(pn2,"not")) {
432 pn2=pn2.getChild("name");
434 String name=pn2.getTerminal();
435 fes.addTagEffect(new TagEffect(name,status));
439 public void parseFlagEffect(FlagEffects fes, ParseNode pn) {
440 ParseNodeVector pnv=pn.getChildren();
441 for(int i=0; i<pnv.size(); i++) {
442 ParseNode pn2=pnv.elementAt(i);
444 if (isNode(pn2,"not")) {
446 pn2=pn2.getChild("name");
448 String name=pn2.getTerminal();
449 fes.addEffect(new FlagEffect(name,status));
453 public FlagExpressionNode parseFlagExpression(ParseNode pn) {
454 if (isNode(pn,"or")) {
455 ParseNodeVector pnv=pn.getChildren();
456 ParseNode left=pnv.elementAt(0);
457 ParseNode right=pnv.elementAt(1);
458 return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_OR));
459 } else if (isNode(pn,"and")) {
460 ParseNodeVector pnv=pn.getChildren();
461 ParseNode left=pnv.elementAt(0);
462 ParseNode right=pnv.elementAt(1);
463 return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_AND));
464 } else if (isNode(pn, "not")) {
465 ParseNodeVector pnv=pn.getChildren();
466 ParseNode left=pnv.elementAt(0);
467 return new FlagOpNode(parseFlagExpression(left), new Operation(Operation.LOGIC_NOT));
469 } else if (isNode(pn,"name")) {
470 return new FlagNode(pn.getTerminal());
476 public Vector parseChecks(ParseNode pn) {
477 Vector ccs=new Vector();
478 ParseNodeVector pnv=pn.getChildren();
479 for(int i=0; i<pnv.size(); i++) {
480 ParseNode fn=pnv.elementAt(i);
481 ConstraintCheck cc=parseConstraintCheck(fn);
487 public ConstraintCheck parseConstraintCheck(ParseNode pn) {
488 if (isNode(pn,"cons_check")) {
489 String specname=pn.getChild("name").getChild("identifier").getTerminal();
490 Vector[] args=parseConsArgumentList(pn);
491 ConstraintCheck cc=new ConstraintCheck(specname);
492 for(int i=0; i<args[0].size(); i++) {
493 cc.addVariable((String)args[0].get(i));
494 cc.addArgument((ExpressionNode)args[1].get(i));
497 } else throw new Error();
500 public void parseParameterList(TaskDescriptor td, ParseNode pn) {
503 ParseNode paramlist=pn.getChild("task_parameter_list");
506 ParseNodeVector pnv=paramlist.getChildren();
507 for(int i=0; i<pnv.size(); i++) {
508 ParseNode paramn=pnv.elementAt(i);
509 if(paramn.getChild("optional")!=null) {
511 paramn = paramn.getChild("optional").getFirstChild();
512 System.out.println("OPTIONAL FOUND!!!!!!!");
513 } else { optional = false;
514 System.out.println("NOT OPTIONAL"); }
516 TypeDescriptor type=parseTypeDescriptor(paramn);
518 String paramname=paramn.getChild("single").getTerminal();
519 FlagExpressionNode fen=null;
520 if (paramn.getChild("flag")!=null)
521 fen=parseFlagExpression(paramn.getChild("flag").getFirstChild());
523 ParseNode tagnode=paramn.getChild("tag");
525 TagExpressionList tel=null;
527 tel=parseTagExpressionList(tagnode);
530 td.addParameter(type,paramname,fen, tel, optional);
534 public TagExpressionList parseTagExpressionList(ParseNode pn) {
535 //BUG FIX: change pn.getChildren() to pn.getChild("tag_expression_list").getChildren()
536 //To test, feed in any input program that uses tags
537 ParseNodeVector pnv=pn.getChild("tag_expression_list").getChildren();
538 TagExpressionList tel=new TagExpressionList();
539 for(int i=0; i<pnv.size(); i++) {
540 ParseNode tn=pnv.elementAt(i);
541 String type=tn.getChild("type").getTerminal();
542 String name=tn.getChild("single").getTerminal();
543 tel.addTag(type, name);
548 public ClassDescriptor parseTypeDecl(ParseNode pn) {
549 ClassDescriptor cn=new ClassDescriptor(packageName, pn.getChild("name").getTerminal(), false);
551 cn.setImports(mandatoryImports, multiimports);
552 if (!isEmpty(pn.getChild("super").getTerminal())) {
553 /* parse superclass name */
554 ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
555 NameDescriptor nd=parseClassName(snn);
556 cn.setSuper(nd.toString());
558 if (!(cn.getSymbol().equals(TypeUtil.ObjectClass)||
559 cn.getSymbol().equals(TypeUtil.TagClass)))
560 cn.setSuper(TypeUtil.ObjectClass);
562 // check inherited interfaces
563 if (!isEmpty(pn.getChild("superIF").getTerminal())) {
564 /* parse inherited interface name */
565 ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list");
566 ParseNodeVector pnv=snlist.getChildren();
567 for(int i=0; i<pnv.size(); i++) {
568 ParseNode decl=pnv.elementAt(i);
569 if (isNode(decl,"type")) {
570 NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
571 cn.addSuperInterface(nd.toString());
575 cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
576 parseClassBody(cn, pn.getChild("classbody"));
578 boolean hasConstructor = false;
579 for(Iterator method_it=cn.getMethods(); method_it.hasNext(); ) {
580 MethodDescriptor md=(MethodDescriptor)method_it.next();
581 hasConstructor |= md.isConstructor();
583 if((!hasConstructor) && (!cn.isEnum())) {
584 // add a default constructor for this class
585 MethodDescriptor md = new MethodDescriptor(new Modifiers(Modifiers.PUBLIC),
586 cn.getSymbol(), false);
587 BlockNode bn=new BlockNode();
588 state.addTreeCode(md,bn);
589 md.setDefaultConstructor();
596 cn.setSourceFileName(currsourcefile);
600 if (analyzeset != null)
603 //create this$n representing a final reference to the next surrounding class. each inner class should have whatever inner class
604 //pointers the surrounding class has + a pointer to the surrounding class.
607 this.isRunningRecursiveInnerClass = true; //fOR dEBUGGING PURPOSES IN ORDER TO DUMP STRINGS WHILE IN THIS CODE PATH
608 addOuterClassReferences( cn, new Vector< String >() );
609 this.isRunningRecursiveInnerClass = false;
614 private void addOuterClassReferences( ClassDescriptor cn, Vector< String > runningClassNames )
616 //SYMBOLTABLE does not have a length or empty method, hence could not define a hasInnerClasses method in classDescriptor
617 Iterator nullCheckItr = cn.getInnerClasses();
618 if( false == nullCheckItr.hasNext() )
620 //logic: for each inner class present in current cn add this$runningIndex and recursively invoke this method on that inner class
622 //JAVA might be passing it by reference , so creating a copy for myself.
624 Vector tempCopy = new Vector< String >( runningClassNames );
625 tempCopy.add( cn.getClassName() );
627 Vector< ParseNode > vecParses = new Vector< ParseNode >();
630 for( Iterator itr = tempCopy.listIterator(); itr.hasNext() ; ++i ) {
631 ParseNode theNode = new ParseNode( "field_declaration" );
632 theNode.addChild("modifier").addChild( new ParseNode( "modifier_list" ) ).addChild("final");
633 ParseNode theTypeNode = new ParseNode("type");
634 ParseNode tempChildNode = theTypeNode.addChild("class").addChild( "name" );
635 //tempChildNode.addChild("base").addChild( new ParseNode("empty") );
636 tempChildNode.addChild("identifier").addChild ( ( String ) itr.next() );
637 theNode.addChild("type").addChild( theTypeNode );
638 ParseNode variableDeclaratorID = new ParseNode("single");
639 String theStr = "this$" + String.valueOf( i );
640 variableDeclaratorID.addChild( theStr );
641 ParseNode variableDeclarator = new ParseNode( "variable_declarator" );
642 variableDeclarator.addChild( variableDeclaratorID );
643 ParseNode variableDeclaratorList = new ParseNode("variable_declarators_list");
644 variableDeclaratorList.addChild( variableDeclarator );
645 theNode.addChild("variables").addChild( variableDeclaratorList );
648 vecParses.add( theNode );
653 for(Iterator it=cn.getInnerClasses(); it.hasNext(); ) {
654 ClassDescriptor icd=(ClassDescriptor)it.next();
655 for( Iterator vecParsesItr = vecParses.listIterator(); vecParsesItr.hasNext(); ) {
656 ParseNode theDummy = ( ParseNode ) vecParsesItr.next();
657 //System.out.println( ( theDummy ).PPrint( 0, true ) );
658 parseFieldDecl( icd, theDummy );
661 SymbolTable fieldTable = icd.getFieldTable();
662 System.out.println( fieldTable.toString() );
664 addOuterClassReferences( icd, tempCopy );
669 private void parseClassBody(ClassDescriptor cn, ParseNode pn) {
670 ParseNode decls=pn.getChild("class_body_declaration_list");
672 ParseNodeVector pnv=decls.getChildren();
673 for(int i=0; i<pnv.size(); i++) {
674 ParseNode decl=pnv.elementAt(i);
675 if (isNode(decl,"member")) {
676 parseClassMember(cn,decl);
677 } else if (isNode(decl,"constructor")) {
678 parseConstructorDecl(cn,decl.getChild("constructor_declaration"));
679 } else if (isNode(decl, "static_block")) {
680 parseStaticBlockDecl(cn, decl.getChild("static_block_declaration"));
681 } else if (isNode(decl,"block")) {
682 } else throw new Error();
687 private void parseClassMember(ClassDescriptor cn, ParseNode pn) {
688 ParseNode fieldnode=pn.getChild("field");
689 if (fieldnode!=null) {
690 //System.out.println( pn.PPrint( 0, true ) );
691 parseFieldDecl(cn,fieldnode.getChild("field_declaration"));
694 ParseNode methodnode=pn.getChild("method");
695 if (methodnode!=null) {
696 parseMethodDecl(cn,methodnode.getChild("method_declaration"));
699 ParseNode innerclassnode=pn.getChild("inner_class_declaration");
700 if (innerclassnode!=null) {
701 parseInnerClassDecl(cn,innerclassnode);
704 ParseNode innerinterfacenode=pn.getChild("interface_declaration");
705 if (innerinterfacenode!=null) {
706 parseInterfaceDecl(innerinterfacenode, cn);
710 ParseNode enumnode=pn.getChild("enum_declaration");
711 if (enumnode!=null) {
712 ClassDescriptor ecn=parseEnumDecl(cn,enumnode);
715 ParseNode flagnode=pn.getChild("flag");
716 if (flagnode!=null) {
717 parseFlagDecl(cn, flagnode.getChild("flag_declaration"));
720 // in case there are empty node
721 ParseNode emptynode=pn.getChild("empty");
722 if(emptynode != null) {
725 System.out.println("Unrecognized node:"+pn.PPrint(2,true));
729 //10/9/2011 changed this function to enable creation of default constructor for inner classes.
730 //the change was refactoring this function with the corresponding version for normal classes. sganapat
731 private ClassDescriptor parseInnerClassDecl(ClassDescriptor cn, ParseNode pn) {
732 String basename=pn.getChild("name").getTerminal();
733 String classname=cn.getClassName()+"$"+basename;
735 if (cn.getPackage()==null)
736 cn.getSingleImportMappings().put(basename,classname);
738 cn.getSingleImportMappings().put(basename,cn.getPackage()+"."+classname);
740 ClassDescriptor icn=new ClassDescriptor(cn.getPackage(), classname, false);
742 icn.setImports(mandatoryImports, multiimports);
743 icn.setAsInnerClass();
744 icn.setSurroundingClass(cn.getSymbol());
745 icn.setSurrounding(cn);
746 cn.addInnerClass(icn);
748 if (!isEmpty(pn.getChild("super").getTerminal())) {
749 /* parse superclass name */
750 ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
751 NameDescriptor nd=parseClassName(snn);
752 icn.setSuper(nd.toString());
754 if (!(icn.getSymbol().equals(TypeUtil.ObjectClass)||
755 icn.getSymbol().equals(TypeUtil.TagClass)))
756 icn.setSuper(TypeUtil.ObjectClass);
758 // check inherited interfaces
759 if (!isEmpty(pn.getChild("superIF").getTerminal())) {
760 /* parse inherited interface name */
761 ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list");
762 ParseNodeVector pnv=snlist.getChildren();
763 for(int i=0; i<pnv.size(); i++) {
764 ParseNode decl=pnv.elementAt(i);
765 if (isNode(decl,"type")) {
766 NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
767 icn.addSuperInterface(nd.toString());
771 icn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
773 parseClassBody(icn, pn.getChild("classbody"));
775 boolean hasConstructor = false;
776 for(Iterator method_it=icn.getMethods(); method_it.hasNext(); ) {
777 MethodDescriptor md=(MethodDescriptor)method_it.next();
778 hasConstructor |= md.isConstructor();
780 //sganapat adding change to allow proper construction of inner class objects
781 if((!hasConstructor) && (!icn.isEnum())) {
782 // add a default constructor for this class
783 MethodDescriptor md = new MethodDescriptor(new Modifiers(Modifiers.PUBLIC),
784 icn.getSymbol(), false);
785 BlockNode bn=new BlockNode();
786 state.addTreeCode(md,bn);
787 md.setDefaultConstructor();
792 if (analyzeset != null)
794 icn.setSourceFileName(currsourcefile);
800 private TypeDescriptor parseTypeDescriptor(ParseNode pn) {
801 ParseNode tn=pn.getChild("type");
802 String type_st=tn.getTerminal();
803 if(type_st.equals("byte")) {
804 return state.getTypeDescriptor(TypeDescriptor.BYTE);
805 } else if(type_st.equals("short")) {
806 return state.getTypeDescriptor(TypeDescriptor.SHORT);
807 } else if(type_st.equals("boolean")) {
808 return state.getTypeDescriptor(TypeDescriptor.BOOLEAN);
809 } else if(type_st.equals("int")) {
810 return state.getTypeDescriptor(TypeDescriptor.INT);
811 } else if(type_st.equals("long")) {
812 return state.getTypeDescriptor(TypeDescriptor.LONG);
813 } else if(type_st.equals("char")) {
814 return state.getTypeDescriptor(TypeDescriptor.CHAR);
815 } else if(type_st.equals("float")) {
816 return state.getTypeDescriptor(TypeDescriptor.FLOAT);
817 } else if(type_st.equals("double")) {
818 return state.getTypeDescriptor(TypeDescriptor.DOUBLE);
819 } else if(type_st.equals("class")) {
820 ParseNode nn=tn.getChild("class");
821 return state.getTypeDescriptor(parseClassName(nn.getChild("name")));
822 } else if(type_st.equals("array")) {
823 ParseNode nn=tn.getChild("array");
824 TypeDescriptor td=parseTypeDescriptor(nn.getChild("basetype"));
825 Integer numdims=(Integer)nn.getChild("dims").getLiteral();
826 for(int i=0; i<numdims.intValue(); i++)
827 td=td.makeArray(state);
830 System.out.println(pn.PPrint(2, true));
835 //Needed to separate out top level call since if a base exists,
836 //we do not want to apply our resolveName function (i.e. deal with imports)
837 //otherwise, if base == null, we do just want to resolve name.
838 private NameDescriptor parseClassName(ParseNode nn) {
839 ParseNode base=nn.getChild("base");
840 ParseNode id=nn.getChild("identifier");
841 String classname = id.getTerminal();
843 return new NameDescriptor(resolveName(classname));
845 return new NameDescriptor(parseClassNameRecursive(base.getChild("name")),classname);
848 private NameDescriptor parseClassNameRecursive(ParseNode nn) {
849 ParseNode base=nn.getChild("base");
850 ParseNode id=nn.getChild("identifier");
851 String classname = id.getTerminal();
853 return new NameDescriptor(classname);
855 return new NameDescriptor(parseClassNameRecursive(base.getChild("name")),classname);
858 //This will get the mapping of a terminal class name
859 //to a canonical classname (with imports/package locations in them)
860 private String resolveName(String terminal) {
862 if(mandatoryImports.containsKey(terminal)) {
863 return (String) mandatoryImports.get(terminal);
865 if(multiimports.containsKey(terminal)) {
867 Object o = multiimports.get(terminal);
868 if(o instanceof Error) {
869 throw new Error("Class " + terminal + " is ambiguous. Cause: more than 1 package import contain the same class.");
871 //At this point, if we found a unique class
872 //we can treat it as a single, mandatory import.
873 mandatoryImports.put(terminal, o);
882 //only function difference between this and parseName() is that this
883 //does not look for a import mapping.
884 private NameDescriptor parseName(ParseNode nn) {
885 ParseNode base=nn.getChild("base");
886 ParseNode id=nn.getChild("identifier");
888 return new NameDescriptor(id.getTerminal());
890 return new NameDescriptor(parseName(base.getChild("name")),id.getTerminal());
893 private void parseFlagDecl(ClassDescriptor cn,ParseNode pn) {
894 String name=pn.getChild("name").getTerminal();
895 FlagDescriptor flag=new FlagDescriptor(name);
896 if (pn.getChild("external")!=null)
901 private void parseFieldDecl(ClassDescriptor cn,ParseNode pn) {
902 ParseNode mn=pn.getChild("modifier");
903 Modifiers m=parseModifiersList(mn);
904 if(cn.isInterface()) {
905 // TODO add version for normal Java later
906 // Can only be PUBLIC or STATIC or FINAL
907 if((m.isAbstract()) || (m.isAtomic()) || (m.isNative())
908 || (m.isSynchronized())) {
909 throw new Error("Error: field in Interface " + cn.getSymbol() + "can only be PUBLIC or STATIC or FINAL");
911 m.addModifier(Modifiers.PUBLIC);
912 m.addModifier(Modifiers.STATIC);
913 m.addModifier(Modifiers.FINAL);
916 ParseNode tn=pn.getChild("type");
917 TypeDescriptor t=parseTypeDescriptor(tn);
918 ParseNode vn=pn.getChild("variables").getChild("variable_declarators_list");
919 ParseNodeVector pnv=vn.getChildren();
920 boolean isglobal=pn.getChild("global")!=null;
922 for(int i=0; i<pnv.size(); i++) {
923 ParseNode vardecl=pnv.elementAt(i);
924 ParseNode tmp=vardecl;
925 TypeDescriptor arrayt=t;
926 if( this.isRunningRecursiveInnerClass && false )
928 System.out.println( "the length of the list is " + String.valueOf( pnv.size() ) );
929 System.out.println( "\n the parse node is \n" + tmp.PPrint( 0, true ) );
931 while (tmp.getChild("single")==null) {
932 arrayt=arrayt.makeArray(state);
933 tmp=tmp.getChild("array");
935 String identifier=tmp.getChild("single").getTerminal();
936 ParseNode epn=vardecl.getChild("initializer");
938 ExpressionNode en=null;
940 en=parseExpression(epn.getFirstChild());
941 en.setNumLine(epn.getFirstChild().getLine());
943 // for static field, the initializer should be considered as a
945 boolean isfirst = false;
946 MethodDescriptor md = (MethodDescriptor)cn.getMethodTable().getFromSameScope("staticblocks");
948 // the first static block for this class
949 Modifiers m_i=new Modifiers();
950 m_i.addModifier(Modifiers.STATIC);
951 md = new MethodDescriptor(m_i, "staticblocks", false);
952 md.setAsStaticBlock();
958 cn.incStaticBlocks();
959 BlockNode bn=new BlockNode();
960 NameNode nn=new NameNode(new NameDescriptor(identifier));
961 nn.setNumLine(en.getNumLine());
962 AssignmentNode an=new AssignmentNode(nn,en,new AssignOperation(1));
963 an.setNumLine(pn.getLine());
964 bn.addBlockStatement(new BlockExpressionNode(an));
966 state.addTreeCode(md,bn);
968 BlockNode obn = state.getMethodBody(md);
969 for(int ii = 0; ii < bn.size(); ii++) {
970 BlockStatementNode bsn = bn.get(ii);
971 obn.addBlockStatement(bsn);
973 state.addTreeCode(md, obn);
980 cn.addField(new FieldDescriptor(m, arrayt, identifier, en, isglobal));
981 assignAnnotationsToType(m,arrayt);
985 private void assignAnnotationsToType(Modifiers modifiers, TypeDescriptor type) {
986 Vector<AnnotationDescriptor> annotations=modifiers.getAnnotations();
987 for(int i=0; i<annotations.size(); i++) {
988 // it only supports a marker annotation
989 AnnotationDescriptor an=annotations.elementAt(i);
990 type.addAnnotationMarker(an);
996 private ExpressionNode parseExpression(ParseNode pn) {
997 if (isNode(pn,"assignment"))
998 return parseAssignmentExpression(pn);
999 else if (isNode(pn,"logical_or")||isNode(pn,"logical_and")||
1000 isNode(pn,"bitwise_or")||isNode(pn,"bitwise_xor")||
1001 isNode(pn,"bitwise_and")||isNode(pn,"equal")||
1002 isNode(pn,"not_equal")||isNode(pn,"comp_lt")||
1003 isNode(pn,"comp_lte")||isNode(pn,"comp_gt")||
1004 isNode(pn,"comp_gte")||isNode(pn,"leftshift")||
1005 isNode(pn,"rightshift")||isNode(pn,"sub")||
1006 isNode(pn,"urightshift")||isNode(pn,"sub")||
1007 isNode(pn,"add")||isNode(pn,"mult")||
1008 isNode(pn,"div")||isNode(pn,"mod")) {
1009 ParseNodeVector pnv=pn.getChildren();
1010 ParseNode left=pnv.elementAt(0);
1011 ParseNode right=pnv.elementAt(1);
1012 Operation op=new Operation(pn.getLabel());
1013 OpNode on=new OpNode(parseExpression(left),parseExpression(right),op);
1014 on.setNumLine(pn.getLine());
1016 } else if (isNode(pn,"unaryplus")||
1017 isNode(pn,"unaryminus")||
1019 isNode(pn,"comp")) {
1020 ParseNode left=pn.getFirstChild();
1021 Operation op=new Operation(pn.getLabel());
1022 OpNode on=new OpNode(parseExpression(left),op);
1023 on.setNumLine(pn.getLine());
1025 } else if (isNode(pn,"postinc")||
1026 isNode(pn,"postdec")) {
1027 ParseNode left=pn.getFirstChild();
1028 AssignOperation op=new AssignOperation(pn.getLabel());
1029 AssignmentNode an=new AssignmentNode(parseExpression(left),null,op);
1030 an.setNumLine(pn.getLine());
1033 } else if (isNode(pn,"preinc")||
1034 isNode(pn,"predec")) {
1035 ParseNode left=pn.getFirstChild();
1036 AssignOperation op=isNode(pn,"preinc")?new AssignOperation(AssignOperation.PLUSEQ):new AssignOperation(AssignOperation.MINUSEQ);
1037 AssignmentNode an=new AssignmentNode(parseExpression(left),
1038 new LiteralNode("integer",new Integer(1)),op);
1039 an.setNumLine(pn.getLine());
1041 } else if (isNode(pn,"literal")) {
1042 String literaltype=pn.getTerminal();
1043 ParseNode literalnode=pn.getChild(literaltype);
1044 Object literal_obj=literalnode.getLiteral();
1045 LiteralNode ln=new LiteralNode(literaltype, literal_obj);
1046 ln.setNumLine(pn.getLine());
1048 } else if (isNode(pn, "createobject")) {
1049 TypeDescriptor td = parseTypeDescriptor(pn);
1051 Vector args = parseArgumentList(pn);
1052 boolean isglobal = pn.getChild("global") != null || pn.getChild("scratch") != null;
1053 String disjointId = null;
1054 if (pn.getChild("disjoint") != null) {
1055 disjointId = pn.getChild("disjoint").getTerminal();
1057 CreateObjectNode con = new CreateObjectNode(td, isglobal, disjointId);
1058 con.setNumLine(pn.getLine());
1059 for (int i = 0; i < args.size(); i++) {
1060 con.addArgument((ExpressionNode) args.get(i));
1062 /* Could have flag set or tag added here */
1063 if (pn.getChild("flag_list") != null || pn.getChild("tag_list") != null) {
1064 FlagEffects fe = new FlagEffects(null);
1065 if (pn.getChild("flag_list") != null)
1066 parseFlagEffect(fe, pn.getChild("flag_list"));
1068 if (pn.getChild("tag_list") != null)
1069 parseTagEffect(fe, pn.getChild("tag_list"));
1070 con.addFlagEffects(fe);
1074 } else if (isNode(pn,"createobjectcls")) {
1075 //TODO::: FIX BUG!!! static fields in caller context need to become parameters
1076 //TODO::: caller context need to be passed in here
1077 TypeDescriptor td=parseTypeDescriptor(pn);
1079 ClassDescriptor cnnew=new ClassDescriptor(packageName,td.getSymbol()+"$"+innerCount, false);
1081 cnnew.setImports(mandatoryImports, multiimports);
1082 cnnew.setSuper(td.getSymbol());
1084 parseClassBody(cnnew, pn.getChild("decl").getChild("classbody"));
1085 TypeDescriptor tdnew=state.getTypeDescriptor(cnnew.getSymbol());
1087 Vector args=parseArgumentList(pn);
1089 CreateObjectNode con=new CreateObjectNode(tdnew, false, null);
1090 con.setNumLine(pn.getLine());
1091 for(int i=0; i<args.size(); i++) {
1092 con.addArgument((ExpressionNode)args.get(i));
1096 if (analyzeset != null)
1097 analyzeset.add(cnnew);
1098 cnnew.setSourceFileName(currsourcefile);
1099 state.addClass(cnnew);
1102 } else if (isNode(pn,"createarray")) {
1103 //System.out.println(pn.PPrint(3,true));
1104 boolean isglobal=pn.getChild("global")!=null||
1105 pn.getChild("scratch")!=null;
1106 String disjointId=null;
1107 if( pn.getChild("disjoint") != null) {
1108 disjointId = pn.getChild("disjoint").getTerminal();
1110 TypeDescriptor td=parseTypeDescriptor(pn);
1111 Vector args=parseDimExprs(pn);
1113 if (pn.getChild("dims_opt").getLiteral()!=null)
1114 num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
1115 for(int i=0; i<(args.size()+num); i++)
1116 td=td.makeArray(state);
1117 CreateObjectNode con=new CreateObjectNode(td, isglobal, disjointId);
1118 con.setNumLine(pn.getLine());
1119 for(int i=0; i<args.size(); i++) {
1120 con.addArgument((ExpressionNode)args.get(i));
1124 if (isNode(pn,"createarray2")) {
1125 TypeDescriptor td=parseTypeDescriptor(pn);
1127 if (pn.getChild("dims_opt").getLiteral()!=null)
1128 num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
1129 for(int i=0; i<num; i++)
1130 td=td.makeArray(state);
1131 CreateObjectNode con=new CreateObjectNode(td, false, null);
1132 con.setNumLine(pn.getLine());
1133 ParseNode ipn = pn.getChild("initializer");
1134 Vector initializers=parseVariableInitializerList(ipn);
1135 ArrayInitializerNode ain = new ArrayInitializerNode(initializers);
1136 ain.setNumLine(pn.getLine());
1137 con.addArrayInitializer(ain);
1139 } else if (isNode(pn,"name")) {
1140 NameDescriptor nd=parseName(pn);
1141 NameNode nn=new NameNode(nd);
1142 nn.setNumLine(pn.getLine());
1144 } else if (isNode(pn,"this")) {
1145 NameDescriptor nd=new NameDescriptor("this");
1146 NameNode nn=new NameNode(nd);
1147 nn.setNumLine(pn.getLine());
1149 } else if (isNode(pn,"parentclass")) {
1150 NameDescriptor nd=new NameDescriptor("this");
1151 NameNode nn=new NameNode(nd);
1152 nn.setNumLine(pn.getLine());
1154 FieldAccessNode fan=new FieldAccessNode(nn,"this$parent");
1155 fan.setNumLine(pn.getLine());
1157 } else if (isNode(pn,"isavailable")) {
1158 NameDescriptor nd=new NameDescriptor(pn.getTerminal());
1159 NameNode nn=new NameNode(nd);
1160 nn.setNumLine(pn.getLine());
1161 return new OpNode(nn,null,new Operation(Operation.ISAVAILABLE));
1162 } else if (isNode(pn,"methodinvoke1")) {
1163 NameDescriptor nd=parseName(pn.getChild("name"));
1164 Vector args=parseArgumentList(pn);
1165 MethodInvokeNode min=new MethodInvokeNode(nd);
1166 min.setNumLine(pn.getLine());
1167 for(int i=0; i<args.size(); i++) {
1168 min.addArgument((ExpressionNode)args.get(i));
1171 } else if (isNode(pn,"methodinvoke2")) {
1172 String methodid=pn.getChild("id").getTerminal();
1173 ExpressionNode exp=parseExpression(pn.getChild("base").getFirstChild());
1174 Vector args=parseArgumentList(pn);
1175 MethodInvokeNode min=new MethodInvokeNode(methodid,exp);
1176 min.setNumLine(pn.getLine());
1177 for(int i=0; i<args.size(); i++) {
1178 min.addArgument((ExpressionNode)args.get(i));
1181 } else if (isNode(pn,"fieldaccess")) {
1182 ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild());
1183 String fieldname=pn.getChild("field").getTerminal();
1185 FieldAccessNode fan=new FieldAccessNode(en,fieldname);
1186 fan.setNumLine(pn.getLine());
1188 } else if (isNode(pn,"arrayaccess")) {
1189 ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild());
1190 ExpressionNode index=parseExpression(pn.getChild("index").getFirstChild());
1191 ArrayAccessNode aan=new ArrayAccessNode(en,index);
1192 aan.setNumLine(pn.getLine());
1194 } else if (isNode(pn,"cast1")) {
1196 CastNode cn=new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(pn.getChild("exp").getFirstChild()));
1197 cn.setNumLine(pn.getLine());
1199 } catch (Exception e) {
1200 System.out.println(pn.PPrint(1,true));
1201 e.printStackTrace();
1204 } else if (isNode(pn,"cast2")) {
1205 CastNode cn=new CastNode(parseExpression(pn.getChild("type").getFirstChild()),parseExpression(pn.getChild("exp").getFirstChild()));
1206 cn.setNumLine(pn.getLine());
1208 } else if (isNode(pn, "getoffset")) {
1209 TypeDescriptor td=parseTypeDescriptor(pn);
1210 String fieldname = pn.getChild("field").getTerminal();
1211 //System.out.println("Checking the values of: "+ " td.toString()= " + td.toString()+ " fieldname= " + fieldname);
1212 return new OffsetNode(td, fieldname);
1213 } else if (isNode(pn, "tert")) {
1215 TertiaryNode tn=new TertiaryNode(parseExpression(pn.getChild("cond").getFirstChild()),
1216 parseExpression(pn.getChild("trueexpr").getFirstChild()),
1217 parseExpression(pn.getChild("falseexpr").getFirstChild()) );
1218 tn.setNumLine(pn.getLine());
1221 } else if (isNode(pn, "instanceof")) {
1222 ExpressionNode exp=parseExpression(pn.getChild("exp").getFirstChild());
1223 TypeDescriptor t=parseTypeDescriptor(pn);
1224 InstanceOfNode ion=new InstanceOfNode(exp,t);
1225 ion.setNumLine(pn.getLine());
1227 } else if (isNode(pn, "array_initializer")) {
1228 Vector initializers=parseVariableInitializerList(pn);
1229 return new ArrayInitializerNode(initializers);
1230 } else if (isNode(pn, "class_type")) {
1231 TypeDescriptor td=parseTypeDescriptor(pn);
1232 ClassTypeNode ctn=new ClassTypeNode(td);
1233 ctn.setNumLine(pn.getLine());
1235 } else if (isNode(pn, "empty")) {
1238 System.out.println("---------------------");
1239 System.out.println(pn.PPrint(3,true));
1244 private Vector parseDimExprs(ParseNode pn) {
1245 Vector arglist=new Vector();
1246 ParseNode an=pn.getChild("dim_exprs");
1247 if (an==null) /* No argument list */
1249 ParseNodeVector anv=an.getChildren();
1250 for(int i=0; i<anv.size(); i++) {
1251 arglist.add(parseExpression(anv.elementAt(i)));
1256 private Vector parseArgumentList(ParseNode pn) {
1257 Vector arglist=new Vector();
1258 ParseNode an=pn.getChild("argument_list");
1259 if (an==null) /* No argument list */
1261 ParseNodeVector anv=an.getChildren();
1262 for(int i=0; i<anv.size(); i++) {
1263 arglist.add(parseExpression(anv.elementAt(i)));
1268 private Vector[] parseConsArgumentList(ParseNode pn) {
1269 Vector arglist=new Vector();
1270 Vector varlist=new Vector();
1271 ParseNode an=pn.getChild("cons_argument_list");
1272 if (an==null) /* No argument list */
1273 return new Vector[] {varlist, arglist};
1274 ParseNodeVector anv=an.getChildren();
1275 for(int i=0; i<anv.size(); i++) {
1276 ParseNode cpn=anv.elementAt(i);
1277 ParseNode var=cpn.getChild("var");
1278 ParseNode exp=cpn.getChild("exp").getFirstChild();
1279 varlist.add(var.getTerminal());
1280 arglist.add(parseExpression(exp));
1282 return new Vector[] {varlist, arglist};
1285 private Vector parseVariableInitializerList(ParseNode pn) {
1286 Vector varInitList=new Vector();
1287 ParseNode vin=pn.getChild("var_init_list");
1288 if (vin==null) /* No argument list */
1290 ParseNodeVector vinv=vin.getChildren();
1291 for(int i=0; i<vinv.size(); i++) {
1292 varInitList.add(parseExpression(vinv.elementAt(i)));
1297 private ExpressionNode parseAssignmentExpression(ParseNode pn) {
1298 AssignOperation ao=new AssignOperation(pn.getChild("op").getTerminal());
1299 ParseNodeVector pnv=pn.getChild("args").getChildren();
1301 AssignmentNode an=new AssignmentNode(parseExpression(pnv.elementAt(0)),parseExpression(pnv.elementAt(1)),ao);
1302 an.setNumLine(pn.getLine());
1307 private void parseMethodDecl(ClassDescriptor cn, ParseNode pn) {
1308 ParseNode headern=pn.getChild("method_header");
1309 ParseNode bodyn=pn.getChild("body");
1310 MethodDescriptor md=parseMethodHeader(headern);
1312 BlockNode bn=parseBlock(bodyn);
1313 bn.setNumLine(pn.getLine()); // assume that method header is located at the beginning of method body
1315 state.addTreeCode(md,bn);
1317 // this is a hack for investigating new language features
1318 // at the AST level, someday should evolve into a nice compiler
1320 //if( cn.getSymbol().equals( ***put a class in here like: "Test" ) &&
1321 // md.getSymbol().equals( ***put your method in here like: "main" )
1323 // bn.setStyle( BlockNode.NORMAL );
1324 // System.out.println( bn.printNode( 0 ) );
1327 } catch (Exception e) {
1328 System.out.println("Error with method:"+md.getSymbol());
1329 e.printStackTrace();
1332 System.out.println("Error with method:"+md.getSymbol());
1333 e.printStackTrace();
1338 private void parseConstructorDecl(ClassDescriptor cn, ParseNode pn) {
1339 ParseNode mn=pn.getChild("modifiers");
1340 Modifiers m=parseModifiersList(mn);
1341 ParseNode cdecl=pn.getChild("constructor_declarator");
1342 boolean isglobal=cdecl.getChild("global")!=null;
1343 String name=resolveName(cn.getSymbol());
1344 MethodDescriptor md=new MethodDescriptor(m, name, isglobal);
1345 ParseNode paramnode=cdecl.getChild("parameters");
1346 parseParameterList(md,paramnode);
1347 ParseNode bodyn0=pn.getChild("body");
1348 ParseNode bodyn=bodyn0.getChild("constructor_body");
1351 if (bodyn!=null&&bodyn.getChild("block_statement_list")!=null)
1352 bn=parseBlock(bodyn);
1355 if (bodyn!=null&&bodyn.getChild("superinvoke")!=null) {
1356 ParseNode sin=bodyn.getChild("superinvoke");
1357 NameDescriptor nd=new NameDescriptor("super");
1358 Vector args=parseArgumentList(sin);
1359 MethodInvokeNode min=new MethodInvokeNode(nd);
1360 min.setNumLine(sin.getLine());
1361 for(int i=0; i<args.size(); i++) {
1362 min.addArgument((ExpressionNode)args.get(i));
1364 BlockExpressionNode ben=new BlockExpressionNode(min);
1365 bn.addFirstBlockStatement(ben);
1367 } else if (bodyn!=null&&bodyn.getChild("explconstrinv")!=null) {
1368 ParseNode eci=bodyn.getChild("explconstrinv");
1369 NameDescriptor nd=new NameDescriptor(cn.getSymbol());
1370 Vector args=parseArgumentList(eci);
1371 MethodInvokeNode min=new MethodInvokeNode(nd);
1372 min.setNumLine(eci.getLine());
1373 for(int i=0; i<args.size(); i++) {
1374 min.addArgument((ExpressionNode)args.get(i));
1376 BlockExpressionNode ben=new BlockExpressionNode(min);
1377 ben.setNumLine(eci.getLine());
1378 bn.addFirstBlockStatement(ben);
1380 state.addTreeCode(md,bn);
1383 private void parseStaticBlockDecl(ClassDescriptor cn, ParseNode pn) {
1384 // Each class maintains one MethodDecscriptor which combines all its
1385 // static blocks in their declaration order
1386 boolean isfirst = false;
1387 MethodDescriptor md = (MethodDescriptor)cn.getMethodTable().getFromSameScope("staticblocks");
1389 // the first static block for this class
1390 Modifiers m_i=new Modifiers();
1391 m_i.addModifier(Modifiers.STATIC);
1392 md = new MethodDescriptor(m_i, "staticblocks", false);
1393 md.setAsStaticBlock();
1396 ParseNode bodyn=pn.getChild("body");
1400 cn.incStaticBlocks();
1402 if (bodyn!=null&&bodyn.getChild("block_statement_list")!=null)
1403 bn=parseBlock(bodyn);
1407 state.addTreeCode(md,bn);
1409 BlockNode obn = state.getMethodBody(md);
1410 for(int i = 0; i < bn.size(); i++) {
1411 BlockStatementNode bsn = bn.get(i);
1412 obn.addBlockStatement(bsn);
1414 state.addTreeCode(md, obn);
1419 public BlockNode parseBlock(ParseNode pn) {
1420 this.m_taskexitnum = 0;
1421 if (pn==null||isEmpty(pn.getTerminal()))
1422 return new BlockNode();
1423 ParseNode bsn=pn.getChild("block_statement_list");
1424 return parseBlockHelper(bsn);
1427 private BlockNode parseBlockHelper(ParseNode pn) {
1428 ParseNodeVector pnv=pn.getChildren();
1429 BlockNode bn=new BlockNode();
1430 for(int i=0; i<pnv.size(); i++) {
1431 Vector bsv=parseBlockStatement(pnv.elementAt(i));
1432 for(int j=0; j<bsv.size(); j++) {
1433 bn.addBlockStatement((BlockStatementNode)bsv.get(j));
1439 public BlockNode parseSingleBlock(ParseNode pn, String label){
1440 BlockNode bn=new BlockNode();
1441 Vector bsv=parseBlockStatement(pn,label);
1442 for(int j=0; j<bsv.size(); j++) {
1443 bn.addBlockStatement((BlockStatementNode)bsv.get(j));
1445 bn.setStyle(BlockNode.NOBRACES);
1449 public BlockNode parseSingleBlock(ParseNode pn) {
1450 return parseSingleBlock(pn,null);
1453 public Vector parseSESEBlock(Vector parentbs, ParseNode pn) {
1454 ParseNodeVector pnv=pn.getChildren();
1455 Vector bv=new Vector();
1456 for(int i=0; i<pnv.size(); i++) {
1457 bv.addAll(parseBlockStatement(pnv.elementAt(i)));
1462 public Vector parseBlockStatement(ParseNode pn){
1463 return parseBlockStatement(pn,null);
1466 public Vector parseBlockStatement(ParseNode pn, String label) {
1467 Vector blockstatements=new Vector();
1468 if (isNode(pn,"tag_declaration")) {
1469 String name=pn.getChild("single").getTerminal();
1470 String type=pn.getChild("type").getTerminal();
1472 TagDeclarationNode tdn=new TagDeclarationNode(name, type);
1473 tdn.setNumLine(pn.getLine());
1475 blockstatements.add(tdn);
1476 } else if (isNode(pn,"local_variable_declaration")) {
1478 TypeDescriptor t=parseTypeDescriptor(pn);
1479 ParseNode vn=pn.getChild("variable_declarators_list");
1480 ParseNodeVector pnv=vn.getChildren();
1481 for(int i=0; i<pnv.size(); i++) {
1482 ParseNode vardecl=pnv.elementAt(i);
1485 ParseNode tmp=vardecl;
1486 TypeDescriptor arrayt=t;
1488 while (tmp.getChild("single")==null) {
1489 arrayt=arrayt.makeArray(state);
1490 tmp=tmp.getChild("array");
1492 String identifier=tmp.getChild("single").getTerminal();
1494 ParseNode epn=vardecl.getChild("initializer");
1497 ExpressionNode en=null;
1499 en=parseExpression(epn.getFirstChild());
1501 DeclarationNode dn=new DeclarationNode(new VarDescriptor(arrayt, identifier),en);
1502 dn.setNumLine(tmp.getLine());
1504 ParseNode mn=pn.getChild("modifiers");
1506 // here, modifers parse node has the list of annotations
1507 Modifiers m=parseModifiersList(mn);
1508 assignAnnotationsToType(m, arrayt);
1511 blockstatements.add(dn);
1513 } else if (isNode(pn,"nop")) {
1515 } else if (isNode(pn,"expression")) {
1516 BlockExpressionNode ben=new BlockExpressionNode(parseExpression(pn.getFirstChild()));
1517 ben.setNumLine(pn.getLine());
1518 blockstatements.add(ben);
1519 } else if (isNode(pn,"ifstatement")) {
1520 IfStatementNode isn=new IfStatementNode(parseExpression(pn.getChild("condition").getFirstChild()),
1521 parseSingleBlock(pn.getChild("statement").getFirstChild()),
1522 pn.getChild("else_statement")!=null?parseSingleBlock(pn.getChild("else_statement").getFirstChild()):null);
1523 isn.setNumLine(pn.getLine());
1525 blockstatements.add(isn);
1526 } else if (isNode(pn,"switch_statement")) {
1527 // TODO add version for normal Java later
1528 SwitchStatementNode ssn=new SwitchStatementNode(parseExpression(pn.getChild("condition").getFirstChild()),
1529 parseSingleBlock(pn.getChild("statement").getFirstChild()));
1530 ssn.setNumLine(pn.getLine());
1531 blockstatements.add(ssn);
1532 } else if (isNode(pn,"switch_block_list")) {
1533 // TODO add version for normal Java later
1534 ParseNodeVector pnv=pn.getChildren();
1535 for(int i=0; i<pnv.size(); i++) {
1536 ParseNode sblockdecl=pnv.elementAt(i);
1538 if(isNode(sblockdecl, "switch_block")) {
1539 ParseNode lpn=sblockdecl.getChild("switch_labels").getChild("switch_label_list");
1540 ParseNodeVector labelv=lpn.getChildren();
1541 Vector<SwitchLabelNode> slv = new Vector<SwitchLabelNode>();
1542 for(int j=0; j<labelv.size(); j++) {
1543 ParseNode labeldecl=labelv.elementAt(j);
1544 if(isNode(labeldecl, "switch_label")) {
1545 SwitchLabelNode sln=new SwitchLabelNode(parseExpression(labeldecl.getChild("constant_expression").getFirstChild()), false);
1546 sln.setNumLine(labeldecl.getLine());
1547 slv.addElement(sln);
1548 } else if(isNode(labeldecl, "default_switch_label")) {
1549 SwitchLabelNode sln=new SwitchLabelNode(null, true);
1550 sln.setNumLine(labeldecl.getLine());
1551 slv.addElement(sln);
1555 SwitchBlockNode sbn=new SwitchBlockNode(slv,
1556 parseSingleBlock(sblockdecl.getChild("switch_statements").getFirstChild()));
1557 sbn.setNumLine(sblockdecl.getLine());
1559 blockstatements.add(sbn);
1563 } else if (isNode(pn, "trycatchstatement")) {
1564 // TODO add version for normal Java later
1565 // Do not fully support exceptions now. Only make sure that if there are no
1566 // exceptions thrown, the execution is right
1567 ParseNode tpn = pn.getChild("tryblock").getFirstChild();
1568 BlockNode bn=parseBlockHelper(tpn);
1569 blockstatements.add(new SubBlockNode(bn));
1571 ParseNode fbk = pn.getChild("finallyblock");
1573 ParseNode fpn = fbk.getFirstChild();
1574 BlockNode fbn=parseBlockHelper(fpn);
1575 blockstatements.add(new SubBlockNode(fbn));
1577 } else if (isNode(pn, "throwstatement")) {
1578 // TODO Simply return here
1579 //blockstatements.add(new ReturnNode());
1580 } else if (isNode(pn,"taskexit")) {
1582 if (pn.getChild("flag_effects_list")!=null)
1583 vfe=parseFlags(pn.getChild("flag_effects_list"));
1585 if (pn.getChild("cons_checks")!=null)
1586 ccs=parseChecks(pn.getChild("cons_checks"));
1587 TaskExitNode ten=new TaskExitNode(vfe, ccs, this.m_taskexitnum++);
1588 ten.setNumLine(pn.getLine());
1589 blockstatements.add(ten);
1590 } else if (isNode(pn,"atomic")) {
1591 BlockNode bn=parseBlockHelper(pn);
1592 AtomicNode an=new AtomicNode(bn);
1593 an.setNumLine(pn.getLine());
1594 blockstatements.add(an);
1595 } else if (isNode(pn,"synchronized")) {
1596 BlockNode bn=parseBlockHelper(pn.getChild("block"));
1597 ExpressionNode en=parseExpression(pn.getChild("expr").getFirstChild());
1598 SynchronizedNode sn=new SynchronizedNode(en, bn);
1599 sn.setNumLine(pn.getLine());
1600 blockstatements.add(sn);
1601 } else if (isNode(pn,"return")) {
1602 if (isEmpty(pn.getTerminal()))
1603 blockstatements.add(new ReturnNode());
1605 ExpressionNode en=parseExpression(pn.getFirstChild());
1606 ReturnNode rn=new ReturnNode(en);
1607 rn.setNumLine(pn.getLine());
1608 blockstatements.add(rn);
1610 } else if (isNode(pn,"block_statement_list")) {
1611 BlockNode bn=parseBlockHelper(pn);
1612 blockstatements.add(new SubBlockNode(bn));
1613 } else if (isNode(pn,"empty")) {
1615 } else if (isNode(pn,"statement_expression_list")) {
1616 ParseNodeVector pnv=pn.getChildren();
1617 BlockNode bn=new BlockNode();
1618 for(int i=0; i<pnv.size(); i++) {
1619 ExpressionNode en=parseExpression(pnv.elementAt(i));
1620 blockstatements.add(new BlockExpressionNode(en));
1622 bn.setStyle(BlockNode.EXPRLIST);
1623 } else if (isNode(pn,"forstatement")) {
1624 BlockNode init=parseSingleBlock(pn.getChild("initializer").getFirstChild());
1625 BlockNode update=parseSingleBlock(pn.getChild("update").getFirstChild());
1626 ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
1627 BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
1628 if(condition == null) {
1629 // no condition clause, make a 'true' expression as the condition
1630 condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
1632 LoopNode ln=new LoopNode(init,condition,update,body,label);
1633 ln.setNumLine(pn.getLine());
1634 blockstatements.add(ln);
1635 } else if (isNode(pn,"whilestatement")) {
1636 ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
1637 BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
1638 if(condition == null) {
1639 // no condition clause, make a 'true' expression as the condition
1640 condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
1642 blockstatements.add(new LoopNode(condition,body,LoopNode.WHILELOOP,label));
1643 } else if (isNode(pn,"dowhilestatement")) {
1644 ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
1645 BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
1646 if(condition == null) {
1647 // no condition clause, make a 'true' expression as the condition
1648 condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
1650 blockstatements.add(new LoopNode(condition,body,LoopNode.DOWHILELOOP,label));
1651 } else if (isNode(pn,"sese")) {
1652 ParseNode pnID=pn.getChild("identifier");
1654 if( pnID != null ) {
1655 stID=pnID.getFirstChild().getTerminal();
1657 SESENode start=new SESENode(stID);
1658 start.setNumLine(pn.getLine());
1659 SESENode end =new SESENode(stID);
1661 end.setStart(start);
1662 blockstatements.add(start);
1663 blockstatements.addAll(parseSESEBlock(blockstatements,pn.getChild("body").getFirstChild()));
1664 blockstatements.add(end);
1665 } else if (isNode(pn,"continue")) {
1666 ContinueBreakNode cbn=new ContinueBreakNode(false);
1667 cbn.setNumLine(pn.getLine());
1668 blockstatements.add(cbn);
1669 } else if (isNode(pn,"break")) {
1670 ContinueBreakNode cbn=new ContinueBreakNode(true);
1671 cbn.setNumLine(pn.getLine());
1672 blockstatements.add(cbn);
1673 ParseNode idopt_pn=pn.getChild("identifier_opt");
1674 ParseNode name_pn=idopt_pn.getChild("name");
1675 // name_pn.getTerminal() gives you the label
1677 } else if (isNode(pn,"genreach")) {
1678 String graphName = pn.getChild("graphName").getTerminal();
1679 blockstatements.add(new GenReachNode(graphName) );
1681 } else if (isNode(pn,"gen_def_reach")) {
1682 String outputName = pn.getChild("outputName").getTerminal();
1683 blockstatements.add(new GenDefReachNode(outputName) );
1685 } else if(isNode(pn,"labeledstatement")) {
1686 String labeledstatement = pn.getChild("name").getTerminal();
1687 BlockNode bn=parseSingleBlock(pn.getChild("statement").getFirstChild(),labeledstatement);
1688 blockstatements.add(new SubBlockNode(bn));
1690 System.out.println("---------------");
1691 System.out.println(pn.PPrint(3,true));
1694 return blockstatements;
1697 public MethodDescriptor parseMethodHeader(ParseNode pn) {
1698 ParseNode mn=pn.getChild("modifiers");
1699 Modifiers m=parseModifiersList(mn);
1701 ParseNode tn=pn.getChild("returntype");
1702 TypeDescriptor returntype;
1704 returntype=parseTypeDescriptor(tn);
1706 returntype=new TypeDescriptor(TypeDescriptor.VOID);
1708 ParseNode pmd=pn.getChild("method_declarator");
1709 String name=pmd.getChild("name").getTerminal();
1710 MethodDescriptor md=new MethodDescriptor(m, returntype, name);
1712 ParseNode paramnode=pmd.getChild("parameters");
1713 parseParameterList(md,paramnode);
1717 public void parseParameterList(MethodDescriptor md, ParseNode pn) {
1718 ParseNode paramlist=pn.getChild("formal_parameter_list");
1719 if (paramlist==null)
1721 ParseNodeVector pnv=paramlist.getChildren();
1722 for(int i=0; i<pnv.size(); i++) {
1723 ParseNode paramn=pnv.elementAt(i);
1725 if (isNode(paramn, "tag_parameter")) {
1726 String paramname=paramn.getChild("single").getTerminal();
1727 TypeDescriptor type=new TypeDescriptor(TypeDescriptor.TAG);
1728 md.addTagParameter(type, paramname);
1731 TypeDescriptor type=parseTypeDescriptor(paramn);
1733 ParseNode tmp=paramn;
1734 while (tmp.getChild("single")==null) {
1735 type=type.makeArray(state);
1736 tmp=tmp.getChild("array");
1738 String paramname=tmp.getChild("single").getTerminal();
1740 md.addParameter(type, paramname);
1741 if(isNode(paramn, "annotation_parameter")) {
1742 ParseNode listnode=paramn.getChild("annotation_list");
1743 parseParameterAnnotation(listnode,type);
1750 public Modifiers parseModifiersList(ParseNode pn) {
1751 Modifiers m=new Modifiers();
1752 ParseNode modlist=pn.getChild("modifier_list");
1753 if (modlist!=null) {
1754 ParseNodeVector pnv=modlist.getChildren();
1755 for(int i=0; i<pnv.size(); i++) {
1756 ParseNode modn=pnv.elementAt(i);
1757 if (isNode(modn,"public"))
1758 m.addModifier(Modifiers.PUBLIC);
1759 else if (isNode(modn,"protected"))
1760 m.addModifier(Modifiers.PROTECTED);
1761 else if (isNode(modn,"private"))
1762 m.addModifier(Modifiers.PRIVATE);
1763 else if (isNode(modn,"static"))
1764 m.addModifier(Modifiers.STATIC);
1765 else if (isNode(modn,"final"))
1766 m.addModifier(Modifiers.FINAL);
1767 else if (isNode(modn,"native"))
1768 m.addModifier(Modifiers.NATIVE);
1769 else if (isNode(modn,"synchronized"))
1770 m.addModifier(Modifiers.SYNCHRONIZED);
1771 else if (isNode(modn,"atomic"))
1772 m.addModifier(Modifiers.ATOMIC);
1773 else if (isNode(modn,"abstract"))
1774 m.addModifier(Modifiers.ABSTRACT);
1775 else if (isNode(modn,"volatile"))
1776 m.addModifier(Modifiers.VOLATILE);
1777 else if (isNode(modn,"transient"))
1778 m.addModifier(Modifiers.TRANSIENT);
1779 else if(isNode(modn,"annotation_list"))
1780 parseAnnotationList(modn,m);
1782 throw new Error("Unrecognized Modifier:"+modn.getLabel());
1789 private void parseAnnotationList(ParseNode pn, Modifiers m) {
1790 ParseNodeVector pnv = pn.getChildren();
1791 for (int i = 0; i < pnv.size(); i++) {
1792 ParseNode body_list = pnv.elementAt(i);
1793 if (isNode(body_list, "annotation_body")) {
1794 ParseNode body_node = body_list.getFirstChild();
1795 if (isNode(body_node, "marker_annotation")) {
1796 m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal()));
1797 } else if (isNode(body_node, "single_annotation")) {
1798 m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal(),
1799 body_node.getChild("element_value").getTerminal()));
1800 } else if (isNode(body_node, "normal_annotation")) {
1801 throw new Error("Annotation with multiple data members is not supported yet.");
1807 private void parseParameterAnnotation(ParseNode pn,TypeDescriptor type) {
1808 ParseNodeVector pnv = pn.getChildren();
1809 for (int i = 0; i < pnv.size(); i++) {
1810 ParseNode body_list = pnv.elementAt(i);
1811 if (isNode(body_list, "annotation_body")) {
1812 ParseNode body_node = body_list.getFirstChild();
1813 if (isNode(body_node, "marker_annotation")) {
1814 type.addAnnotationMarker(new AnnotationDescriptor(body_node.getChild("name").getTerminal()));
1815 } else if (isNode(body_node, "single_annotation")) {
1816 type.addAnnotationMarker(new AnnotationDescriptor(body_node.getChild("name").getTerminal(),
1817 body_node.getChild("element_value").getTerminal()));
1818 } else if (isNode(body_node, "normal_annotation")) {
1819 throw new Error("Annotation with multiple data members is not supported yet.");
1825 private boolean isNode(ParseNode pn, String label) {
1826 if (pn.getLabel().equals(label))
1831 private static boolean isEmpty(ParseNode pn) {
1832 if (pn.getLabel().equals("empty"))
1838 private static boolean isEmpty(String s) {
1839 if (s.equals("empty"))
1845 /** Throw an exception if something is unexpected */
1846 private void check(ParseNode pn, String label) {
1848 throw new Error(pn+ "IE: Expected '" + label + "', got null");
1850 if (!pn.getLabel().equals(label)) {
1851 throw new Error(pn+ "IE: Expected '" + label + "', got '"+pn.getLabel()+"'");