356c56da2c500e290cb3cd51d502452d97320d43
[repair.git] / Repair / RepairCompiler / MCC / IR / RepairGenerator.java
1 package MCC.IR;
2
3 import java.io.*;
4 import java.util.*;
5 import MCC.State;
6 import MCC.Compiler;
7
8 public class RepairGenerator {
9     State state;
10     java.io.PrintWriter outputrepair = null;
11     java.io.PrintWriter outputaux = null;
12     java.io.PrintWriter outputhead = null;
13     String name="foo";
14     String headername;
15     static VarDescriptor oldmodel=null;
16     static VarDescriptor newmodel=null;
17     static VarDescriptor worklist=null;
18     static VarDescriptor repairtable=null;
19     static VarDescriptor goodflag=null;
20     Rule currentrule=null;
21     Hashtable updatenames;
22     HashSet usedupdates;
23     Termination termination;
24     Set removed;
25     HashSet togenerate;
26     static boolean DEBUG=false;
27     Cost cost;
28     Sources sources;
29     ModelRuleDependence mrd;
30
31     public RepairGenerator(State state, Termination t) {
32         this.state = state;
33         updatenames=new Hashtable();
34         usedupdates=new HashSet();
35         termination=t;
36         removed=t.removedset;
37         togenerate=new HashSet();
38         togenerate.addAll(termination.conjunctions);
39         if (Compiler.REPAIR)
40             togenerate.removeAll(removed);
41         GraphNode.computeclosure(togenerate,removed);
42         cost=new Cost();
43         sources=new Sources(state);
44         mrd=ModelRuleDependence.doAnalysis(state);
45         Repair.repairgenerator=this;
46     }
47
48     private void generatetypechecks(boolean flag) {
49         if (flag) {
50             DotExpr.DOTYPECHECKS=true;
51             VarExpr.DOTYPECHECKS=true;
52             DotExpr.DONULL=true;
53             VarExpr.DONULL=true;
54         } else {
55             VarExpr.DOTYPECHECKS=false;
56             DotExpr.DOTYPECHECKS=false;
57             VarExpr.DONULL=true;
58             DotExpr.DONULL=true;
59         }
60     }
61
62
63     private void name_updates() {
64         int count=0;
65         for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
66             GraphNode gn=(GraphNode) it.next();
67             TermNode tn=(TermNode) gn.getOwner();
68             MultUpdateNode mun=tn.getUpdate();
69             if (togenerate.contains(gn))
70             for (int i=0;i<mun.numUpdates();i++) {
71                 UpdateNode un=mun.getUpdate(i);
72                 String name="update"+String.valueOf(count++);
73                 updatenames.put(un,name);
74             }
75         }
76     }
77
78     public void generate(OutputStream outputrepair, OutputStream outputaux,OutputStream outputhead, String st) {
79         this.outputrepair = new java.io.PrintWriter(outputrepair, true);
80         this.outputaux = new java.io.PrintWriter(outputaux, true);
81         this.outputhead = new java.io.PrintWriter(outputhead, true);
82         headername=st;
83         name_updates();
84         generatetypechecks(true);
85         generate_tokentable();
86         generate_hashtables();
87         generate_stateobject();
88         generate_call();
89         generate_start();
90         generate_rules();
91         generate_checks();
92         generate_teardown();
93         CodeWriter crhead = new StandardCodeWriter(this.outputhead);
94         CodeWriter craux = new StandardCodeWriter(this.outputaux);
95         crhead.outputline("};");
96         craux.outputline("}");
97         generatetypechecks(false);
98         generate_computesizes();
99         generatetypechecks(true);
100         generate_recomputesizes();
101         generatetypechecks(false);
102         generate_updates();
103         StructureGenerator sg=new StructureGenerator(state,this);
104         sg.buildall();
105         crhead.outputline("#endif");
106     }
107
108     String ststate="state";
109     String stmodel="model";
110     String strepairtable="repairtable";
111     String stleft="left";
112     String stright="right";
113     String stnew="newvalue";
114
115     private void generate_updates() {
116         int count=0;
117         CodeWriter crhead = new StandardCodeWriter(outputhead);        
118         CodeWriter craux = new StandardCodeWriter(outputaux);        
119
120         /* Rewrite globals */
121
122         for (Iterator it=this.state.stGlobals.descriptors();it.hasNext();) {
123             VarDescriptor vd=(VarDescriptor)it.next();
124             craux.outputline("#define "+vd.getSafeSymbol()+" "+ststate+"->"+vd.getSafeSymbol());
125         }
126
127         for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
128             GraphNode gn=(GraphNode) it.next();
129             TermNode tn=(TermNode) gn.getOwner();
130             MultUpdateNode mun=tn.getUpdate();
131             boolean isrelation=(mun.getDescriptor() instanceof RelationDescriptor);
132             if (togenerate.contains(gn))
133             for (int i=0;i<mun.numUpdates();i++) {
134                 UpdateNode un=mun.getUpdate(i);
135                 String methodname=(String)updatenames.get(un);
136                 
137                 switch(mun.op) {
138                 case MultUpdateNode.ADD:
139                     if (isrelation) {
140                         crhead.outputline("void "+methodname+"("+name+"_state * " +ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+", int "+stright+");");
141                         craux.outputline("void "+methodname+"("+name+"_state * "+ ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+", int "+stright+")");
142                     } else {
143                         crhead.outputline("void "+methodname+"("+name+"_state * "+ ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+");");
144                         craux.outputline("void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+")");
145                     }
146                     craux.startblock();
147                     craux.outputline("int maybe=0;");
148                     final SymbolTable st = un.getRule().getSymbolTable();                
149                     CodeWriter cr = new StandardCodeWriter(outputaux) {
150                         public SymbolTable getSymbolTable() { return st; }
151                     };
152                     un.generate(cr, false, false, stleft,stright, null,this);
153                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
154                     craux.endblock();
155                     break;
156                 case MultUpdateNode.REMOVE: {
157                     Rule r=un.getRule();
158                     String methodcall="void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable;
159                     for(int j=0;j<r.numQuantifiers();j++) {
160                         Quantifier q=r.getQuantifier(j);
161                         if (q instanceof SetQuantifier) {
162                             SetQuantifier sq=(SetQuantifier) q;
163                             methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
164                         } else if (q instanceof RelationQuantifier) {
165                             RelationQuantifier rq=(RelationQuantifier) q;
166                             
167                             methodcall+=","+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
168                             methodcall+=","+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
169                         } else if (q instanceof ForQuantifier) {
170                             ForQuantifier fq=(ForQuantifier) q;
171                             methodcall+=",int "+fq.getVar().getSafeSymbol();
172                         }
173                     }
174                     methodcall+=")";
175                     crhead.outputline(methodcall+";");
176                     craux.outputline(methodcall);
177                     craux.startblock();
178                     craux.outputline("int maybe=0;");
179                     final SymbolTable st2 = un.getRule().getSymbolTable();
180                     CodeWriter cr2 = new StandardCodeWriter(outputaux) {
181                         public SymbolTable getSymbolTable() { return st2; }
182                     };
183                     un.generate(cr2, true, false, null,null, null,this);
184                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
185                     craux.endblock();
186                 }
187                     break;
188                 case MultUpdateNode.MODIFY: {
189                     Rule r=un.getRule();
190                     String methodcall="void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable;
191                     for(int j=0;j<r.numQuantifiers();j++) {
192                         Quantifier q=r.getQuantifier(j);
193                         if (q instanceof SetQuantifier) {
194                             SetQuantifier sq=(SetQuantifier) q;
195                             methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
196                         } else if (q instanceof RelationQuantifier) {
197                             RelationQuantifier rq=(RelationQuantifier) q;
198                             
199                             methodcall+=", "+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
200                             methodcall+=", "+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
201                         } else if (q instanceof ForQuantifier) {
202                             ForQuantifier fq=(ForQuantifier) q;
203                             methodcall+=", int "+fq.getVar().getSafeSymbol();
204                         }
205                     }
206                     methodcall+=", "+stleft+", "+stright+", "+stnew;
207                     methodcall+=")";
208                     crhead.outputline(methodcall+";");
209                     craux.outputline(methodcall);
210                     craux.startblock();
211                     craux.outputline("int maybe=0;");
212                     final SymbolTable st2 = un.getRule().getSymbolTable();
213                     CodeWriter cr2 = new StandardCodeWriter(outputaux) {
214                         public SymbolTable getSymbolTable() { return st2; }
215                     };
216                     un.generate(cr2, false, true, stleft, stright, stnew, this);
217                     craux.outputline("if (maybe) printf(\"REALLY BAD\");");
218                     craux.endblock();
219                 }
220                     break;
221
222                 default:
223                     throw new Error("Nonimplement Update");
224                 }
225             }
226         }
227     }
228
229     private void generate_call() {
230         CodeWriter cr = new StandardCodeWriter(outputrepair);        
231         VarDescriptor vdstate=VarDescriptor.makeNew("repairstate");
232         cr.outputline(name+"_state * "+vdstate.getSafeSymbol()+"=new "+name+"_state();");
233         Iterator globals=state.stGlobals.descriptors();
234         while (globals.hasNext()) {
235             VarDescriptor vd=(VarDescriptor) globals.next();
236             cr.outputline(vdstate.getSafeSymbol()+"->"+vd.getSafeSymbol()+"=("+vd.getType().getGenerateType().getSafeSymbol()+")"+vd.getSafeSymbol()+";");
237         }
238         /* Insert repair here */
239         cr.outputline(vdstate.getSafeSymbol()+"->doanalysis();");
240         globals=state.stGlobals.descriptors();
241         while (globals.hasNext()) {
242             VarDescriptor vd=(VarDescriptor) globals.next();
243             cr.outputline("*(("+vd.getType().getGenerateType().getSafeSymbol()+"*) &"+vd.getSafeSymbol()+")="+vdstate.getSafeSymbol()+"->"+vd.getSafeSymbol()+";");
244         }
245         cr.outputline("delete "+vdstate.getSafeSymbol()+";");
246     }
247
248     private void generate_tokentable() {
249         CodeWriter cr = new StandardCodeWriter(outputrepair);        
250         Iterator tokens = TokenLiteralExpr.tokens.keySet().iterator();        
251
252         cr.outputline("");
253         cr.outputline("// Token values");
254         cr.outputline("");
255
256         while (tokens.hasNext()) {
257             Object token = tokens.next();
258             cr.outputline("// " + token.toString() + " = " + TokenLiteralExpr.tokens.get(token).toString());            
259         }
260
261         cr.outputline("");
262         cr.outputline("");
263     }
264
265     private void generate_stateobject() {
266         CodeWriter crhead = new StandardCodeWriter(outputhead);
267         crhead.outputline("class "+name+"_state {");
268         crhead.outputline("public:");
269         Iterator globals=state.stGlobals.descriptors();
270         while (globals.hasNext()) {
271             VarDescriptor vd=(VarDescriptor) globals.next();
272             crhead.outputline(vd.getType().getGenerateType().getSafeSymbol()+" "+vd.getSafeSymbol()+";");
273         }
274         crhead.outputline("void computesizes(int *,int **);");
275         crhead.outputline("void recomputesizes();");
276     }
277
278     private void generate_computesizes() {
279         int max=TypeDescriptor.counter;
280         TypeDescriptor[] tdarray=new TypeDescriptor[max];
281         for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
282             TypeDescriptor ttd=(TypeDescriptor)it.next();
283             tdarray[ttd.getId()]=ttd;
284         }
285         final SymbolTable st = state.stGlobals;
286         CodeWriter cr = new StandardCodeWriter(outputaux) {
287                 public SymbolTable getSymbolTable() { return st; }
288             };
289
290         cr.outputline("void "+name+"_state::computesizes(int *sizearray,int **numele) {");
291         for(int i=0;i<max;i++) {
292             TypeDescriptor td=tdarray[i];
293             Expr size=td.getSizeExpr();
294             VarDescriptor vd=VarDescriptor.makeNew("size");
295             size.generate(cr,vd);
296             cr.outputline("sizearray["+i+"]="+vd.getSafeSymbol()+";");
297         }
298         for(int i=0;i<max;i++) {
299             TypeDescriptor td=tdarray[i];
300             if (td instanceof StructureTypeDescriptor) {
301                 StructureTypeDescriptor std=(StructureTypeDescriptor) td;
302                 for(int j=0;j<std.fieldlist.size();j++) {
303                     FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
304                     if (fd instanceof ArrayDescriptor) {
305                         ArrayDescriptor ad=(ArrayDescriptor)fd;
306                         Expr index=ad.getIndexBound();
307                         VarDescriptor vd=VarDescriptor.makeNew("index");
308                         index.generate(cr,vd);
309                         cr.outputline("numele["+i+"]["+j+"]="+vd.getSafeSymbol()+";");
310                     }
311                 }
312             }
313         }
314         cr.outputline("}");
315     }
316
317     private void generate_recomputesizes() {
318         int max=TypeDescriptor.counter;
319         TypeDescriptor[] tdarray=new TypeDescriptor[max];
320         for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
321             TypeDescriptor ttd=(TypeDescriptor)it.next();
322             tdarray[ttd.getId()]=ttd;
323         }
324         final SymbolTable st = state.stGlobals;
325         CodeWriter cr = new StandardCodeWriter(outputaux) {
326                 public SymbolTable getSymbolTable() { return st; }
327             };
328         cr.outputline("void "+name+"_state::recomputesizes() {");
329         for(int i=0;i<max;i++) {
330             TypeDescriptor td=tdarray[i];
331             Expr size=td.getSizeExpr();
332             VarDescriptor vd=VarDescriptor.makeNew("size");
333             size.generate(cr,vd);
334         }
335         for(int i=0;i<max;i++) {
336             TypeDescriptor td=tdarray[i];
337             if (td instanceof StructureTypeDescriptor) {
338                 StructureTypeDescriptor std=(StructureTypeDescriptor) td;
339                 for(int j=0;j<std.fieldlist.size();j++) {
340                     FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
341                     if (fd instanceof ArrayDescriptor) {
342                         ArrayDescriptor ad=(ArrayDescriptor)fd;
343                         Expr index=ad.getIndexBound();
344                         VarDescriptor vd=VarDescriptor.makeNew("index");
345                         index.generate(cr,vd);
346                     }
347                 }
348             }
349         }
350         cr.outputline("}");
351     }
352
353
354     private void generate_hashtables() {
355         CodeWriter craux = new StandardCodeWriter(outputaux);
356         CodeWriter crhead = new StandardCodeWriter(outputhead);
357         crhead.outputline("#ifndef "+name+"_h");
358         crhead.outputline("#define "+name+"_h");
359         crhead.outputline("#include \"SimpleHash.h\"");
360         crhead.outputline("extern \"C\" {");
361         crhead.outputline("#include \"instrument.h\"");
362         crhead.outputline("}");
363         crhead.outputline("#include <stdio.h>");
364         crhead.outputline("#include <stdlib.h>");
365         crhead.outputline("class "+name+" {");
366         crhead.outputline("public:");
367         crhead.outputline(name+"();");
368         crhead.outputline("~"+name+"();");
369         craux.outputline("#include \""+headername+"\"");
370         craux.outputline("#include \"size.h\"");
371
372         craux.outputline(name+"::"+name+"() {");
373         craux.outputline("// creating hashtables ");
374         
375         /* build sets */
376         Iterator sets = state.stSets.descriptors();
377         
378         /* first pass create all the hash tables */
379         while (sets.hasNext()) {
380             SetDescriptor set = (SetDescriptor) sets.next();
381             crhead.outputline("SimpleHash* " + set.getSafeSymbol() + "_hash;");
382             craux.outputline(set.getSafeSymbol() + "_hash = new SimpleHash();");
383         }
384         
385         /* second pass build relationships between hashtables */
386         sets = state.stSets.descriptors();
387         
388         while (sets.hasNext()) {
389             SetDescriptor set = (SetDescriptor) sets.next();
390             Iterator subsets = set.subsets();
391             
392             while (subsets.hasNext()) {
393                 SetDescriptor subset = (SetDescriptor) subsets.next();                
394                 craux.outputline(subset.getSafeSymbol() + "_hash->addParent(" + set.getSafeSymbol() + "_hash);");
395             }
396         } 
397
398         /* build relations */
399         Iterator relations = state.stRelations.descriptors();
400         
401         /* first pass create all the hash tables */
402         while (relations.hasNext()) {
403             RelationDescriptor relation = (RelationDescriptor) relations.next();
404             
405             if (relation.testUsage(RelationDescriptor.IMAGE)) {
406                 crhead.outputline("SimpleHash* " + relation.getSafeSymbol() + "_hash;");
407                 craux.outputline(relation.getSafeSymbol() + "_hash = new SimpleHash();");
408             }
409
410             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
411                 crhead.outputline("SimpleHash* " + relation.getSafeSymbol() + "_hashinv;");
412                 craux.outputline(relation.getSafeSymbol() + "_hashinv = new SimpleHash();");
413             } 
414         }
415
416         craux.outputline("}");
417         crhead.outputline("};");
418         craux.outputline(name+"::~"+name+"() {");
419         craux.outputline("// deleting hashtables");
420
421         /* build destructor */
422         sets = state.stSets.descriptors();
423         
424         /* first pass create all the hash tables */
425         while (sets.hasNext()) {
426             SetDescriptor set = (SetDescriptor) sets.next();
427             craux.outputline("delete "+set.getSafeSymbol() + "_hash;");
428         } 
429         
430         /* destroy relations */
431         relations = state.stRelations.descriptors();
432         
433         /* first pass create all the hash tables */
434         while (relations.hasNext()) {
435             RelationDescriptor relation = (RelationDescriptor) relations.next();
436             
437             if (relation.testUsage(RelationDescriptor.IMAGE)) {
438                 craux.outputline("delete "+relation.getSafeSymbol() + "_hash;");
439             }
440
441             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
442                 craux.outputline("delete " + relation.getSafeSymbol() + "_hashinv;");
443             } 
444         }
445         craux.outputline("}");
446     }
447
448     private void generate_start() {
449         CodeWriter crhead = new StandardCodeWriter(outputhead);
450         CodeWriter craux = new StandardCodeWriter(outputaux);
451         oldmodel=VarDescriptor.makeNew("oldmodel");
452         newmodel=VarDescriptor.makeNew("newmodel");
453         worklist=VarDescriptor.makeNew("worklist");
454         goodflag=VarDescriptor.makeNew("goodflag");
455         repairtable=VarDescriptor.makeNew("repairtable");
456         crhead.outputline("void doanalysis();");
457         craux.outputline("void "+name +"_state::doanalysis()");
458         craux.startblock();
459         craux.outputline("int highmark;");
460         craux.outputline("initializestack(&highmark);");
461         craux.outputline("typeobject *typeobject1=gettypeobject();");
462         craux.outputline("typeobject1->computesizes(this);");
463         craux.outputline("recomputesizes();");
464         craux.outputline(name+ " * "+oldmodel.getSafeSymbol()+"=0;");
465         craux.outputline("WorkList * "+worklist.getSafeSymbol()+" = new WorkList();");
466         craux.outputline("RepairHash * "+repairtable.getSafeSymbol()+"=0;");
467         craux.outputline("while (1)");
468         craux.startblock();
469         craux.outputline(name+ " * "+newmodel.getSafeSymbol()+"=new "+name+"();");
470     }
471     
472     private void generate_teardown() {
473         CodeWriter cr = new StandardCodeWriter(outputaux);        
474         cr.endblock();
475     }
476
477     Set ruleset=null;
478     private void generate_rules() {
479         /* first we must sort the rules */
480         RelationDescriptor.prefix = newmodel.getSafeSymbol()+"->";
481         SetDescriptor.prefix = newmodel.getSafeSymbol()+"->";
482         System.out.println("SCC="+(mrd.numSCC()-1));
483         for(int sccindex=0;sccindex<mrd.numSCC();sccindex++) {
484             ruleset=mrd.getSCC(sccindex);
485             boolean needworklist=mrd.hasCycle(sccindex);
486             
487             if (!needworklist) {
488                 Iterator iterator_rs = ruleset.iterator();
489                 while (iterator_rs.hasNext()) {
490                     Rule rule = (Rule) iterator_rs.next();
491                     {
492                         final SymbolTable st = rule.getSymbolTable();
493                         CodeWriter cr = new StandardCodeWriter(outputaux) {
494                                 public SymbolTable getSymbolTable() { return st; }
495                             };
496                         cr.outputline("// build " +escape(rule.toString()));
497                         cr.startblock();
498                         cr.outputline("int maybe=0;");
499                         ListIterator quantifiers = rule.quantifiers();
500                         while (quantifiers.hasNext()) {
501                             Quantifier quantifier = (Quantifier) quantifiers.next();
502                             quantifier.generate_open(cr);
503                         }
504                         
505                         /* pretty print! */
506                         cr.output("//");
507                         rule.getGuardExpr().prettyPrint(cr);
508                         cr.outputline("");
509                         
510                         /* now we have to generate the guard test */
511                         VarDescriptor guardval = VarDescriptor.makeNew();
512                         rule.getGuardExpr().generate(cr, guardval);
513                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
514                         cr.startblock();
515                         
516                         /* now we have to generate the inclusion code */
517                         currentrule=rule;
518                         rule.getInclusion().generate(cr);
519                         cr.endblock();
520                         while (quantifiers.hasPrevious()) {
521                             Quantifier quantifier = (Quantifier) quantifiers.previous();
522                             cr.endblock();
523                         }
524                         cr.endblock();
525                         cr.outputline("");
526                         cr.outputline("");
527                     }
528                 }
529             } else {
530                 CodeWriter cr2 = new StandardCodeWriter(outputaux);
531                 
532                 for(Iterator initialworklist=ruleset.iterator();initialworklist.hasNext();) {
533                     /** Construct initial worklist set */
534                     Rule rule=(Rule)initialworklist.next();
535                     cr2.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
536                 }
537
538                 cr2.outputline("while ("+worklist.getSafeSymbol()+"->hasMoreElements())");
539                 cr2.startblock();
540                 VarDescriptor idvar=VarDescriptor.makeNew("id");
541                 cr2.outputline("int "+idvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getid();");
542                 
543                 String elseladder = "if";
544                 
545                 Iterator iterator_rules = ruleset.iterator();
546                 while (iterator_rules.hasNext()) {
547                     
548                     Rule rule = (Rule) iterator_rules.next();
549                     int dispatchid = rule.getNum();
550                     
551                     {
552                         final SymbolTable st = rule.getSymbolTable();
553                         CodeWriter cr = new StandardCodeWriter(outputaux) {
554                                 public SymbolTable getSymbolTable() { return st; }
555                             };
556                         
557                         cr.indent();
558                         cr.outputline(elseladder + " ("+idvar.getSafeSymbol()+" == " + dispatchid + ")");
559                         cr.startblock();
560                         cr.outputline("int maybe=0;");
561                         VarDescriptor typevar=VarDescriptor.makeNew("type");
562                         VarDescriptor leftvar=VarDescriptor.makeNew("left");
563                         VarDescriptor rightvar=VarDescriptor.makeNew("right");
564                         cr.outputline("int "+typevar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->gettype();");
565                         cr.outputline("int "+leftvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getlvalue();");
566                         cr.outputline("int "+rightvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getrvalue();");
567                         cr.outputline("// build " +escape(rule.toString()));
568                         
569                         
570                         for (int j=0;j<rule.numQuantifiers();j++) {
571                             Quantifier quantifier = rule.getQuantifier(j);
572                             quantifier.generate_open(cr, typevar.getSafeSymbol(),j,leftvar.getSafeSymbol(),rightvar.getSafeSymbol());
573                         }
574                         
575                         /* pretty print! */
576                         cr.output("//");
577                         
578                         rule.getGuardExpr().prettyPrint(cr);
579                         cr.outputline("");
580                         
581                         /* now we have to generate the guard test */
582                         
583                         VarDescriptor guardval = VarDescriptor.makeNew();
584                         rule.getGuardExpr().generate(cr, guardval);
585                         
586                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
587                         cr.startblock();
588                         
589                         /* now we have to generate the inclusion code */
590                         currentrule=rule;
591                         rule.getInclusion().generate(cr);
592                         cr.endblock();
593                         
594                         for (int j=0;j<rule.numQuantifiers();j++) {
595                             cr.endblock();
596                         }
597                         
598                         // close startblocks generated by DotExpr memory checks
599                         //DotExpr.generate_memory_endblocks(cr);
600                         
601                         cr.endblock(); // end else-if WORKLIST ladder
602                         
603                         elseladder = "else if";
604                     }
605                 }
606                 cr2.outputline("else");
607                 cr2.startblock();
608                 cr2.outputline("printf(\"VERY BAD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\");");
609                 cr2.outputline("exit(1);");
610                 cr2.endblock();
611                 // end block created for worklist
612                 cr2.outputline(worklist.getSafeSymbol()+"->pop();");
613                 cr2.endblock();
614             }
615         }
616     }
617
618     public static String escape(String s) {
619         String newstring="";
620         for(int i=0;i<s.length();i++) {
621             char c=s.charAt(i);
622             if (c=='"')
623                 newstring+="\"";
624             else
625                 newstring+=c;
626         }
627         return newstring;
628     }
629
630     private void generate_checks() {
631
632         /* do constraint checks */
633         //        Vector constraints = state.vConstraints;
634
635
636         //        for (int i = 0; i < constraints.size(); i++) {
637         //            Constraint constraint = (Constraint) constraints.elementAt(i); 
638         for (Iterator i = termination.constraintdependence.computeOrdering().iterator(); i.hasNext();) {
639             Constraint constraint = (Constraint) ((GraphNode)i.next()).getOwner();
640             
641             {
642                 final SymbolTable st = constraint.getSymbolTable();
643                 CodeWriter cr = new StandardCodeWriter(outputaux);
644                 cr.pushSymbolTable(constraint.getSymbolTable());
645
646                 cr.outputline("// checking " + escape(constraint.toString()));
647                 cr.startblock();
648
649                 ListIterator quantifiers = constraint.quantifiers();
650
651                 while (quantifiers.hasNext()) {
652                     Quantifier quantifier = (Quantifier) quantifiers.next();
653                     quantifier.generate_open(cr);
654                 }
655
656                 cr.outputline("int maybe = 0;");
657                         
658                 /* now we have to generate the guard test */
659         
660                 VarDescriptor constraintboolean = VarDescriptor.makeNew("constraintboolean");
661                 constraint.getLogicStatement().generate(cr, constraintboolean);
662                 
663                 cr.outputline("if (maybe)");
664                 cr.startblock();
665                 cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
666                 cr.outputline("exit(1);");
667                 cr.endblock();
668
669                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
670                 cr.startblock();
671                 if (!Compiler.REPAIR)
672                     cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
673                 else {
674                 /* Do repairs */
675                 /* Build new repair table */
676                 cr.outputline("if ("+repairtable.getSafeSymbol()+")");
677                 cr.outputline("delete "+repairtable.getSafeSymbol()+";");
678                 cr.outputline(repairtable.getSafeSymbol()+"=new RepairHash();");
679
680                 
681                 /* Compute cost of each repair */
682                 VarDescriptor mincost=VarDescriptor.makeNew("mincost");
683                 VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
684                 DNFConstraint dnfconst=constraint.dnfconstraint;
685                 if (dnfconst.size()<=1) {
686                     cr.outputline("int "+mincostindex.getSafeSymbol()+"=0;");
687                 }
688                 if (dnfconst.size()>1) {
689                     cr.outputline("int "+mincostindex.getSafeSymbol()+";");
690                     boolean first=true;
691                     for(int j=0;j<dnfconst.size();j++) {
692                         Conjunction conj=dnfconst.get(j);
693                         GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
694                         if (removed.contains(gn))
695                             continue;
696                         
697                         VarDescriptor costvar;
698                         if (first) {
699                             costvar=mincost;
700                         } else
701                             costvar=VarDescriptor.makeNew("cost");
702                         for(int k=0;k<conj.size();k++) {
703                             DNFPredicate dpred=conj.get(k);
704                             Predicate p=dpred.getPredicate();
705                             boolean negate=dpred.isNegated();
706                             VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
707                             p.generate(cr,predvalue);
708                             if (negate)
709                                 cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
710                             else
711                                 cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
712                             if (k==0)
713                                 cr.outputline("int "+costvar.getSafeSymbol()+"="+cost.getCost(dpred)+";");
714                             else
715                                 cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
716                         }
717
718                         if(!first) {
719                             cr.outputline("if ("+costvar.getSafeSymbol()+"<"+mincost.getSafeSymbol()+")");
720                             cr.startblock();
721                             cr.outputline(mincost.getSafeSymbol()+"="+costvar.getSafeSymbol()+";");
722                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
723                             cr.endblock();
724                         } else
725                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
726                         first=false;
727                     }
728                 }
729                 cr.outputline("switch("+mincostindex.getSafeSymbol()+") {");
730                 for(int j=0;j<dnfconst.size();j++) {
731                     Conjunction conj=dnfconst.get(j);
732                     GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
733                     if (removed.contains(gn))
734                         continue;
735                     cr.outputline("case "+j+":");
736                     for(int k=0;k<conj.size();k++) {
737                         DNFPredicate dpred=conj.get(k);
738                         Predicate p=dpred.getPredicate();
739                         boolean negate=dpred.isNegated();
740                         VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
741                         p.generate(cr,predvalue);
742                         if (negate)
743                             cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
744                         else
745                             cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
746                         cr.startblock();
747                         if (p instanceof InclusionPredicate)
748                             generateinclusionrepair(conj,dpred, cr);
749                         else if (p instanceof ExprPredicate) {
750                             ExprPredicate ep=(ExprPredicate)p;
751                             if (ep.getType()==ExprPredicate.SIZE)
752                                 generatesizerepair(conj,dpred,cr);
753                             else if (ep.getType()==ExprPredicate.COMPARISON)
754                                 generatecomparisonrepair(conj,dpred,cr);
755                         } else throw new Error("Unrecognized Predicate");
756                         cr.endblock();
757                     }
758                     /* Update model */
759                     cr.outputline("break;");
760                 }
761                 cr.outputline("}");
762
763                 cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
764                 cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
765                 cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
766                 cr.outputline("goto rebuild;");  /* Rebuild model and all */
767                 }
768                 cr.endblock();
769                 
770                 while (quantifiers.hasPrevious()) {
771                     Quantifier quantifier = (Quantifier) quantifiers.previous();
772                     cr.endblock();
773                 }
774                 cr.endblock();
775                 cr.outputline("");
776                 cr.outputline("");
777             }
778         }
779         CodeWriter cr = new StandardCodeWriter(outputaux);
780         cr.startblock();
781         cr.outputline("if ("+repairtable.getSafeSymbol()+")");
782         cr.outputline("delete "+repairtable.getSafeSymbol()+";");
783         cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
784         cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
785         cr.outputline("delete "+newmodel.getSafeSymbol()+";");
786         cr.outputline("delete "+worklist.getSafeSymbol()+";");
787         cr.outputline("resettypemap();");
788         cr.outputline("break;");
789         cr.endblock();
790         cr.outputline("rebuild:");
791         cr.outputline(";");     
792         
793     }
794     
795     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
796         MultUpdateNode mun=null;
797         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
798         for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
799             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
800             TermNode tn2=(TermNode)gn2.getOwner();
801             if (tn2.getType()==TermNode.ABSTRACT) {
802                 AbstractRepair ar=tn2.getAbstract();
803                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
804                     ar.getPredicate()==dpred) {
805                     for(Iterator edgeit2=gn2.edges();edgeit2.hasNext();) {
806                         GraphNode gn3=((GraphNode.Edge) edgeit2.next()).getTarget();
807                         if (!removed.contains(gn3)) {
808                             TermNode tn3=(TermNode)gn3.getOwner();
809                             if (tn3.getType()==TermNode.UPDATE) {
810                                 mun=tn3.getUpdate();
811                                 break;
812                             }
813                         }
814                     }
815                 }
816             }
817         }
818         return mun;
819     }
820
821     /** Generates abstract (and concrete) repair for a comparison */
822
823     private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
824         MultUpdateNode munmodify=getmultupdatenode(conj,dpred,AbstractRepair.MODIFYRELATION);
825         MultUpdateNode munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
826         MultUpdateNode munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
827         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
828         RelationDescriptor rd=(RelationDescriptor)ep.getDescriptor();
829         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
830         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
831         boolean inverted=ep.inverted();
832         boolean negated=dpred.isNegated();
833         OpExpr expr=(OpExpr)ep.expr;
834         Opcode opcode=expr.getOpcode();
835         VarDescriptor leftside=VarDescriptor.makeNew("leftside");
836         VarDescriptor rightside=VarDescriptor.makeNew("rightside");
837         VarDescriptor newvalue=VarDescriptor.makeNew("newvalue");
838         if (!inverted) {
839             expr.getLeftExpr().generate(cr,leftside);
840             expr.getRightExpr().generate(cr,newvalue);
841             cr.outputline(rd.getRange().getType().getGenerateType().getSafeSymbol()+" "+rightside.getSafeSymbol()+";");
842             cr.outputline(rd.getSafeSymbol()+"_hash->get("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
843         } else {
844             expr.getLeftExpr().generate(cr,rightside);
845             expr.getRightExpr().generate(cr,newvalue);
846             cr.outputline(rd.getDomain().getType().getGenerateType().getSafeSymbol()+" "+leftside.getSafeSymbol()+";");
847             cr.outputline(rd.getSafeSymbol()+"_hashinv->get("+leftside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
848         }
849         if (negated)
850             if (opcode==Opcode.GT) {
851                 opcode=Opcode.LE;
852             } else if (opcode==Opcode.GE) {
853                 opcode=Opcode.LT;
854             } else if (opcode==Opcode.LT) {
855                 opcode=Opcode.GE;
856             } else if (opcode==Opcode.LE) {
857                 opcode=Opcode.GT;
858             } else if (opcode==Opcode.EQ) {
859                 opcode=Opcode.NE;
860             } else if (opcode==Opcode.NE) {
861                 opcode=Opcode.EQ;
862             } else {
863                 throw new Error("Unrecognized Opcode");
864             }
865
866         if (opcode==Opcode.GT) {
867             cr.outputline(newvalue.getSafeSymbol()+"++;");
868         } else if (opcode==Opcode.GE) {
869             /* Equal */
870         } else if (opcode==Opcode.LT) {
871             cr.outputline(newvalue.getSafeSymbol()+"--;");
872         } else if (opcode==Opcode.LE) {
873             /* Equal */
874         } else if (opcode==Opcode.EQ) {
875             /* Equal */
876         } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
877             cr.outputline(newvalue.getSafeSymbol()+"++;");
878         } else {
879             throw new Error("Unrecognized Opcode");
880         }
881         /* Do abstract repairs */
882         if (usageimage) {
883             cr.outputline(rd.getSafeSymbol()+"_hash->remove("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
884             if (!inverted) {
885                 cr.outputline(rd.getSafeSymbol()+"_hash->add("+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
886             } else {
887                 cr.outputline(rd.getSafeSymbol()+"_hash->add("+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
888             }
889         }
890         if (usageinvimage) {
891             cr.outputline(rd.getSafeSymbol()+"_hashinv->remove("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
892             if (!inverted) {
893                 cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newvalue.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
894             } else {
895                 cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+rightside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
896             }
897         }
898         /* Do concrete repairs */
899         if (munmodify!=null) {
900             for(int i=0;i<state.vRules.size();i++) {
901                 Rule r=(Rule)state.vRules.get(i);
902                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
903                     for(int j=0;j<munmodify.numUpdates();j++) {
904                         UpdateNode un=munmodify.getUpdate(j);
905                         if (un.getRule()==r) {
906                             /* Update for rule r */
907                             String name=(String)updatenames.get(un);
908                             cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
909                         }
910                     }
911                 }
912             }
913
914         } else {
915             /* Start with scheduling removal */
916             for(int i=0;i<state.vRules.size();i++) {
917                 Rule r=(Rule)state.vRules.get(i);
918                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
919                     for(int j=0;j<munremove.numUpdates();j++) {
920                         UpdateNode un=munremove.getUpdate(i);
921                         if (un.getRule()==r) {
922                             /* Update for rule r */
923                             String name=(String)updatenames.get(un);
924                             cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
925                         }
926                     }
927                 }
928             }
929             /* Now do addition */
930             UpdateNode un=munadd.getUpdate(0);
931             String name=(String)updatenames.get(un);
932             if (!inverted) {
933                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
934             } else {
935                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
936             }
937         }
938     }
939
940     public void generatesizerepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr) {
941         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
942         OpExpr expr=(OpExpr)ep.expr;
943         Opcode opcode=expr.getOpcode();
944         opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
945
946         MultUpdateNode munremove;
947
948         MultUpdateNode munadd;
949         if (ep.getDescriptor() instanceof RelationDescriptor) {
950             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
951             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
952         } else {
953             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
954             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
955         }
956         int size=ep.rightSize();
957         VarDescriptor sizevar=VarDescriptor.makeNew("size");
958         ((OpExpr)expr).left.generate(cr, sizevar);
959         VarDescriptor change=VarDescriptor.makeNew("change");
960         cr.outputline("int "+change.getSafeSymbol()+";");
961         boolean generateadd=false;
962         boolean generateremove=false;
963         if (opcode==Opcode.GT) {
964             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
965             generateadd=true;
966             generateremove=false;
967         } else if (opcode==Opcode.GE) {
968             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
969             generateadd=true;
970             generateremove=false;
971         } else if (opcode==Opcode.LT) {
972             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size-1)+"-"+sizevar.getSafeSymbol()+";");
973             generateadd=false;
974             generateremove=true;
975         } else if (opcode==Opcode.LE) {
976             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
977             generateadd=false;
978             generateremove=true;
979         } else if (opcode==Opcode.EQ) {
980             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
981             if (size==0)
982                 generateadd=false;
983             else 
984                 generateadd=true;
985             generateremove=true;
986         } else if (opcode==Opcode.NE) {
987             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
988             generateadd=true;
989             generateremove=false;
990         } else {
991             throw new Error("Unrecognized Opcode");
992         }
993
994 // In some cases the analysis has determined that generating removes
995 // is unnecessary
996         if (generateremove&&munremove==null) 
997             generateremove=false;
998
999         Descriptor d=ep.getDescriptor();
1000         if (generateremove) {
1001             cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
1002             cr.startblock();
1003             /* Find element to remove */
1004             VarDescriptor leftvar=VarDescriptor.makeNew("leftvar");
1005             VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
1006             if (d instanceof RelationDescriptor) {
1007                 if (ep.inverted()) {
1008                     rightvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
1009                     cr.outputline("int "+leftvar.getSafeSymbol()+";");
1010                     cr.outputline(d.getSafeSymbol()+"_hashinv->get((int)"+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1011                 } else {
1012                     leftvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
1013                     cr.outputline("int "+rightvar.getSafeSymbol()+"=0;");
1014                     cr.outputline(d.getSafeSymbol()+"_hash->get((int)"+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1015                 }
1016             } else {
1017                 cr.outputline("int "+leftvar.getSafeSymbol()+"="+d.getSafeSymbol()+"_hash->firstkey();");
1018             }
1019             /* Generate abstract remove instruction */
1020             if (d instanceof RelationDescriptor) {
1021                 RelationDescriptor rd=(RelationDescriptor) d;
1022                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1023                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1024                 if (usageimage)
1025                     cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1026                 if (usageinvimage)
1027                     cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1028             } else {
1029                 cr.outputline(d.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1030             }
1031             /* Generate concrete remove instruction */
1032             for(int i=0;i<state.vRules.size();i++) {
1033                 Rule r=(Rule)state.vRules.get(i);
1034                 if (r.getInclusion().getTargetDescriptors().contains(d)) {
1035                     for(int j=0;j<munremove.numUpdates();j++) {
1036                         UpdateNode un=munremove.getUpdate(j);
1037                         if (un.getRule()==r) {
1038                                 /* Update for rule rule r */
1039                             String name=(String)updatenames.get(un);
1040                             if (d instanceof RelationDescriptor) {
1041                                 cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1042                             } else {
1043                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1044                             }
1045                         }
1046                     }
1047                 }
1048             }
1049             cr.endblock();
1050         }
1051         if (generateadd) {
1052
1053             cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
1054             cr.startblock();
1055             VarDescriptor newobject=VarDescriptor.makeNew("newobject");
1056             if (d instanceof RelationDescriptor) {
1057                 VarDescriptor otherside=((ImageSetExpr)((SizeofExpr)((OpExpr)ep.expr).left).setexpr).vd;
1058                 RelationDescriptor rd=(RelationDescriptor)d;
1059                 if (sources.relsetSource(rd,!ep.inverted())) {
1060                     /* Set Source */
1061                     SetDescriptor sd=sources.relgetSourceSet(rd,!ep.inverted());
1062                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1063                     cr.outputline(sd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1064                     cr.outputline("for("+iterator.getSafeSymbol()+"="+sd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
1065                     cr.startblock();
1066                     if (ep.inverted()) {
1067                         cr.outputline("if !"+rd.getSafeSymbol()+"_hashinv->contains("+iterator.getSafeSymbol()+"->key(),"+otherside.getSafeSymbol()+")");
1068                     } else {
1069                         cr.outputline("if !"+rd.getSafeSymbol()+"_hash->contains("+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+"->key())");
1070                     }
1071                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1072                     cr.outputline(iterator.getSafeSymbol()+"->next();");
1073                     cr.endblock();
1074                 } else if (sources.relallocSource(rd,!ep.inverted())) {
1075                     /* Allocation Source*/
1076                     sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
1077                 } else throw new Error("No source for adding to Relation");
1078                 if (ep.inverted()) {
1079                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1080                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1081                     if (usageimage)
1082                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1083                     if (usageinvimage)
1084                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1085
1086                     UpdateNode un=munadd.getUpdate(0);
1087                     String name=(String)updatenames.get(un);
1088                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1089                 } else {
1090                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1091                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1092                     if (usageimage)
1093                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1094                     if (usageinvimage)
1095                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1096                     UpdateNode un=munadd.getUpdate(0);
1097                     String name=(String)updatenames.get(un);
1098                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1099                 }
1100             } else {
1101                 SetDescriptor sd=(SetDescriptor)d;
1102                 if (sources.setSource(sd)) {
1103                     /* Set Source */
1104                     /* Set Source */
1105                     SetDescriptor sourcesd=sources.getSourceSet(sd);
1106                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1107                     cr.outputline(sourcesd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1108                     cr.outputline("for("+iterator.getSafeSymbol()+"="+sourcesd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
1109                     cr.startblock();
1110                     cr.outputline("if !"+sd.getSafeSymbol()+"_hash->contains("+iterator.getSafeSymbol()+"->key())");
1111                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1112                     cr.outputline(iterator.getSafeSymbol()+"->next();");
1113                     cr.endblock();
1114                 } else if (sources.allocSource(sd)) {
1115                     /* Allocation Source*/
1116                     sources.generateSourceAlloc(cr,newobject,sd);
1117                 } else throw new Error("No source for adding to Set");
1118                 cr.outputline(sd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1119                 UpdateNode un=munadd.getUpdate(0);
1120                 String name=(String)updatenames.get(un);
1121                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1122             }
1123             cr.endblock();
1124         }
1125     }
1126
1127     public void generateinclusionrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1128         InclusionPredicate ip=(InclusionPredicate) dpred.getPredicate();
1129         boolean negated=dpred.isNegated();
1130         MultUpdateNode mun=getmultupdatenode(conj,dpred,-1);
1131         VarDescriptor leftvar=VarDescriptor.makeNew("left");
1132         ip.expr.generate(cr, leftvar);
1133
1134         if (negated) {
1135             if (ip.setexpr instanceof ImageSetExpr) {
1136                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1137                 VarDescriptor rightvar=ise.getVar();
1138                 boolean inverse=ise.inverted();
1139                 RelationDescriptor rd=ise.getRelation();
1140                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1141                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1142                 if (inverse) {
1143                     if (usageimage)
1144                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1145                     if (usageinvimage)
1146                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1147                 } else {
1148                     if (usageimage)
1149                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1150                     if (usageinvimage)
1151                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1152                 }
1153                 for(int i=0;i<state.vRules.size();i++) {
1154                     Rule r=(Rule)state.vRules.get(i);
1155                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1156                         for(int j=0;j<mun.numUpdates();j++) {
1157                             UpdateNode un=mun.getUpdate(i);
1158                             if (un.getRule()==r) {
1159                                 /* Update for rule rule r */
1160                                 String name=(String)updatenames.get(un);
1161                                 if (inverse) {
1162                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1163                                 } else {
1164                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1165                                 }
1166                             }
1167                         }
1168                     }
1169                 }
1170             } else {
1171                 SetDescriptor sd=ip.setexpr.sd;
1172                 cr.outputline(sd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1173
1174                 for(int i=0;i<state.vRules.size();i++) {
1175                     Rule r=(Rule)state.vRules.get(i);
1176                     if (r.getInclusion().getTargetDescriptors().contains(sd)) {
1177                         for(int j=0;j<mun.numUpdates();j++) {
1178                             UpdateNode un=mun.getUpdate(i);
1179                             if (un.getRule()==r) {
1180                                 /* Update for rule rule r */
1181                                 String name=(String)updatenames.get(un);
1182                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+sd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1183                             }
1184                         }
1185                     }
1186                 }
1187             }
1188         } else {
1189             /* Generate update */
1190             if (ip.setexpr instanceof ImageSetExpr) {
1191                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1192                 VarDescriptor rightvar=ise.getVar();
1193                 boolean inverse=ise.inverted();
1194                 RelationDescriptor rd=ise.getRelation();
1195                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1196                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1197                 if (inverse) {
1198                     if (usageimage)
1199                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1200                     if (usageinvimage)
1201                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1202                 } else {
1203                     if (usageimage)
1204                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1205                     if (usageinvimage)
1206                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1207                 }
1208                 UpdateNode un=mun.getUpdate(0);
1209                 String name=(String)updatenames.get(un);
1210                 if (inverse) {
1211                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1212                 } else {
1213                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1214                 }
1215             } else {
1216                 SetDescriptor sd=ip.setexpr.sd;
1217                 cr.outputline(sd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1218
1219                 UpdateNode un=mun.getUpdate(0);
1220                 /* Update for rule rule r */
1221                 String name=(String)updatenames.get(un);
1222                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1223             }
1224         }
1225     }
1226
1227     public static Vector getrulelist(Descriptor d) {
1228         Vector dispatchrules = new Vector();
1229         Vector rules = State.currentState.vRules;
1230
1231         for (int i = 0; i < rules.size(); i++) {
1232             Rule rule = (Rule) rules.elementAt(i);
1233             Set requiredsymbols = rule.getRequiredDescriptors();
1234             
1235             // #TBD#: in general this is wrong because these descriptors may contain descriptors
1236             // bound in "in?" expressions which need to be dealt with in a topologically sorted
1237             // fashion...
1238
1239             if (rule.getRequiredDescriptors().contains(d)) {
1240                 dispatchrules.addElement(rule);
1241             }
1242         }
1243         return dispatchrules;
1244     }
1245
1246     private boolean need_compensation(Rule r) {
1247         if (!Compiler.REPAIR)
1248             return false;
1249         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1250         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1251             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1252             GraphNode gn2=edge.getTarget();
1253             if (!removed.contains(gn2)) {
1254                 TermNode tn2=(TermNode)gn2.getOwner();
1255                 if (tn2.getType()==TermNode.CONSEQUENCE)
1256                     return false;
1257             }
1258         }
1259         return true;
1260     }
1261
1262     private UpdateNode find_compensation(Rule r) {
1263         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1264         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1265             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1266             GraphNode gn2=edge.getTarget();
1267             if (!removed.contains(gn2)) {
1268                 TermNode tn2=(TermNode)gn2.getOwner();
1269                 if (tn2.getType()==TermNode.UPDATE) {
1270                     MultUpdateNode mun=tn2.getUpdate();
1271                     for(int i=0;i<mun.numUpdates();i++) {
1272                         UpdateNode un=mun.getUpdate(i);
1273                         if (un.getRule()==r)
1274                             return un;
1275                     }
1276                 }
1277             }
1278         }
1279         throw new Error("No Compensation Update could be found");
1280     }
1281
1282     public void generate_dispatch(CodeWriter cr, RelationDescriptor rd, String leftvar, String rightvar) {
1283         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1284         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1285
1286         if (!(usageinvimage||usageimage)) /* not used at all*/
1287             return;
1288
1289         cr.outputline("// RELATION DISPATCH ");
1290         if (Compiler.REPAIR) {
1291             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1292             if (usageimage)
1293                 cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
1294             else
1295                 cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
1296
1297             cr.startblock(); {
1298                 /* Adding new item */
1299                 /* Perform safety checks */
1300                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1301                 cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
1302                 cr.startblock(); {
1303                     /* Have update to call into */
1304                     VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
1305                     cr.outputline("int "+mdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->getrelation2("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1306                     
1307                     String parttype="";
1308                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1309                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1310                             parttype=parttype+", int, int";
1311                         else
1312                             parttype=parttype+", int";
1313                     }
1314                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1315                     VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
1316                     
1317                     String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1318                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1319                         Quantifier q=currentrule.getQuantifier(i);
1320                         if (q instanceof SetQuantifier) {
1321                             SetQuantifier sq=(SetQuantifier) q;
1322                             methodcall+=","+sq.getVar().getSafeSymbol();
1323                         } else if (q instanceof RelationQuantifier) {
1324                             RelationQuantifier rq=(RelationQuantifier) q;
1325                             methodcall+=","+rq.x.getSafeSymbol();
1326                             methodcall+=","+rq.y.getSafeSymbol();
1327                         } else if (q instanceof ForQuantifier) {
1328                             ForQuantifier fq=(ForQuantifier) q;
1329                             methodcall+=","+fq.getVar().getSafeSymbol();
1330                         }
1331                     }
1332                     
1333                     
1334                 
1335                     cr.outputline("void *"+tmpptr.getSafeSymbol()+"=");
1336                     cr.outputline("(void *) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1337                     cr.outputline("if ("+mdfyptr.getSafeSymbol()+")");
1338                     {
1339                         cr.startblock();
1340                         cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol());
1341                         cr.outputline(methodcall+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
1342                         cr.endblock();
1343                     }
1344                     cr.outputline("else ");
1345                     {
1346                         cr.startblock();
1347                         cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol());
1348                         cr.outputline(methodcall+");");
1349                         cr.endblock();
1350                     }
1351                     cr.outputline("goto rebuild;");
1352                 }
1353                 cr.endblock();
1354                 
1355                 /* Build standard compensation actions */
1356                 if (need_compensation(currentrule)) {
1357                     UpdateNode un=find_compensation(currentrule);
1358                     String name=(String)updatenames.get(un);
1359                     usedupdates.add(un); /* Mark as used */
1360                     String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1361                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1362                         Quantifier q=currentrule.getQuantifier(i);
1363                         if (q instanceof SetQuantifier) {
1364                             SetQuantifier sq=(SetQuantifier) q;
1365                             methodcall+=","+sq.getVar().getSafeSymbol();
1366                         } else if (q instanceof RelationQuantifier) {
1367                             RelationQuantifier rq=(RelationQuantifier) q;
1368                             methodcall+=","+rq.x.getSafeSymbol();
1369                             methodcall+=","+rq.y.getSafeSymbol();
1370                         } else if (q instanceof ForQuantifier) {
1371                             ForQuantifier fq=(ForQuantifier) q;
1372                             methodcall+=","+fq.getVar().getSafeSymbol();
1373                         }
1374                     }
1375                     methodcall+=");";
1376                     cr.outputline(methodcall);
1377                     cr.outputline("goto rebuild;");
1378                 }
1379             }
1380             cr.endblock();
1381         }
1382
1383         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1384         cr.outputline("int " + addeditem + ";");
1385         if (rd.testUsage(RelationDescriptor.IMAGE)) {
1386             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar+ ");");
1387         }
1388         
1389         if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
1390             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
1391         }
1392         
1393
1394
1395         Vector dispatchrules = getrulelist(rd);
1396         
1397         Set toremove=new HashSet();
1398         for(int i=0;i<dispatchrules.size();i++) {
1399             Rule r=(Rule)dispatchrules.get(i);
1400             if (!ruleset.contains(r))
1401                 toremove.add(r);
1402         }
1403         dispatchrules.removeAll(toremove);
1404         if (dispatchrules.size() == 0) {
1405             cr.outputline("// nothing to dispatch");
1406             return;
1407         }
1408
1409         cr.outputline("if (" + addeditem + ")");
1410         cr.startblock();
1411        
1412         for(int i = 0; i < dispatchrules.size(); i++) {
1413             Rule rule = (Rule) dispatchrules.elementAt(i);
1414             if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
1415                 /* Guard depends on this relation, so we recomput everything */
1416                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1417             } else {
1418                 for (int j=0;j<rule.numQuantifiers();j++) {
1419                     Quantifier q=rule.getQuantifier(j);
1420                     if (q.getRequiredDescriptors().contains(rd)) {
1421                         /* Generate add */
1422                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+leftvar+","+rightvar+");");
1423                     }
1424                 }
1425             }
1426         }
1427
1428         cr.endblock();
1429     }
1430
1431
1432     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
1433                
1434         cr.outputline("// SET DISPATCH ");
1435         if (Compiler.REPAIR) {
1436             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1437             cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
1438             cr.startblock(); {
1439                 /* Adding new item */
1440                 /* Perform safety checks */
1441                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1442                 cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
1443                 cr.startblock(); {
1444                     /* Have update to call into */
1445                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1446                     String parttype="";
1447                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1448                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1449                             parttype=parttype+", int, int";
1450                         else
1451                             parttype=parttype+", int";
1452                     }
1453                     cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
1454                     cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
1455                     String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
1456                         repairtable.getSafeSymbol();
1457                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1458                         Quantifier q=currentrule.getQuantifier(i);
1459                         if (q instanceof SetQuantifier) {
1460                             SetQuantifier sq=(SetQuantifier) q;
1461                             methodcall+=","+sq.getVar().getSafeSymbol();
1462                         } else if (q instanceof RelationQuantifier) {
1463                             RelationQuantifier rq=(RelationQuantifier) q;
1464                             methodcall+=","+rq.x.getSafeSymbol();
1465                             methodcall+=","+rq.y.getSafeSymbol();
1466                         } else if (q instanceof ForQuantifier) {
1467                             ForQuantifier fq=(ForQuantifier) q;
1468                             methodcall+=","+fq.getVar().getSafeSymbol();
1469                         }
1470                     }
1471                     methodcall+=");";
1472                     cr.outputline(methodcall);
1473                     cr.outputline("goto rebuild;");
1474                 }
1475                 cr.endblock();
1476                 /* Build standard compensation actions */
1477                 if (need_compensation(currentrule)) {
1478                     UpdateNode un=find_compensation(currentrule);
1479                     String name=(String)updatenames.get(un);
1480                     usedupdates.add(un); /* Mark as used */
1481                     
1482                     String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
1483                         repairtable.getSafeSymbol();
1484                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1485                         Quantifier q=currentrule.getQuantifier(i);
1486                         if (q instanceof SetQuantifier) {
1487                             SetQuantifier sq=(SetQuantifier) q;
1488                             methodcall+=","+sq.getVar().getSafeSymbol();
1489                         } else if (q instanceof RelationQuantifier) {
1490                             RelationQuantifier rq=(RelationQuantifier) q;
1491                             methodcall+=","+rq.x.getSafeSymbol();
1492                             methodcall+=","+rq.y.getSafeSymbol();
1493                         } else if (q instanceof ForQuantifier) {
1494                             ForQuantifier fq=(ForQuantifier) q;
1495                             methodcall+=","+fq.getVar().getSafeSymbol();
1496                         }
1497                     }
1498                     methodcall+=");";
1499                     cr.outputline(methodcall);
1500                     cr.outputline("goto rebuild;");
1501                 }
1502             }
1503             cr.endblock();
1504         }
1505
1506         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1507         cr.outputline("int " + addeditem + " = 1;");
1508         cr.outputline(addeditem + " = " + sd.getSafeSymbol() + "_hash->add((int)" + setvar +  ", (int)" + setvar + ");");
1509         cr.startblock();
1510         Vector dispatchrules = getrulelist(sd);
1511
1512         Set toremove=new HashSet();
1513         for(int i=0;i<dispatchrules.size();i++) {
1514             Rule r=(Rule)dispatchrules.get(i);
1515             if (!ruleset.contains(r))
1516                 toremove.add(r);
1517         }
1518         dispatchrules.removeAll(toremove);
1519
1520         if (dispatchrules.size() == 0) {
1521             cr.outputline("// nothing to dispatch");
1522             cr.endblock();
1523             return;
1524         }
1525         cr.outputline("if ("+addeditem+")");
1526         cr.startblock();
1527         for(int i = 0; i < dispatchrules.size(); i++) {
1528             Rule rule = (Rule) dispatchrules.elementAt(i);
1529             if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
1530                 /* Guard depends on this relation, so we recompute everything */
1531                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1532             } else {
1533                 for (int j=0;j<rule.numQuantifiers();j++) {
1534                     Quantifier q=rule.getQuantifier(j);
1535                     if (SetDescriptor.expand(q.getRequiredDescriptors()).contains(sd)) {
1536                         /* Generate add */
1537                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+setvar+",0);");
1538                     }
1539                 }
1540             }
1541         }
1542         cr.endblock();
1543         cr.endblock();
1544     }
1545 }