Random small changes...
[repair.git] / Repair / RepairCompiler / MCC / IR / Termination.java
1 package MCC.IR;
2 import java.util.*;
3 import java.io.*;
4 import MCC.State;
5 import MCC.Compiler;
6
7 public class Termination {
8     HashSet conjunctions;
9     Hashtable conjunctionmap;
10
11     HashSet abstractrepair;
12     HashSet abstractrepairadd;
13
14     HashSet updatenodes;
15     HashSet consequencenodes;
16
17     HashSet scopenodes;
18     Hashtable scopesatisfy;
19     Hashtable scopefalsify;
20     Hashtable consequence;
21     Hashtable abstractadd;
22     Hashtable abstractremove;
23     Hashtable conjtonodemap;
24     Hashtable predtoabstractmap;
25     Set removedset;
26     ComputeMaxSize maxsize;
27     State state;
28     AbstractInterferes abstractinterferes;
29     ConstraintDependence constraintdependence;
30     ExactSize exactsize;
31     ArrayAnalysis arrayanalysis;
32     Sources sources;
33
34     public Termination(State state) {
35         this.state=state;
36         conjunctions=new HashSet();
37         conjunctionmap=new Hashtable();
38         abstractrepair=new HashSet();
39         abstractrepairadd=new HashSet();
40         scopenodes=new HashSet();
41         scopesatisfy=new Hashtable();
42         scopefalsify=new Hashtable();
43         consequence=new Hashtable();
44         updatenodes=new HashSet();
45         consequencenodes=new HashSet();
46         abstractadd=new Hashtable();
47         abstractremove=new Hashtable();
48         conjtonodemap=new Hashtable();
49         predtoabstractmap=new Hashtable();
50         if (!Compiler.REPAIR)
51             return;
52         
53
54         for(int i=0;i<state.vRules.size();i++)
55             System.out.println(state.vRules.get(i));
56         for(int i=0;i<state.vConstraints.size();i++)
57             System.out.println(state.vConstraints.get(i));
58
59         sources=new Sources(state);
60         maxsize=new ComputeMaxSize(state);
61         exactsize=new ExactSize(state);
62         arrayanalysis=new ArrayAnalysis(state,this);
63
64         abstractinterferes=new AbstractInterferes(this);
65         generateconjunctionnodes();
66         constraintdependence=new ConstraintDependence(state,this);
67
68         generatescopenodes();
69         generaterepairnodes();
70         generatedatastructureupdatenodes();
71         generatecompensationnodes();
72
73         generateabstractedges();
74         generatescopeedges();
75         generateupdateedges();
76
77
78         HashSet superset=new HashSet();
79         superset.addAll(conjunctions);
80         HashSet closureset=new HashSet();
81
82         GraphNode.computeclosure(superset,closureset);
83         try {
84             GraphNode.DOTVisitor.visit(new FileOutputStream("graph.dot"),superset);
85         } catch (Exception e) {
86             e.printStackTrace();
87             System.exit(-1);
88         }
89         for(Iterator it=updatenodes.iterator();it.hasNext();) {
90             GraphNode gn=(GraphNode)it.next();
91             TermNode tn=(TermNode)gn.getOwner();
92             MultUpdateNode mun=tn.getUpdate();
93             System.out.println(gn.getTextLabel());
94             System.out.println(mun.toString());
95         }
96         GraphAnalysis ga=new GraphAnalysis(this);
97         removedset=ga.doAnalysis();
98         if (removedset==null) {
99             System.out.println("Can't generate terminating repair algorithm!");
100             System.exit(-1);
101         }
102         constraintdependence.traversedependences(this);
103
104         System.out.println("Removing:");
105         for(Iterator it=removedset.iterator();it.hasNext();) {
106             GraphNode gn=(GraphNode)it.next();
107             System.out.println(gn.getTextLabel());
108         }
109
110         superset=new HashSet();
111         superset.addAll(conjunctions);
112         superset.removeAll(removedset);
113         GraphNode.computeclosure(superset,removedset);
114         try {
115             GraphNode.DOTVisitor.visit(new FileOutputStream("graphfinal.dot"),superset);
116         } catch (Exception e) {
117             e.printStackTrace();
118             System.exit(-1);
119         }
120
121     }
122
123
124     /** This method generates a node for each conjunction in the DNF
125      * form of each constraint.  It also converts the quantifiers into
126      * conjunctions also - constraints can be satisfied by removing
127      * items from the sets and relations they are quantified over */
128
129     void generateconjunctionnodes() {
130         Vector constraints=state.vConstraints;
131         // Constructs conjunction nodes
132         for(int i=0;i<constraints.size();i++) {
133             Constraint c=(Constraint)constraints.get(i);
134             DNFConstraint dnf=c.dnfconstraint;
135             for(int j=0;j<dnf.size();j++) {
136                 TermNode tn=new TermNode(c,dnf.get(j));
137                 GraphNode gn=new GraphNode("Conj"+i+"A"+j,
138                                            "Conj ("+i+","+j+") "+dnf.get(j).name()
139                                            ,tn);
140                 conjunctions.add(gn);
141                 if (!conjunctionmap.containsKey(c))
142                     conjunctionmap.put(c,new HashSet());
143                 ((Set)conjunctionmap.get(c)).add(gn);
144                 conjtonodemap.put(dnf.get(j),gn);
145
146
147             }
148             // Construct quantifier "conjunction" nodes
149             for(int j=0;j<c.numQuantifiers();j++) {
150                 Quantifier q=c.getQuantifier(j);
151                 if (q instanceof SetQuantifier) {
152                     SetQuantifier sq=(SetQuantifier)q;
153                     VarExpr ve=new VarExpr(sq.getVar());
154                     InclusionPredicate ip=new InclusionPredicate(ve,new SetExpr(sq.getSet()));
155                     DNFConstraint dconst=new DNFConstraint(ip);
156                     dconst=dconst.not();
157                     TermNode tn=new TermNode(c,dconst.get(0));
158                     GraphNode gn=new GraphNode("Conj"+i+"AQ"+j,
159                                                "Conj ("+i+","+j+") "+dconst.get(0).name()
160                                                ,tn);
161                     conjunctions.add(gn);
162                     if (!conjunctionmap.containsKey(c))
163                         conjunctionmap.put(c,new HashSet());
164                     ((Set)conjunctionmap.get(c)).add(gn);
165                     conjtonodemap.put(dconst.get(0),gn);
166
167                 } else if (q instanceof RelationQuantifier) {
168                     RelationQuantifier rq=(RelationQuantifier)q;
169                     VarExpr ve=new VarExpr(rq.y);
170                     InclusionPredicate ip=new InclusionPredicate(ve,new ImageSetExpr(rq.x,rq.getRelation()));
171                     DNFConstraint dconst=new DNFConstraint(ip);
172                     dconst=dconst.not();
173                     TermNode tn=new TermNode(c,dconst.get(0));
174                     GraphNode gn=new GraphNode("Conj"+i+"AQ"+j,
175                                                "Conj ("+i+","+j+") "+dconst.get(0).name()
176                                                ,tn);
177                     conjunctions.add(gn);
178                     if (!conjunctionmap.containsKey(c))
179                         conjunctionmap.put(c,new HashSet());
180                     ((Set)conjunctionmap.get(c)).add(gn);
181                     conjtonodemap.put(dconst.get(0),gn);
182
183                 }
184             }
185         }
186     }
187
188     void generateupdateedges() {
189         for(Iterator updateiterator=updatenodes.iterator();updateiterator.hasNext();) {
190             GraphNode gn=(GraphNode)updateiterator.next();
191             TermNode tn=(TermNode)gn.getOwner();
192             MultUpdateNode mun=tn.getUpdate();
193             for(int i=0;i<mun.numUpdates();i++) {
194                 UpdateNode un=mun.getUpdate(i);
195                 for(int j=0;j<un.numUpdates();j++) {
196                     Updates u=un.getUpdate(j);
197                     if (u.getType()==Updates.ABSTRACT) {
198                         Expr e=u.getLeftExpr();
199                         boolean negated=u.negate;
200                         if (e instanceof TupleOfExpr) {
201                             TupleOfExpr toe=(TupleOfExpr)e;
202                             if (negated) {
203                                 GraphNode agn=(GraphNode)abstractremove.get(toe.relation);
204                                 GraphNode.Edge edge=new GraphNode.Edge("requires",agn);
205                                 gn.addEdge(edge);
206                             } else {
207                                 GraphNode agn=(GraphNode)abstractadd.get(toe.relation);
208                                 GraphNode.Edge edge=new GraphNode.Edge("requires",agn);
209                                 gn.addEdge(edge);
210                             }
211                         } else if (e instanceof ElementOfExpr) {
212                             ElementOfExpr eoe=(ElementOfExpr)e;
213                             if (negated) {
214                                 GraphNode agn=(GraphNode)abstractremove.get(eoe.set);
215                                 GraphNode.Edge edge=new GraphNode.Edge("requires",agn);
216                                 gn.addEdge(edge);
217                             } else {
218                                 GraphNode agn=(GraphNode)abstractadd.get(eoe.set);
219                                 GraphNode.Edge edge=new GraphNode.Edge("requires",agn);
220                                 gn.addEdge(edge);
221                             }
222                         } else throw new Error("Unrecognized Abstract Update");
223                     }
224                 }
225             }
226
227             /* Cycle through the rules to look for possible conflicts */
228             for(int i=0;i<state.vRules.size();i++) {
229                 Rule r=(Rule) state.vRules.get(i);  
230                 if (ConcreteInterferes.interferes(mun,r,true)) {
231                     GraphNode scopenode=(GraphNode)scopesatisfy.get(r);
232                     GraphNode.Edge e=new GraphNode.Edge("interferes",scopenode);
233                     gn.addEdge(e);
234                 }
235                 if (ConcreteInterferes.interferes(mun,r,false)) {
236                     GraphNode scopenode=(GraphNode)scopefalsify.get(r);
237                     GraphNode.Edge e=new GraphNode.Edge("interferes",scopenode);
238                     gn.addEdge(e);
239                 }
240             }
241         }
242     }
243
244     void generateabstractedges() {
245         for(Iterator absiterator=abstractrepair.iterator();absiterator.hasNext();) {
246             GraphNode gn=(GraphNode)absiterator.next();
247             TermNode tn=(TermNode)gn.getOwner();
248             AbstractRepair ar=(AbstractRepair)tn.getAbstract();
249         
250             for(Iterator conjiterator=conjunctions.iterator();conjiterator.hasNext();) {
251                 GraphNode gn2=(GraphNode)conjiterator.next();
252                 TermNode tn2=(TermNode)gn2.getOwner();
253                 Conjunction conj=tn2.getConjunction();
254                 Constraint cons=tn2.getConstraint();
255
256                 for(int i=0;i<conj.size();i++) {
257                     DNFPredicate dp=conj.get(i);
258                     if (AbstractInterferes.interferes(ar,cons)||
259                         abstractinterferes.interferes(ar,dp)) {
260                         GraphNode.Edge e=new GraphNode.Edge("interferes",gn2);
261                         gn.addEdge(e);
262                         break;
263                     }
264                 }
265             }
266
267             for(Iterator scopeiterator=scopenodes.iterator();scopeiterator.hasNext();) {
268                 GraphNode gn2=(GraphNode)scopeiterator.next();
269                 TermNode tn2=(TermNode)gn2.getOwner();
270                 ScopeNode sn2=tn2.getScope();
271                 if (AbstractInterferes.interferes(ar,sn2.getRule(),sn2.getSatisfy())) {
272                     GraphNode.Edge e=new GraphNode.Edge("interferes",gn2);
273                     gn.addEdge(e);
274                 }
275             }
276         }
277     }
278
279     void generatescopenodes() {
280         for(int i=0;i<state.vRules.size();i++) {
281             Rule r=(Rule) state.vRules.get(i);
282             ScopeNode satisfy=new ScopeNode(r,true);
283             TermNode tnsatisfy=new TermNode(satisfy);
284             GraphNode gnsatisfy=new GraphNode("SatisfyRule"+i,tnsatisfy);
285             ConsequenceNode cnsatisfy=new ConsequenceNode();
286             TermNode ctnsatisfy=new TermNode(cnsatisfy);
287             GraphNode cgnsatisfy=new GraphNode("ConseqSatisfyRule"+i,ctnsatisfy);
288             consequence.put(satisfy,cgnsatisfy);
289             GraphNode.Edge esat=new GraphNode.Edge("consequencesatisfy"+i,cgnsatisfy);
290             gnsatisfy.addEdge(esat);
291             consequencenodes.add(cgnsatisfy);
292             scopesatisfy.put(r,gnsatisfy);
293             scopenodes.add(gnsatisfy);
294
295             ScopeNode falsify=new ScopeNode(r,false);
296             TermNode tnfalsify=new TermNode(falsify);
297             GraphNode gnfalsify=new GraphNode("FalsifyRule"+i,tnfalsify);
298             ConsequenceNode cnfalsify=new ConsequenceNode();
299             TermNode ctnfalsify=new TermNode(cnfalsify);
300             GraphNode cgnfalsify=new GraphNode("ConseqFalsifyRule"+i,ctnfalsify);
301             consequence.put(falsify,cgnfalsify);
302             GraphNode.Edge efals=new GraphNode.Edge("consequencefalsify"+i,cgnfalsify);
303             gnfalsify.addEdge(efals);
304             consequencenodes.add(cgnfalsify);
305             scopefalsify.put(r,gnfalsify);
306             scopenodes.add(gnfalsify);
307         }
308     }
309     
310     void generatescopeedges() {
311         for(Iterator scopeiterator=scopenodes.iterator();scopeiterator.hasNext();) {
312             GraphNode gn=(GraphNode)scopeiterator.next();
313             TermNode tn=(TermNode)gn.getOwner();
314             ScopeNode sn=tn.getScope();
315             
316             /* Interference edges with conjunctions */
317             for(Iterator conjiterator=conjunctions.iterator();conjiterator.hasNext();) {
318                 GraphNode gn2=(GraphNode)conjiterator.next();
319                 TermNode tn2=(TermNode)gn2.getOwner();
320                 Conjunction conj=tn2.getConjunction();
321                 Constraint constr=tn2.getConstraint();
322                 for(int i=0;i<conj.size();i++) {
323                     DNFPredicate dp=conj.get(i);
324                     if (abstractinterferes.interferes(sn,dp)||
325                         AbstractInterferes.interferes(sn.getDescriptor(),sn.getSatisfy(),constr)) {
326                         GraphNode.Edge e=new GraphNode.Edge("interferes",gn2);
327                         GraphNode gnconseq=(GraphNode)consequence.get(sn);
328                         gnconseq.addEdge(e);
329                         break;
330                     }
331                 }
332             }
333
334             /* Now see if this could effect other model defintion rules */
335             for(int i=0;i<state.vRules.size();i++) {
336                 Rule r=(Rule) state.vRules.get(i);
337                 if (AbstractInterferes.interferes(sn.getDescriptor(),sn.getSatisfy(),r,true)) {
338                     GraphNode scopenode=(GraphNode)scopesatisfy.get(r);
339                     GraphNode.Edge e=new GraphNode.Edge("interferes",scopenode);
340                     GraphNode gnconseq=(GraphNode)consequence.get(sn);
341                     gnconseq.addEdge(e);
342                 }
343                 if (AbstractInterferes.interferes(sn.getDescriptor(),sn.getSatisfy(),r,false)) {
344                     GraphNode scopenode=(GraphNode)scopefalsify.get(r);
345                     GraphNode.Edge e=new GraphNode.Edge("interferes",scopenode);
346                     GraphNode gnconseq=(GraphNode)consequence.get(sn);
347                     gnconseq.addEdge(e);
348                 }
349             }
350         }
351     }
352
353     /** This method generates the abstract repair nodes. */
354     void generaterepairnodes() {
355         /* Generate repairs of conjunctions */
356         for(Iterator conjiterator=conjunctions.iterator();conjiterator.hasNext();) {
357             GraphNode gn=(GraphNode)conjiterator.next();
358             TermNode tn=(TermNode)gn.getOwner();
359             Conjunction conj=tn.getConjunction();
360             for(int i=0;i<conj.size();i++) {
361                 DNFPredicate dp=conj.get(i);
362                 int[] array=dp.getPredicate().getRepairs(dp.isNegated(),this);
363                 Descriptor d=dp.getPredicate().getDescriptor();
364                 for(int j=0;j<array.length;j++) {
365                     AbstractRepair ar=new AbstractRepair(dp,array[j],d);
366                     TermNode tn2=new TermNode(ar);
367                     GraphNode gn2=new GraphNode(gn.getLabel()+"A"+i+"B"+ar.type(),gn.getTextLabel()+" #"+i+" "+ar.type(),tn2);
368                     GraphNode.Edge e=new GraphNode.Edge("abstract",gn2);
369                     gn.addEdge(e);
370                     if (!predtoabstractmap.containsKey(dp))
371                         predtoabstractmap.put(dp,new HashSet());
372                     ((Set)predtoabstractmap.get(dp)).add(gn2);
373                     abstractrepair.add(gn2);
374                 }
375             }
376         }
377         /* Generate additional abstract repairs */
378         Vector setdescriptors=state.stSets.getAllDescriptors();
379         for(int i=0;i<setdescriptors.size();i++) {
380             SetDescriptor sd=(SetDescriptor)setdescriptors.get(i);
381
382             VarExpr ve=new VarExpr("DUMMY");
383             InclusionPredicate ip=new InclusionPredicate(ve,new SetExpr(sd));
384             DNFPredicate tp=new DNFPredicate(false,ip);
385             AbstractRepair ar=new AbstractRepair(tp, AbstractRepair.ADDTOSET, sd);
386             TermNode tn=new TermNode(ar);
387             GraphNode gn=new GraphNode("AbstractAddSetRule"+i,tn);
388             if (!predtoabstractmap.containsKey(tp))
389                 predtoabstractmap.put(tp,new HashSet());
390             ((Set)predtoabstractmap.get(tp)).add(gn);
391             abstractrepair.add(gn);
392             abstractrepairadd.add(gn);
393             abstractadd.put(sd,gn);
394             
395             DNFPredicate tp2=new DNFPredicate(true,ip);
396             AbstractRepair ar2=new AbstractRepair(tp2, AbstractRepair.REMOVEFROMSET, sd);
397             TermNode tn2=new TermNode(ar2);
398             GraphNode gn2=new GraphNode("AbstractRemSetRule"+i,tn2);
399             if (!predtoabstractmap.containsKey(tp2))
400                 predtoabstractmap.put(tp2,new HashSet());
401             ((Set)predtoabstractmap.get(tp2)).add(gn2);
402             abstractrepair.add(gn2);
403             abstractrepairadd.add(gn2);
404             abstractremove.put(sd,gn2);
405         }
406
407         Vector relationdescriptors=state.stRelations.getAllDescriptors();
408         for(int i=0;i<relationdescriptors.size();i++) {
409             RelationDescriptor rd=(RelationDescriptor)relationdescriptors.get(i);
410             VarDescriptor vd1=new VarDescriptor("DUMMY1");
411             VarExpr ve2=new VarExpr("DUMMY2");
412
413             InclusionPredicate ip=new InclusionPredicate(ve2,new ImageSetExpr(vd1, rd));
414             
415             DNFPredicate tp=new DNFPredicate(false,ip);
416             AbstractRepair ar=new AbstractRepair(tp, AbstractRepair.ADDTORELATION, rd);
417             TermNode tn=new TermNode(ar);
418             GraphNode gn=new GraphNode("AbstractAddRelRule"+i,tn);
419             if (!predtoabstractmap.containsKey(tp))
420                 predtoabstractmap.put(tp,new HashSet());
421             ((Set)predtoabstractmap.get(tp)).add(gn);
422             abstractrepair.add(gn);
423             abstractrepairadd.add(gn);
424             abstractadd.put(rd,gn);
425             
426             DNFPredicate tp2=new DNFPredicate(true,ip);
427             AbstractRepair ar2=new AbstractRepair(tp2, AbstractRepair.REMOVEFROMRELATION, rd);
428             TermNode tn2=new TermNode(ar2);
429             GraphNode gn2=new GraphNode("AbstractRemRelRule"+i,tn2);
430             if (!predtoabstractmap.containsKey(tp2))
431                 predtoabstractmap.put(tp2,new HashSet());
432             ((Set)predtoabstractmap.get(tp2)).add(gn2);
433             abstractrepair.add(gn2);
434             abstractrepairadd.add(gn2);
435             abstractremove.put(rd,gn2);
436         }
437     }
438
439     int compensationcount=0;
440     void generatecompensationnodes() {
441         for(int i=0;i<state.vRules.size();i++) {
442             Rule r=(Rule) state.vRules.get(i);
443             Vector possiblerules=new Vector();
444
445             for(int j=0;j<(r.numQuantifiers()+r.getDNFNegGuardExpr().size());j++) {
446                 GraphNode gn=(GraphNode)scopesatisfy.get(r);
447                 TermNode tn=(TermNode) gn.getOwner();
448                 ScopeNode sn=tn.getScope();
449                 MultUpdateNode mun=new MultUpdateNode(sn);
450                 TermNode tn2=new TermNode(mun);
451                 GraphNode gn2=new GraphNode("CompRem"+compensationcount,tn2);
452                 UpdateNode un=new UpdateNode(r);
453
454                 if (j<r.numQuantifiers()) {
455                     /* Remove quantifier */
456                     Quantifier q=r.getQuantifier(j);
457                     if (q instanceof RelationQuantifier) {
458                         RelationQuantifier rq=(RelationQuantifier)q;
459                         TupleOfExpr toe=new TupleOfExpr(new VarExpr(rq.x),new VarExpr(rq.y),rq.relation);
460                         toe.td=ReservedTypeDescriptor.INT;
461                         Updates u=new Updates(toe,true);
462                         un.addUpdate(u);
463                         if (abstractremove.containsKey(rq.relation)) {
464                             GraphNode agn=(GraphNode)abstractremove.get(rq.relation);
465                             GraphNode.Edge e=new GraphNode.Edge("requires",agn);
466                             gn2.addEdge(e);
467                         } else {
468                             continue; /* Abstract repair doesn't exist */
469                         }
470                     } else if (q instanceof SetQuantifier) {
471                         SetQuantifier sq=(SetQuantifier)q;
472                         ElementOfExpr eoe=new ElementOfExpr(new VarExpr(sq.var),sq.set);
473                         eoe.td=ReservedTypeDescriptor.INT;
474                         Updates u=new Updates(eoe,true);
475                         un.addUpdate(u);
476                         if (abstractremove.containsKey(sq.set)) {
477                             GraphNode agn=(GraphNode)abstractremove.get(sq.set);
478                             GraphNode.Edge e=new GraphNode.Edge("requires",agn);
479                             gn2.addEdge(e);
480                         } else {
481                             continue; /* Abstract repair doesn't exist */
482                         }
483                     } else {
484                         continue;
485                     }
486                 } else {
487                     /* Negate conjunction */
488                     int c=j-r.numQuantifiers();
489                     if (!processconjunction(un,r.getDNFNegGuardExpr().get(c))) {
490                         continue;
491                     }
492                 }
493                 if (!un.checkupdates()) /* Make sure we have a good update */
494                     continue;
495                 
496                 mun.addUpdate(un);
497                 GraphNode.Edge e=new GraphNode.Edge("abstract"+compensationcount,gn2);
498                 compensationcount++;
499                 gn.addEdge(e);
500                 updatenodes.add(gn2);
501             }
502         }
503     }
504
505     void generatedatastructureupdatenodes() {
506         for(Iterator absiterator=abstractrepair.iterator();absiterator.hasNext();) {
507             GraphNode gn=(GraphNode)absiterator.next();
508             TermNode tn=(TermNode) gn.getOwner();
509             AbstractRepair ar=tn.getAbstract();
510             if (ar.getType()==AbstractRepair.ADDTOSET) {
511                 generateaddtosetrelation(gn,ar);
512             } else if (ar.getType()==AbstractRepair.REMOVEFROMSET) {
513                 generateremovefromsetrelation(gn,ar);
514             } else if (ar.getType()==AbstractRepair.ADDTORELATION) {
515                 generateaddtosetrelation(gn,ar);
516             } else if (ar.getType()==AbstractRepair.REMOVEFROMRELATION) {
517                 generateremovefromsetrelation(gn,ar);
518             } else if (ar.getType()==AbstractRepair.MODIFYRELATION) {
519                 /* Generate remove/add pairs */
520                 generateremovefromsetrelation(gn,ar);
521                 generateaddtosetrelation(gn,ar);
522                 /* Generate atomic modify */
523                 generatemodifyrelation(gn,ar);
524             }
525         }
526     }
527
528
529     /** This method generates concrete data structure updates which
530      * remove an object (or tuple) from a set (or relation).*/
531
532     int removefromcount=0;
533     void generateremovefromsetrelation(GraphNode gn,AbstractRepair ar) {
534         /* Construct the set of all rules which could add something to the given set or relation */
535
536         Vector possiblerules=new Vector();
537         for(int i=0;i<state.vRules.size();i++) {
538             Rule r=(Rule) state.vRules.get(i);
539             if ((r.getInclusion() instanceof SetInclusion)&&
540                 (ar.getDescriptor()==((SetInclusion)r.getInclusion()).getSet()))
541                 possiblerules.add(r);
542             if ((r.getInclusion() instanceof RelationInclusion)&&
543                 (ar.getDescriptor()==((RelationInclusion)r.getInclusion()).getRelation()))
544                 possiblerules.add(r);
545         }
546         if (possiblerules.size()==0)
547             return;
548         
549         /* Loop through different ways of falsifying each of these rules */
550         int[] count=new int[possiblerules.size()];
551         while(remains(count,possiblerules,true)) {
552             MultUpdateNode mun=new MultUpdateNode(ar,MultUpdateNode.REMOVE);
553             TermNode tn=new TermNode(mun);
554             GraphNode gn2=new GraphNode("UpdateRem"+removefromcount,tn);
555
556             boolean goodflag=true;
557             for(int i=0;i<possiblerules.size();i++) {
558                 Rule r=(Rule)possiblerules.get(i);
559                 UpdateNode un=new UpdateNode(r);
560
561                 if (count[i]<r.numQuantifiers()) {
562                     /* Remove quantifier */
563                     Quantifier q=r.getQuantifier(count[i]);
564                     if (q instanceof RelationQuantifier) {
565                         RelationQuantifier rq=(RelationQuantifier)q;
566                         TupleOfExpr toe=new TupleOfExpr(new VarExpr(rq.x),new VarExpr(rq.y),rq.relation);
567                         toe.td=ReservedTypeDescriptor.INT;
568                         Updates u=new Updates(toe,true);
569                         un.addUpdate(u);
570                         if (abstractremove.containsKey(rq.relation)) {
571                             GraphNode agn=(GraphNode)abstractremove.get(rq.relation);
572                             GraphNode.Edge e=new GraphNode.Edge("requires",agn);
573                             gn2.addEdge(e);
574                         } else {
575                             goodflag=false;break; /* Abstract repair doesn't exist */
576                         }
577                     } else if (q instanceof SetQuantifier) {
578                         SetQuantifier sq=(SetQuantifier)q;
579                         ElementOfExpr eoe=new ElementOfExpr(new VarExpr(sq.var),sq.set);
580                         eoe.td=ReservedTypeDescriptor.INT;
581                         Updates u=new Updates(eoe,true);
582                         un.addUpdate(u);
583                         if (abstractremove.containsKey(sq.set)) {
584                             GraphNode agn=(GraphNode)abstractremove.get(sq.set);
585                             GraphNode.Edge e=new GraphNode.Edge("requires",agn);
586                             gn2.addEdge(e);
587                         } else {
588                             goodflag=false;break; /* Abstract repair doesn't exist */
589                         }
590                     } else {goodflag=false;break;}
591                 } else {
592                     int c=count[i]-r.numQuantifiers();
593                     if (!processconjunction(un,r.getDNFNegGuardExpr().get(c))) {
594                         goodflag=false;break;
595                     }
596                 }
597                 if (!un.checkupdates()) {
598                     goodflag=false;
599                     break;
600                 }
601                 mun.addUpdate(un);
602             }
603             if (goodflag) {
604                 GraphNode.Edge e=new GraphNode.Edge("abstract"+removefromcount,gn2);
605                 removefromcount++;
606                 gn.addEdge(e);
607                 updatenodes.add(gn2);
608             }
609             increment(count,possiblerules,true);
610         }
611     }
612
613     /** This method increments to the next possibility. */
614
615     static private void increment(int count[], Vector rules,boolean isremove) {
616         count[0]++;
617         for(int i=0;i<(rules.size()-1);i++) {
618             int num=isremove?(((Rule)rules.get(i)).numQuantifiers()+(((Rule)rules.get(i)).getDNFNegGuardExpr().size())):((Rule)rules.get(i)).getDNFGuardExpr().size();
619             if (count[i]>=num) {
620                 count[i+1]++;
621                 count[i]=0;
622             } else break;
623         }
624     }
625
626
627     /** This method test if there remain any possibilities to loop
628      * through. */
629     static private boolean remains(int count[], Vector rules, boolean isremove) {
630         for(int i=0;i<rules.size();i++) {
631             int num=isremove?(((Rule)rules.get(i)).numQuantifiers()+(((Rule)rules.get(i)).getDNFNegGuardExpr().size())):((Rule)rules.get(i)).getDNFGuardExpr().size();
632             if (count[i]>=num) {
633                 return false;
634             }
635         }
636         return true;
637     }
638
639     /** This method generates data structure updates to implement the
640      *  abstract atomic modification specified by ar. */
641
642     int modifycount=0;
643     void generatemodifyrelation(GraphNode gn, AbstractRepair ar) {
644         RelationDescriptor rd=(RelationDescriptor)ar.getDescriptor();
645         ExprPredicate exprPredicate=(ExprPredicate)ar.getPredicate().getPredicate();
646         boolean inverted=exprPredicate.inverted();
647         int leftindex=0;
648         int rightindex=1;
649         if (inverted)
650             leftindex=2;
651         else 
652             rightindex=2;
653
654         // construct set of possible rules
655         Vector possiblerules=new Vector();
656         for(int i=0;i<state.vRules.size();i++) {
657             Rule r=(Rule) state.vRules.get(i);
658             if ((r.getInclusion() instanceof RelationInclusion)&&
659                 (rd==((RelationInclusion)r.getInclusion()).getRelation()))
660                 possiblerules.add(r);
661         }
662         if (possiblerules.size()==0)
663             return;
664
665         // increment through this set
666         int[] count=new int[possiblerules.size()];
667         while(remains(count,possiblerules,false)) {
668             MultUpdateNode mun=new MultUpdateNode(ar,MultUpdateNode.MODIFY);
669             TermNode tn=new TermNode(mun);
670             GraphNode gn2=new GraphNode("UpdateMod"+removefromcount,tn);
671
672             boolean goodflag=true;
673             for(int i=0;i<possiblerules.size();i++) {
674                 Rule r=(Rule)possiblerules.get(i);
675                 UpdateNode un=new UpdateNode(r);
676                 
677                 int c=count[i];
678                 if (!processconjunction(un,r.getDNFGuardExpr().get(c))) {
679                     goodflag=false;break;
680                 }
681                 RelationInclusion ri=(RelationInclusion)r.getInclusion();
682                 if (!(ri.getLeftExpr() instanceof VarExpr)) {
683                     if (ri.getLeftExpr().isValue()) {
684                         Updates up=new Updates(ri.getLeftExpr(),leftindex);
685                         un.addUpdate(up);
686                     } else
687                         goodflag=false;
688                 } else {
689                     VarDescriptor vd=((VarExpr)ri.getLeftExpr()).getVar();
690                     if (vd.isGlobal()) {
691                         Updates up=new Updates(ri.getLeftExpr(),leftindex);
692                         un.addUpdate(up);
693                     } else if (inverted)
694                         goodflag=false;
695                 }
696                 if (!(ri.getRightExpr() instanceof VarExpr)) {
697                     if (ri.getRightExpr().isValue()) {
698                         Updates up=new Updates(ri.getRightExpr(),rightindex);
699                         un.addUpdate(up);
700                     } else
701                         goodflag=false;
702                 } else {
703                     VarDescriptor vd=((VarExpr)ri.getRightExpr()).getVar();
704                     if (vd.isGlobal()) {
705                         Updates up=new Updates(ri.getRightExpr(),rightindex);
706                         un.addUpdate(up);
707                     } else if (!inverted) 
708                         goodflag=false;
709                 }
710                                 
711                 if (!un.checkupdates()) {
712                     goodflag=false;
713                     break;
714                 }
715                 mun.addUpdate(un);
716             }
717             if (goodflag) {
718                 GraphNode.Edge e=new GraphNode.Edge("abstract"+modifycount,gn2);
719                 modifycount++;
720                 gn.addEdge(e);
721                 updatenodes.add(gn2);
722             }
723             increment(count,possiblerules,false);
724         }
725     }
726
727     /** Generate concrete data structure update to add an object(or
728      * tuple) to a set (or relation). */
729
730     static int addtocount=0;
731     void generateaddtosetrelation(GraphNode gn, AbstractRepair ar) {
732         for(int i=0;i<state.vRules.size();i++) {
733             Rule r=(Rule) state.vRules.get(i);
734             /* See if this is a good rule*/
735             if ((r.getInclusion() instanceof SetInclusion&&
736                  ar.getDescriptor()==((SetInclusion)r.getInclusion()).getSet())||
737                 (r.getInclusion() instanceof RelationInclusion&&
738                  ar.getDescriptor()==((RelationInclusion)r.getInclusion()).getRelation())) {
739                 
740                 /* First solve for quantifiers */
741                 Vector bindings=new Vector();
742                 /* Construct bindings */
743                 if (!constructbindings(bindings,r,false))
744                     continue;
745                 //Generate add instruction
746                 DNFRule dnfrule=r.getDNFGuardExpr();
747                 for(int j=0;j<dnfrule.size();j++) {
748                     Inclusion inc=r.getInclusion();
749                     UpdateNode un=new UpdateNode(r);
750                     un.addBindings(bindings);
751                     /* Now build update for tuple/set inclusion condition */
752                     if(inc instanceof SetInclusion) {
753                         SetInclusion si=(SetInclusion)inc;
754                         if (!(si.elementexpr instanceof VarExpr)) {
755                             if (si.elementexpr.isValue()) {
756                                 Updates up=new Updates(si.elementexpr,0);
757                                 un.addUpdate(up);
758                             } else {
759                                 /* We're an add to set*/
760                                 System.out.println("Rule: "+r);
761                                 ArrayAnalysis.AccessPath rap=arrayanalysis.analyzeExpr(r,si.elementexpr);
762                                 System.out.println("Attempting perform array add");
763                                 SetDescriptor set=sources.setSource(si.getSet())?
764                                     sources.getSourceSet(si.getSet()):null;
765                                 if (set==null)
766                                     continue;
767                                 System.out.println("Non-null source set");
768                                 ArrayAnalysis.AccessPath ap=arrayanalysis.getSet(set);
769                                 if (rap==ArrayAnalysis.AccessPath.NONE)
770                                     continue;
771                                 System.out.println("A");
772                                 if (!rap.equal(ap))
773                                     continue;
774                                 System.out.println("B");
775                                 if (!constructarrayupdate(un, si.elementexpr, rap, 0))
776                                     continue;
777                                 System.out.println("C");
778                             }
779                         } else {
780                             VarDescriptor vd=((VarExpr)si.elementexpr).getVar();
781                             if (vd.isGlobal()) {
782                                 Updates up=new Updates(si.elementexpr,0);
783                                 un.addUpdate(up);
784                             }
785                         }
786                     } else if (inc instanceof RelationInclusion) {
787                         RelationInclusion ri=(RelationInclusion)inc;
788                         if (!(ri.getLeftExpr() instanceof VarExpr)) {
789                             if (ri.getLeftExpr().isValue()) {
790                                 Updates up=new Updates(ri.getLeftExpr(),0);
791                                 un.addUpdate(up);
792                             } else {
793                                 /* We don't handly relation modifies */
794                                 if (ar.getType()==AbstractRepair.MODIFYRELATION)
795                                     continue;
796                                 /* We're an add to relation*/
797                                 ArrayAnalysis.AccessPath rap=arrayanalysis.analyzeExpr(r,ri.getLeftExpr());
798                                 SetDescriptor set=sources.relsetSource(ri.getRelation(),true /* Domain*/)?
799                                     sources.relgetSourceSet(ri.getRelation(),true):null;
800                                 if (set==null)
801                                     continue;
802                                 ArrayAnalysis.AccessPath ap=arrayanalysis.getSet(set);
803                                 
804                                 if (rap==ArrayAnalysis.AccessPath.NONE||
805                                     !rap.equal(ap)||
806                                     !constructarrayupdate(un, ri.getLeftExpr(), rap, 0))
807                                     continue;
808                             }
809                         } else {
810                             VarDescriptor vd=((VarExpr)ri.getLeftExpr()).getVar();
811                             if (vd.isGlobal()) {
812                                 Updates up=new Updates(ri.getLeftExpr(),0);
813                                 un.addUpdate(up);
814                             }
815                         }
816                         if (!(ri.getRightExpr() instanceof VarExpr)) {
817                             if (ri.getRightExpr().isValue()) {
818                                 Updates up=new Updates(ri.getRightExpr(),1);
819                                 un.addUpdate(up);
820                             } else {
821                                 /* We don't handly relation modifies */
822                                 if (ar.getType()==AbstractRepair.MODIFYRELATION)
823                                     continue;
824                                 /* We're an add to relation*/
825                                 ArrayAnalysis.AccessPath rap=arrayanalysis.analyzeExpr(r,ri.getRightExpr());
826                                 SetDescriptor set=sources.relsetSource(ri.getRelation(),false /* Range*/)?
827                                     sources.relgetSourceSet(ri.getRelation(),false):null;
828                                 if (set==null)
829                                     continue;
830                                 ArrayAnalysis.AccessPath ap=arrayanalysis.getSet(set);
831                                 
832                                 if (rap==ArrayAnalysis.AccessPath.NONE||
833                                     !rap.equal(ap)||
834                                     !constructarrayupdate(un, ri.getRightExpr(), rap, 1))
835                                     continue;
836                             }
837                         } else {
838                             VarDescriptor vd=((VarExpr)ri.getRightExpr()).getVar();
839                             if (vd.isGlobal()) {
840                                 Updates up=new Updates(ri.getRightExpr(),1);
841                                 un.addUpdate(up);
842                             }
843                         }
844                     }
845                     //Finally build necessary updates to satisfy conjunction
846                     RuleConjunction ruleconj=dnfrule.get(j);
847
848                     /* Add in updates for quantifiers */
849                     MultUpdateNode mun=new MultUpdateNode(ar,MultUpdateNode.ADD);
850                     TermNode tn=new TermNode(mun);
851                     GraphNode gn2=new GraphNode("UpdateAdd"+addtocount,tn);
852
853                     if (processquantifiers(gn2,un, r)&&
854                         processconjunction(un,ruleconj)&&
855                         un.checkupdates()) {
856                         mun.addUpdate(un);
857                         GraphNode.Edge e=new GraphNode.Edge("abstract"+addtocount,gn2);
858                         addtocount++;
859                         gn.addEdge(e);
860                         updatenodes.add(gn2);
861                     }
862                 }
863             }
864         }
865     }
866
867     boolean constructarrayupdate(UpdateNode un, Expr lexpr, ArrayAnalysis.AccessPath ap, int slotnumber) {
868         System.out.println("Constructing array update");
869         Expr e=null;
870         for (int i=ap.numFields()-1;i>=0;i--) {
871             if (e==null)
872                 e=lexpr;
873             else 
874                 e=((DotExpr)e).getExpr();
875
876             while (e instanceof CastExpr)
877                 e=((CastExpr)e).getExpr();
878
879             DotExpr de=(DotExpr)e;
880             FieldDescriptor fd=ap.getField(i);
881             if (fd instanceof ArrayDescriptor) {
882                 // We have an ArrayDescriptor!
883                 Expr index=de.getIndex();
884                 if (!index.isValue()) {/* Not assignable */
885                     System.out.println("ERROR:Index isn't assignable");
886                     return false;
887                 }
888                 Updates updates=new Updates(index,i,ap,lexpr,slotnumber);
889                 un.addUpdate(updates);
890             }
891         }
892         return true;
893     }
894
895     /** This method constructs bindings for an update using rule
896      * r. The boolean flag isremoval indicates that the update
897      * performs a removal.  The function returns true if it is able to
898      * generate a valid set of bindings and false otherwise. */
899
900     boolean constructbindings(Vector bindings, Rule r, boolean isremoval) {
901         boolean goodupdate=true;
902         Inclusion inc=r.getInclusion();
903         for(Iterator iterator=r.quantifiers();iterator.hasNext();) {
904             Quantifier q=(Quantifier)iterator.next();
905             if ((q instanceof SetQuantifier)||(q instanceof ForQuantifier)) {
906                 VarDescriptor vd=null;
907                 SetDescriptor set=null;
908                 if (q instanceof SetQuantifier) {
909                     vd=((SetQuantifier)q).getVar();
910                     set=((SetQuantifier)q).getSet();
911                 } else {
912                     vd=((ForQuantifier)q).getVar();
913                 }
914                 if(inc instanceof SetInclusion) {
915                     SetInclusion si=(SetInclusion)inc;
916                     if ((si.elementexpr instanceof VarExpr)&&
917                         (((VarExpr)si.elementexpr).getVar()==vd)) {
918                         /* Can solve for v */
919                         Binding binding=new Binding(vd,0);
920                         bindings.add(binding);
921                     } else {
922                         goodupdate=false;
923                     }
924                 } else if (inc instanceof RelationInclusion) {
925                     RelationInclusion ri=(RelationInclusion)inc;
926                     boolean f1=true;
927                     boolean f2=true;
928                     if ((ri.getLeftExpr() instanceof VarExpr)&&
929                         (((VarExpr)ri.getLeftExpr()).getVar()==vd)) {
930                                 /* Can solve for v */
931                         Binding binding=new Binding(vd,0);
932                         bindings.add(binding);
933                     } else f1=false;
934                     if ((ri.getRightExpr() instanceof VarExpr)&&
935                         (((VarExpr)ri.getRightExpr()).getVar()==vd)) {
936                                 /* Can solve for v */
937                         Binding binding=new Binding(vd,0);
938                         bindings.add(binding);
939                     } else f2=false;
940                     if (!(f1||f2))
941                         goodupdate=false;
942                 } else throw new Error("Inclusion not recognized");
943                 if (!goodupdate)
944                     if (isremoval) {
945                         /* Removals don't need bindings anymore
946                            Binding binding=new Binding(vd);
947                            bindings.add(binding);*/
948                         goodupdate=true;
949                     } else if (q instanceof SetQuantifier) {
950                         /* Create new element to bind to */
951                         // search if the set 'set' has a size
952                         Binding binding=new Binding(vd,set,exactsize.getsize(set)==1);
953                         bindings.add(binding);
954                         goodupdate=true;
955
956                     } else
957                         goodupdate=false;
958             } else if (q instanceof RelationQuantifier) {
959                 RelationQuantifier rq=(RelationQuantifier)q;
960                 for(int k=0;k<2;k++) {
961                     VarDescriptor vd=(k==0)?rq.x:rq.y;
962                     if(inc instanceof SetInclusion) {
963                         SetInclusion si=(SetInclusion)inc;
964                         if ((si.elementexpr instanceof VarExpr)&&
965                             (((VarExpr)si.elementexpr).getVar()==vd)) {
966                             /* Can solve for v */
967                             Binding binding=new Binding(vd,0);
968                             bindings.add(binding);
969                         } else
970                             goodupdate=false;
971                     } else if (inc instanceof RelationInclusion) {
972                         RelationInclusion ri=(RelationInclusion)inc;
973                         boolean f1=true;
974                         boolean f2=true;
975                         if ((ri.getLeftExpr() instanceof VarExpr)&&
976                             (((VarExpr)ri.getLeftExpr()).getVar()==vd)) {
977                             /* Can solve for v */
978                             Binding binding=new Binding(vd,0);
979                             bindings.add(binding);
980                         } else f1=false;
981                         if ((ri.getRightExpr() instanceof VarExpr)&&
982                             (((VarExpr)ri.getRightExpr()).getVar()==vd)) {
983                             /* Can solve for v */
984                             Binding binding=new Binding(vd,0);
985                             bindings.add(binding);
986                         } else f2=false;
987                         if (!(f1||f2))
988                             goodupdate=false;
989                     } else throw new Error("Inclusion not recognized");
990                     if (!goodupdate)
991                         if (isremoval) {
992                             /* Removals don't need bindings anymore
993                                Binding binding=new Binding(vd);
994                                bindings.add(binding);*/
995                             goodupdate=true;
996                         } else
997                             break;
998                 }
999                 if (!goodupdate)
1000                     break;
1001             } else throw new Error("Quantifier not recognized");
1002         }
1003         return goodupdate;
1004     }
1005     
1006     /** Adds updates that add an item to the appropriate set or
1007      * relation quantified over by the model definition rule.. */
1008     
1009     boolean processquantifiers(GraphNode gn,UpdateNode un, Rule r) {
1010         Inclusion inc=r.getInclusion();
1011         for(Iterator iterator=r.quantifiers();iterator.hasNext();) {
1012             Quantifier q=(Quantifier)iterator.next();
1013             /* Add quantifier */
1014             /* FIXME: Analysis to determine when this update is necessary */
1015             if (q instanceof RelationQuantifier) {
1016                 RelationQuantifier rq=(RelationQuantifier)q;
1017                 TupleOfExpr toe=new TupleOfExpr(new VarExpr(rq.x),new VarExpr(rq.y),rq.relation);
1018                 toe.td=ReservedTypeDescriptor.INT;
1019                 Updates u=new Updates(toe,false);
1020                 un.addUpdate(u);
1021                 if (abstractadd.containsKey(rq.relation)) {
1022                     GraphNode agn=(GraphNode)abstractadd.get(rq.relation);
1023                     GraphNode.Edge e=new GraphNode.Edge("requires",agn);
1024                     gn.addEdge(e);
1025                 } else {
1026                     return false;
1027                 }
1028                 
1029             } else if (q instanceof SetQuantifier) {
1030                 SetQuantifier sq=(SetQuantifier)q;
1031                 if (un.getBinding(sq.var).getType()==Binding.SEARCH) {
1032                     Binding b=un.getBinding(sq.var);
1033                     Constraint reqc=exactsize.getConstraint(b.getSet());
1034                     constraintdependence.requiresConstraint(gn,reqc);
1035                     continue; /* Don't need to ensure addition for search */
1036                 }
1037
1038                 ElementOfExpr eoe=new ElementOfExpr(new VarExpr(sq.var),sq.set);
1039                 eoe.td=ReservedTypeDescriptor.INT;
1040                 Updates u=new Updates(eoe,false);
1041                 un.addUpdate(u);
1042                 if (abstractadd.containsKey(sq.set)) {
1043                     GraphNode agn=(GraphNode)abstractadd.get(sq.set);
1044                     GraphNode.Edge e=new GraphNode.Edge("requires",agn);
1045                     gn.addEdge(e);
1046                 } else {
1047                     return false;
1048                 }
1049             } else return false;
1050         }
1051         return true;
1052     }
1053
1054     /** This method generates the necessary updates to satisfy the
1055      * conjunction ruleconj. */
1056
1057     boolean  processconjunction(UpdateNode un,RuleConjunction ruleconj){
1058         boolean okay=true;
1059         for(int k=0;k<ruleconj.size();k++) {
1060             DNFExpr de=ruleconj.get(k);
1061             Expr e=de.getExpr();
1062             if (e instanceof OpExpr) {
1063                 OpExpr ex=(OpExpr)de.getExpr();
1064                 Opcode op=ex.getOpcode();
1065                 Updates up=new Updates(ex.left,ex.right,op, de.getNegation());
1066                 un.addUpdate(up);
1067             } else if (e instanceof ElementOfExpr) {
1068                 Updates up=new Updates(e,de.getNegation());
1069                 un.addUpdate(up);
1070             } else if (e instanceof TupleOfExpr) {
1071                 Updates up=new Updates(e,de.getNegation());
1072                 un.addUpdate(up);
1073             } else if (e instanceof BooleanLiteralExpr) { 
1074                 boolean truth=((BooleanLiteralExpr)e).getValue();
1075                 if (de.getNegation())
1076                     truth=!truth;
1077                 if (!truth) {
1078                     okay=false;
1079                     break;
1080                 }
1081             } else {
1082                 System.out.println(e.getClass().getName());
1083                 throw new Error("Unrecognized Expr");
1084             }
1085         }
1086         return okay;
1087     }
1088 }