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