Generate code to compute the sum.
[repair.git] / Repair / RepairCompiler / MCC / IR / SumExpr.java
1 package MCC.IR;
2
3 import java.util.*;
4
5 public class SumExpr extends Expr {
6
7     SetDescriptor sd;
8     RelationDescriptor rd;
9
10
11     public SumExpr(SetDescriptor sd, RelationDescriptor rd) {
12         if (sd == null||rd==null) {
13             throw new NullPointerException();
14         }
15         this.sd=sd;
16         this.rd=rd;
17     }
18
19     public String name() {
20         return "sum("+sd.toString()+"."+rd.toString()+")";
21     }
22
23     public boolean equals(Map remap, Expr e) {
24         if (e==null||!(e instanceof SumExpr))
25             return false;
26         SumExpr se=(SumExpr)e;
27         return (se.sd==sd)&&(se.rd==rd);
28     }
29
30     public boolean usesDescriptor(Descriptor d) {
31         return (sd==d)||(rd==d);
32     }
33
34     public Set useDescriptor(Descriptor d) {
35         HashSet newset=new HashSet();
36         if ((d==sd)||(d==rd))
37             newset.add(this);
38         return newset;
39     }
40
41     public Descriptor getDescriptor() {
42         throw new Error("Sum shouldn't appear on left hand side!");
43     }
44
45     public boolean inverted() {
46         return false;
47     }
48
49     public Set getRequiredDescriptors() {
50         HashSet v=new HashSet();
51         v.add(sd);
52         v.add(rd);
53         return v;
54     }
55
56     public void generate(CodeWriter writer, VarDescriptor dest) {
57         writer.outputline("int "+dest.getSafeSymbol()+"=0;");
58
59         VarDescriptor itvd=VarDescriptor.makeNew("iterator");
60         writer.outputline("SimpleIterator "+itvd.getSafeSymbol()+";");
61         writer.outputline(sd.getSafeSymbol()+"_hash->iterator("+itvd.getSafeSymbol()+");");
62         writer.outputline("while ("+itvd.getSafeSymbol()+".hasNext()) {");
63         VarDescriptor keyvd=VarDescriptor.makeNew("key");
64         writer.outputline("int "+keyvd.getSafeSymbol()+"="+itvd.getSafeSymbol()+".next();");
65         VarDescriptor tmpvar=VarDescriptor.makeNew("tmp");
66         writer.outputline("int "+tmpvar.getSafeSymbol()+";");
67         writer.outputline(rd.getSafeSymbol()+ "_hash->get("+keyvd.getSafeSymbol()+","+tmpvar.getSafeSymbol()+");");
68         writer.outputline(dest.getSafeSymbol()+"+="+tmpvar.getSafeSymbol()+";");
69         writer.outputline("}");
70     }
71
72     public void prettyPrint(PrettyPrinter pp) {
73         pp.output("sum(");
74         pp.output(sd.toString());
75         pp.output(".");
76         pp.output(rd.toString());
77         pp.output(")");
78     }
79
80     public TypeDescriptor typecheck(SemanticAnalyzer sa) {
81         this.td = ReservedTypeDescriptor.INT;
82         return this.td;
83     }
84
85     public Set getInversedRelations() {
86         return new HashSet();
87     }
88
89 }