checking in code
[IRC.git] / Robust / src / IR / Tree / BuildIR.java
1 package IR.Tree;
2 import IR.*;
3 import java.util.*;
4
5
6 public class BuildIR {
7     State state;
8     public BuildIR(State state) {
9         this.state=state;
10     }
11     public void buildtree() {
12         for(Iterator it=state.parsetrees.iterator();it.hasNext();) {
13             ParseNode pn=(ParseNode)it.next();
14             parseFile(pn);
15         }
16     }
17
18     /** Parse the classes in this file */
19     public void parseFile(ParseNode pn) {
20         ParseNode tpn=pn.getChild("type_declaration_list");
21         if (tpn!=null) {
22             ParseNodeVector pnv=tpn.getChildren();
23             for(int i=0;i<pnv.size();i++) {
24                 ParseNode type_pn=pnv.elementAt(i);
25                 if (isEmpty(type_pn)) /* Skip the semicolon */
26                     continue;
27                 if (isNode(type_pn,"class_declaration")) {
28                     ClassDescriptor cn=parseTypeDecl(type_pn);
29                     state.addClass(cn);
30                 } else if (isNode(type_pn,"task_declaration")) {
31                     TaskDescriptor td=parseTaskDecl(type_pn);
32                     state.addTask(td);
33                 } throw new Error();
34             }
35         }
36     }
37
38     public TaskDescriptor parseTaskDecl(ParseNode pn) {
39         TaskDescriptor td=new TaskDescriptor(pn.getChild("name").getTerminal());
40         ParseNode bodyn=pn.getChild("body");
41         BlockNode bn=parseBlock(bodyn);
42         parseParameterList(td, pn);
43         state.addTreeCode(td,bn);
44         return td;
45     }
46
47     public FlagExpressionNode parseFlagExpression(ParseNode pn) {
48         if (paramn.getChild("or")!=null) {
49             ParseNodeVector pnv=paramn.getChild("or").getChildren();
50             ParseNode left=pnv.elementAt(0);
51             ParseNode right=pnv.elementAt(1);
52             return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_OR));
53         } else if (paramn.getChild("and")!=null) {
54             ParseNodeVector pnv=paramn.getChild("and").getChildren();
55             ParseNode left=pnv.elementAt(0);
56             ParseNode right=pnv.elementAt(1);
57             return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_AND));
58         } else if (paramn.getChild("not")!=null) {
59             ParseNodeVector pnv=paramn.getChild("not").getChildren();
60             ParseNode left=pnv.elementAt(0);
61             return new FlagOpNode(parseFlagExpression(left), new Operation(Operation.LOGIC_NOT));           
62
63         } else if (paramn.getChild("name")!=null) {
64             return new FlagNode(paramn.getChild("name").getTerminal());
65         } else throw new Error();
66     }
67
68     public void parseParameterList(TaskDescriptor td, ParseNode pn) {
69         ParseNode paramlist=pn.getChild("task_parameter_list");
70         if (paramlist==null)
71             return;
72          ParseNodeVector pnv=paramlist.getChildren();
73          for(int i=0;i<pnv.size();i++) {
74              ParseNode paramn=pnv.elementAt(i);
75              TypeDescriptor type=parseTypeDescriptor(paramn);
76
77              ParseNode tmp=paramn;
78              while (tmp.getChild("single")==null) {
79                  type=type.makeArray(state);
80                  tmp=tmp.getChild("array");
81              }
82              String paramname=tmp.getChild("single").getTerminal();
83              FlagExpressionNode fen=parseFlagExpression(paramn.getChild("flag"));
84              
85              td.addParameter(type,paramname);
86          }
87     }
88
89     public ClassDescriptor parseTypeDecl(ParseNode pn) {
90         ClassDescriptor cn=new ClassDescriptor(pn.getChild("name").getTerminal());
91         if (!isEmpty(pn.getChild("super").getTerminal())) {
92             /* parse superclass name */
93             ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
94             NameDescriptor nd=parseName(snn);
95             cn.setSuper(nd.toString());
96         } else {
97             if (!cn.getSymbol().equals(TypeUtil.ObjectClass))
98                 cn.setSuper(TypeUtil.ObjectClass);
99         }
100         cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
101         parseClassBody(cn, pn.getChild("classbody"));
102         return cn;
103     }
104
105     private void parseClassBody(ClassDescriptor cn, ParseNode pn) {
106         ParseNode decls=pn.getChild("class_body_declaration_list");
107         if (decls!=null) {
108             ParseNodeVector pnv=decls.getChildren();
109             for(int i=0;i<pnv.size();i++) {
110                 ParseNode decl=pnv.elementAt(i);
111                 if (isNode(decl,"member")) {
112                     parseClassMember(cn,decl);
113                 } else if (isNode(decl,"constructor")) {
114                     parseConstructorDecl(cn,decl.getChild("constructor_declaration"));
115                 } else if (isNode(decl,"block")) {
116                 } else throw new Error();
117             }
118         }
119     }
120
121     private void parseClassMember(ClassDescriptor cn, ParseNode pn) {
122         ParseNode fieldnode=pn.getChild("field");
123
124         if (fieldnode!=null) {
125             parseFieldDecl(cn,fieldnode.getChild("field_declaration"));
126             return;
127         }
128         ParseNode methodnode=pn.getChild("method");
129         if (methodnode!=null) {
130             parseMethodDecl(cn,methodnode.getChild("method_declaration"));
131             return;
132         }
133         throw new Error();
134     }
135
136     private TypeDescriptor parseTypeDescriptor(ParseNode pn) {
137         ParseNode tn=pn.getChild("type");
138         String type_st=tn.getTerminal();
139         if(type_st.equals("byte")) {
140             return state.getTypeDescriptor(TypeDescriptor.BYTE);
141         } else if(type_st.equals("short")) {
142             return state.getTypeDescriptor(TypeDescriptor.SHORT);
143         } else if(type_st.equals("boolean")) {
144             return state.getTypeDescriptor(TypeDescriptor.BOOLEAN);
145         } else if(type_st.equals("int")) {
146             return state.getTypeDescriptor(TypeDescriptor.INT);
147         } else if(type_st.equals("long")) {
148             return state.getTypeDescriptor(TypeDescriptor.LONG);
149         } else if(type_st.equals("char")) {
150             return state.getTypeDescriptor(TypeDescriptor.CHAR);
151         } else if(type_st.equals("float")) {
152             return state.getTypeDescriptor(TypeDescriptor.FLOAT);
153         } else if(type_st.equals("double")) {
154             return state.getTypeDescriptor(TypeDescriptor.DOUBLE);
155         } else if(type_st.equals("class")) {
156             ParseNode nn=tn.getChild("class");
157             return state.getTypeDescriptor(parseName(nn.getChild("name")));
158         } else if(type_st.equals("array")) {
159             ParseNode nn=tn.getChild("array");
160             TypeDescriptor td=parseTypeDescriptor(nn.getChild("basetype"));
161             Integer numdims=(Integer)nn.getChild("dims").getLiteral();
162             for(int i=0;i<numdims.intValue();i++)
163                 td=td.makeArray(state);
164             return td;
165         } else {
166             throw new Error();
167         }
168     }
169
170     private NameDescriptor parseName(ParseNode nn) {
171         ParseNode base=nn.getChild("base");
172         ParseNode id=nn.getChild("identifier");
173         if (base==null)
174             return new NameDescriptor(id.getTerminal());
175         return new NameDescriptor(parseName(base.getChild("name")),id.getTerminal());
176         
177     }
178
179     private void parseFieldDecl(ClassDescriptor cn,ParseNode pn) {
180         ParseNode mn=pn.getChild("modifier");
181         Modifiers m=parseModifiersList(mn);
182
183         ParseNode tn=pn.getChild("type");
184         TypeDescriptor t=parseTypeDescriptor(tn);
185         ParseNode vn=pn.getChild("variables").getChild("variable_declarators_list");
186         ParseNodeVector pnv=vn.getChildren();
187         for(int i=0;i<pnv.size();i++) {
188             ParseNode vardecl=pnv.elementAt(i);
189
190             
191             ParseNode tmp=vardecl;
192             TypeDescriptor arrayt=t;
193             while (tmp.getChild("single")==null) {
194                 arrayt=arrayt.makeArray(state);
195                 tmp=tmp.getChild("array");
196             }
197             String identifier=tmp.getChild("single").getTerminal();
198
199             ParseNode epn=vardecl.getChild("initializer");
200             
201             ExpressionNode en=null;
202             if (epn!=null)
203                 en=parseExpression(epn.getFirstChild());
204   
205             cn.addField(new FieldDescriptor(m,arrayt,identifier, en));
206         }
207         
208     }
209
210     private ExpressionNode parseExpression(ParseNode pn) {
211         if (isNode(pn,"assignment"))
212             return parseAssignmentExpression(pn);
213         else if (isNode(pn,"logical_or")||isNode(pn,"logical_and")||
214                  isNode(pn,"bitwise_or")||isNode(pn,"bitwise_xor")||
215                  isNode(pn,"bitwise_and")||isNode(pn,"equal")||
216                  isNode(pn,"not_equal")||isNode(pn,"comp_lt")||
217                  isNode(pn,"comp_lte")||isNode(pn,"comp_gt")||
218                  isNode(pn,"comp_gte")||isNode(pn,"leftshift")||
219                  isNode(pn,"rightshift")||isNode(pn,"sub")||
220                  isNode(pn,"add")||isNode(pn,"mult")||
221                  isNode(pn,"div")||isNode(pn,"mod")) {
222             ParseNodeVector pnv=pn.getChildren();
223             ParseNode left=pnv.elementAt(0);
224             ParseNode right=pnv.elementAt(1);
225             Operation op=new Operation(pn.getLabel());
226             return new OpNode(parseExpression(left),parseExpression(right),op);
227         } else if (isNode(pn,"unaryplus")||
228                    isNode(pn,"unaryminus")||
229                    isNode(pn,"postinc")||
230                    isNode(pn,"postdec")||
231                    isNode(pn,"preinc")||
232                    isNode(pn,"not")||
233                    isNode(pn,"predec")) {
234             ParseNode left=pn.getFirstChild();
235             Operation op=new Operation(pn.getLabel());
236             return new OpNode(parseExpression(left),op);
237         } else if (isNode(pn,"literal")) {
238             String literaltype=pn.getTerminal();
239             ParseNode literalnode=pn.getChild(literaltype);
240             Object literal_obj=literalnode.getLiteral();
241             return new LiteralNode(literaltype, literal_obj);
242         } else if (isNode(pn,"createobject")) {
243             TypeDescriptor td=parseTypeDescriptor(pn);
244             Vector args=parseArgumentList(pn);
245             CreateObjectNode con=new CreateObjectNode(td);
246             for(int i=0;i<args.size();i++) {
247                 con.addArgument((ExpressionNode)args.get(i));
248             }
249             return con;
250         } else if (isNode(pn,"createarray")) {
251             System.out.println(pn.PPrint(3,true));
252             TypeDescriptor td=parseTypeDescriptor(pn);
253             Vector args=parseDimExprs(pn);
254             int num=0;
255             if (pn.getChild("dims_opt").getLiteral()!=null)
256                 num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
257             for(int i=0;i<(args.size()+num);i++)
258                 td=td.makeArray(state);
259             CreateObjectNode con=new CreateObjectNode(td);
260             for(int i=0;i<args.size();i++) {
261                 con.addArgument((ExpressionNode)args.get(i));
262             }
263             return con;
264         } else if (isNode(pn,"name")) {
265             NameDescriptor nd=parseName(pn);
266             return new NameNode(nd);
267         } else if (isNode(pn,"this")) {
268             NameDescriptor nd=new NameDescriptor("this");
269             return new NameNode(nd);
270         } else if (isNode(pn,"methodinvoke1")) {
271             NameDescriptor nd=parseName(pn.getChild("name"));
272             Vector args=parseArgumentList(pn);
273             MethodInvokeNode min=new MethodInvokeNode(nd);
274             for(int i=0;i<args.size();i++) {
275                 min.addArgument((ExpressionNode)args.get(i));
276             }
277             return min;
278         } else if (isNode(pn,"methodinvoke2")) {
279             String methodid=pn.getChild("id").getTerminal();
280             ExpressionNode exp=parseExpression(pn.getChild("base").getFirstChild());
281             Vector args=parseArgumentList(pn);
282             MethodInvokeNode min=new MethodInvokeNode(methodid,exp);
283             for(int i=0;i<args.size();i++) {
284                 min.addArgument((ExpressionNode)args.get(i));
285             }
286             return min;
287         } else if (isNode(pn,"fieldaccess")) { 
288             ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild());         String fieldname=pn.getChild("field").getTerminal();
289             return new FieldAccessNode(en,fieldname);
290         } else if (isNode(pn,"arrayaccess")) { 
291             ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild());
292             ExpressionNode index=parseExpression(pn.getChild("index").getFirstChild());
293             return new ArrayAccessNode(en,index);
294         } else if (isNode(pn,"cast1")) { 
295             return new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(pn.getChild("exp").getFirstChild()));
296         } else if (isNode(pn,"cast2")) { 
297             return new CastNode(parseExpression(pn.getChild("type").getFirstChild()),parseExpression(pn.getChild("exp").getFirstChild()));
298         } else {
299             System.out.println("---------------------");
300             System.out.println(pn.PPrint(3,true));
301             throw new Error();
302         }
303     }
304
305     private Vector parseDimExprs(ParseNode pn) {
306         Vector arglist=new Vector();
307         ParseNode an=pn.getChild("dim_exprs");
308         if (an==null)   /* No argument list */
309             return arglist;
310         ParseNodeVector anv=an.getChildren();
311         for(int i=0;i<anv.size();i++) {
312             arglist.add(parseExpression(anv.elementAt(i)));
313         }
314         return arglist;
315     }
316
317     private Vector parseArgumentList(ParseNode pn) {
318         Vector arglist=new Vector();
319         ParseNode an=pn.getChild("argument_list");
320         if (an==null)   /* No argument list */
321             return arglist;
322         ParseNodeVector anv=an.getChildren();
323         for(int i=0;i<anv.size();i++) {
324             arglist.add(parseExpression(anv.elementAt(i)));
325         }
326         return arglist;
327     }
328
329     private ExpressionNode parseAssignmentExpression(ParseNode pn) {
330         AssignOperation ao=new AssignOperation(pn.getChild("op").getTerminal());
331         ParseNodeVector pnv=pn.getChild("args").getChildren();
332         
333         AssignmentNode an=new AssignmentNode(parseExpression(pnv.elementAt(0)),parseExpression(pnv.elementAt(1)),ao);
334         return an;
335     }
336
337
338     private void parseMethodDecl(ClassDescriptor cn, ParseNode pn) {
339         ParseNode headern=pn.getChild("method_header");
340         ParseNode bodyn=pn.getChild("body");
341         MethodDescriptor md=parseMethodHeader(headern);
342         BlockNode bn=parseBlock(bodyn);
343         cn.addMethod(md);
344         state.addTreeCode(md,bn);
345     }
346
347     private void parseConstructorDecl(ClassDescriptor cn, ParseNode pn) {
348         ParseNode mn=pn.getChild("modifiers");
349         Modifiers m=parseModifiersList(mn);
350         ParseNode cdecl=pn.getChild("constructor_declarator");
351         String name=cdecl.getChild("name").getChild("identifier").getTerminal();
352         MethodDescriptor md=new MethodDescriptor(m, name);
353         ParseNode paramnode=cdecl.getChild("parameters");
354         parseParameterList(md,paramnode);
355         ParseNode bodyn0=pn.getChild("body");
356         ParseNode bodyn=bodyn0.getChild("constructor_body");
357         cn.addMethod(md);
358         if (bodyn!=null) {
359             BlockNode bn=parseBlock(bodyn);
360             state.addTreeCode(md,bn);
361         }
362     }
363
364     public BlockNode parseBlock(ParseNode pn) {
365         if (isEmpty(pn.getTerminal()))
366             return new BlockNode();
367         ParseNode bsn=pn.getChild("block_statement_list");
368         return parseBlockHelper(bsn);
369     }
370     
371     private BlockNode parseBlockHelper(ParseNode pn) {
372         ParseNodeVector pnv=pn.getChildren();
373         BlockNode bn=new BlockNode();
374         for(int i=0;i<pnv.size();i++) {
375             Vector bsv=parseBlockStatement(pnv.elementAt(i));
376             for(int j=0;j<bsv.size();j++) {
377                 bn.addBlockStatement((BlockStatementNode)bsv.get(j));
378             }
379         }
380         return bn;
381     }
382
383     public BlockNode parseSingleBlock(ParseNode pn) {
384         BlockNode bn=new BlockNode();
385         Vector bsv=parseBlockStatement(pn);
386         for(int j=0;j<bsv.size();j++) {
387             bn.addBlockStatement((BlockStatementNode)bsv.get(j));
388         }
389         bn.setStyle(BlockNode.NOBRACES);
390         return bn;
391     }
392
393     public Vector parseBlockStatement(ParseNode pn) {
394         Vector blockstatements=new Vector();
395         if (isNode(pn,"local_variable_declaration")) {
396             TypeDescriptor t=parseTypeDescriptor(pn);
397             ParseNode vn=pn.getChild("variable_declarators_list");
398             ParseNodeVector pnv=vn.getChildren();
399             for(int i=0;i<pnv.size();i++) {
400                 ParseNode vardecl=pnv.elementAt(i);
401
402             
403                 ParseNode tmp=vardecl;
404                 TypeDescriptor arrayt=t;
405                 while (tmp.getChild("single")==null) {
406                     arrayt=arrayt.makeArray(state);
407                     tmp=tmp.getChild("array");
408                 }
409                 String identifier=tmp.getChild("single").getTerminal();
410                 
411                 ParseNode epn=vardecl.getChild("initializer");
412             
413
414                 ExpressionNode en=null;
415                 if (epn!=null)
416                     en=parseExpression(epn.getFirstChild());
417                 
418                 blockstatements.add(new DeclarationNode(new VarDescriptor(arrayt, identifier),en));
419             }
420         } else if (isNode(pn,"nop")) {
421             /* Do Nothing */
422         } else if (isNode(pn,"expression")) {
423             blockstatements.add(new BlockExpressionNode(parseExpression(pn.getFirstChild())));
424         } else if (isNode(pn,"ifstatement")) {
425             blockstatements.add(new IfStatementNode(parseExpression(pn.getChild("condition").getFirstChild()),
426                                        parseSingleBlock(pn.getChild("statement").getFirstChild()),
427                                        pn.getChild("else_statement")!=null?parseSingleBlock(pn.getChild("else_statement").getFirstChild()):null));
428         } else if (isNode(pn,"return")) {
429             if (isEmpty(pn.getTerminal()))
430                 blockstatements.add(new ReturnNode());
431             else {
432                 ExpressionNode en=parseExpression(pn.getFirstChild());
433                 blockstatements.add(new ReturnNode(en));
434             }
435         } else if (isNode(pn,"block_statement_list")) {
436             BlockNode bn=parseBlockHelper(pn);
437             blockstatements.add(new SubBlockNode(bn));
438         } else if (isNode(pn,"empty")) {
439             /* nop */
440         } else if (isNode(pn,"statement_expression_list")) {
441             ParseNodeVector pnv=pn.getChildren();
442             BlockNode bn=new BlockNode();
443             for(int i=0;i<pnv.size();i++) {
444                 ExpressionNode en=parseExpression(pnv.elementAt(i));
445                 blockstatements.add(new BlockExpressionNode(en));
446             }
447             bn.setStyle(BlockNode.EXPRLIST);
448         } else if (isNode(pn,"forstatement")) {
449             BlockNode init=parseSingleBlock(pn.getChild("initializer").getFirstChild());
450             BlockNode update=parseSingleBlock(pn.getChild("update").getFirstChild());
451             ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
452             BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
453             blockstatements.add(new LoopNode(init,condition,update,body));
454         } else if (isNode(pn,"whilestatement")) {
455             ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
456             BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
457             blockstatements.add(new LoopNode(condition,body,LoopNode.WHILELOOP));
458         } else if (isNode(pn,"dowhilestatement")) {
459             ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
460             BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
461             blockstatements.add(new LoopNode(condition,body,LoopNode.DOWHILELOOP));
462         } else {
463             System.out.println("---------------");
464             System.out.println(pn.PPrint(3,true));
465             throw new Error();
466         }
467         return blockstatements;
468     }
469
470     public MethodDescriptor parseMethodHeader(ParseNode pn) {
471         ParseNode mn=pn.getChild("modifiers");
472         Modifiers m=parseModifiersList(mn);
473         
474         ParseNode tn=pn.getChild("returntype");
475         TypeDescriptor returntype;
476         if (tn!=null) 
477             returntype=parseTypeDescriptor(tn);
478         else
479             returntype=new TypeDescriptor(TypeDescriptor.VOID);
480
481         ParseNode pmd=pn.getChild("method_declarator");
482         String name=pmd.getChild("name").getTerminal();
483         MethodDescriptor md=new MethodDescriptor(m, returntype, name);
484        
485         ParseNode paramnode=pmd.getChild("parameters");
486         parseParameterList(md,paramnode);
487         return md;
488     }
489
490     public void parseParameterList(MethodDescriptor md, ParseNode pn) {
491         ParseNode paramlist=pn.getChild("formal_parameter_list");
492         if (paramlist==null)
493             return;
494          ParseNodeVector pnv=paramlist.getChildren();
495          for(int i=0;i<pnv.size();i++) {
496              ParseNode paramn=pnv.elementAt(i);
497              TypeDescriptor type=parseTypeDescriptor(paramn);
498
499              ParseNode tmp=paramn;
500              while (tmp.getChild("single")==null) {
501                  type=type.makeArray(state);
502                  tmp=tmp.getChild("array");
503              }
504              String paramname=tmp.getChild("single").getTerminal();
505             
506              md.addParameter(type,paramname);
507          }
508     }
509
510     public Modifiers parseModifiersList(ParseNode pn) {
511         Modifiers m=new Modifiers();
512         ParseNode modlist=pn.getChild("modifier_list");
513         if (modlist!=null) {
514             ParseNodeVector pnv=modlist.getChildren();
515             for(int i=0;i<pnv.size();i++) {
516                 ParseNode modn=pnv.elementAt(i);
517                 if (isNode(modn,"public"))
518                     m.addModifier(Modifiers.PUBLIC);
519                 if (isNode(modn,"protected"))
520                     m.addModifier(Modifiers.PROTECTED);
521                 if (isNode(modn,"private"))
522                     m.addModifier(Modifiers.PRIVATE);
523                 if (isNode(modn,"static"))
524                     m.addModifier(Modifiers.STATIC);
525                 if (isNode(modn,"final"))
526                     m.addModifier(Modifiers.FINAL);
527                 if (isNode(modn,"native"))
528                     m.addModifier(Modifiers.NATIVE);
529             }
530         }
531         return m;
532     }
533
534     private boolean isNode(ParseNode pn, String label) {
535         if (pn.getLabel().equals(label))
536             return true;
537         else return false;
538     }
539
540     private static boolean isEmpty(ParseNode pn) {
541         if (pn.getLabel().equals("empty"))
542             return true;
543         else
544             return false;
545     }
546
547     private static boolean isEmpty(String s) {
548         if (s.equals("empty"))
549             return true;
550         else
551             return false;
552     }
553
554     /** Throw an exception if something is unexpected */
555     private void check(ParseNode pn, String label) {
556         if (pn == null) {
557             throw new Error(pn+ "IE: Expected '" + label + "', got null");
558         }
559         if (! pn.getLabel().equals(label)) {
560             throw new Error(pn+ "IE: Expected '" + label + "', got '"+pn.getLabel()+"'");
561         }
562     }
563 }