Changes:
[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         for (int i = 0; i < constraints.size(); i++) {
636             Constraint constraint = (Constraint) constraints.elementAt(i); 
637             
638             {
639                 final SymbolTable st = constraint.getSymbolTable();
640                 CodeWriter cr = new StandardCodeWriter(outputaux);
641                 cr.pushSymbolTable(constraint.getSymbolTable());
642
643                 cr.outputline("// checking " + escape(constraint.toString()));
644                 cr.startblock();
645
646                 ListIterator quantifiers = constraint.quantifiers();
647
648                 while (quantifiers.hasNext()) {
649                     Quantifier quantifier = (Quantifier) quantifiers.next();
650                     quantifier.generate_open(cr);
651                 }
652
653                 cr.outputline("int maybe = 0;");
654                         
655                 /* now we have to generate the guard test */
656         
657                 VarDescriptor constraintboolean = VarDescriptor.makeNew("constraintboolean");
658                 constraint.getLogicStatement().generate(cr, constraintboolean);
659                 
660                 cr.outputline("if (maybe)");
661                 cr.startblock();
662                 cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
663                 cr.outputline("exit(1);");
664                 cr.endblock();
665
666                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
667                 cr.startblock();
668                 if (!Compiler.REPAIR)
669                     cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
670                 else {
671                 /* Do repairs */
672                 /* Build new repair table */
673                 cr.outputline("if ("+repairtable.getSafeSymbol()+")");
674                 cr.outputline("delete "+repairtable.getSafeSymbol()+";");
675                 cr.outputline(repairtable.getSafeSymbol()+"=new RepairHash();");
676
677                 
678                 /* Compute cost of each repair */
679                 VarDescriptor mincost=VarDescriptor.makeNew("mincost");
680                 VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
681                 DNFConstraint dnfconst=constraint.dnfconstraint;
682                 if (dnfconst.size()<=1) {
683                     cr.outputline("int "+mincostindex.getSafeSymbol()+"=0;");
684                 }
685                 if (dnfconst.size()>1) {
686                     cr.outputline("int "+mincostindex.getSafeSymbol()+";");
687                     boolean first=true;
688                     for(int j=0;j<dnfconst.size();j++) {
689                         Conjunction conj=dnfconst.get(j);
690                         GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
691                         if (removed.contains(gn))
692                             continue;
693                         
694                         VarDescriptor costvar;
695                         if (first) {
696                             costvar=mincost;
697                         } else
698                             costvar=VarDescriptor.makeNew("cost");
699                         for(int k=0;k<conj.size();k++) {
700                             DNFPredicate dpred=conj.get(k);
701                             Predicate p=dpred.getPredicate();
702                             boolean negate=dpred.isNegated();
703                             VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
704                             p.generate(cr,predvalue);
705                             if (negate)
706                                 cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
707                             else
708                                 cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
709                             if (k==0)
710                                 cr.outputline("int "+costvar.getSafeSymbol()+"="+cost.getCost(dpred)+";");
711                             else
712                                 cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
713                         }
714
715                         if(!first) {
716                             cr.outputline("if ("+costvar.getSafeSymbol()+"<"+mincost.getSafeSymbol()+")");
717                             cr.startblock();
718                             cr.outputline(mincost.getSafeSymbol()+"="+costvar.getSafeSymbol()+";");
719                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
720                             cr.endblock();
721                         } else
722                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
723                         first=false;
724                     }
725                 }
726                 cr.outputline("switch("+mincostindex.getSafeSymbol()+") {");
727                 for(int j=0;j<dnfconst.size();j++) {
728                     Conjunction conj=dnfconst.get(j);
729                     GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
730                     if (removed.contains(gn))
731                         continue;
732                     cr.outputline("case "+j+":");
733                     for(int k=0;k<conj.size();k++) {
734                         DNFPredicate dpred=conj.get(k);
735                         Predicate p=dpred.getPredicate();
736                         boolean negate=dpred.isNegated();
737                         VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
738                         p.generate(cr,predvalue);
739                         if (negate)
740                             cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
741                         else
742                             cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
743                         cr.startblock();
744                         if (p instanceof InclusionPredicate)
745                             generateinclusionrepair(conj,dpred, cr);
746                         else if (p instanceof ExprPredicate) {
747                             ExprPredicate ep=(ExprPredicate)p;
748                             if (ep.getType()==ExprPredicate.SIZE)
749                                 generatesizerepair(conj,dpred,cr);
750                             else if (ep.getType()==ExprPredicate.COMPARISON)
751                                 generatecomparisonrepair(conj,dpred,cr);
752                         } else throw new Error("Unrecognized Predicate");
753                         cr.endblock();
754                     }
755                     /* Update model */
756                     cr.outputline("break;");
757                 }
758                 cr.outputline("}");
759
760                 cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
761                 cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
762                 cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
763                 cr.outputline("goto rebuild;");  /* Rebuild model and all */
764                 }
765                 cr.endblock();
766                 
767                 while (quantifiers.hasPrevious()) {
768                     Quantifier quantifier = (Quantifier) quantifiers.previous();
769                     cr.endblock();
770                 }
771                 cr.endblock();
772                 cr.outputline("");
773                 cr.outputline("");
774             }
775         }
776         CodeWriter cr = new StandardCodeWriter(outputaux);
777         cr.startblock();
778         cr.outputline("if ("+repairtable.getSafeSymbol()+")");
779         cr.outputline("delete "+repairtable.getSafeSymbol()+";");
780         cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
781         cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
782         cr.outputline("delete "+newmodel.getSafeSymbol()+";");
783         cr.outputline("delete "+worklist.getSafeSymbol()+";");
784         cr.outputline("resettypemap();");
785         cr.outputline("break;");
786         cr.endblock();
787         cr.outputline("rebuild:");
788         cr.outputline(";");     
789         
790     }
791     
792     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
793         MultUpdateNode mun=null;
794         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
795         for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
796             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
797             TermNode tn2=(TermNode)gn2.getOwner();
798             if (tn2.getType()==TermNode.ABSTRACT) {
799                 AbstractRepair ar=tn2.getAbstract();
800                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
801                     ar.getPredicate()==dpred) {
802                     for(Iterator edgeit2=gn2.edges();edgeit2.hasNext();) {
803                         GraphNode gn3=((GraphNode.Edge) edgeit2.next()).getTarget();
804                         if (!removed.contains(gn3)) {
805                             TermNode tn3=(TermNode)gn3.getOwner();
806                             if (tn3.getType()==TermNode.UPDATE) {
807                                 mun=tn3.getUpdate();
808                                 break;
809                             }
810                         }
811                     }
812                 }
813             }
814         }
815         return mun;
816     }
817
818     /** Generates abstract (and concrete) repair for a comparison */
819
820     private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
821         MultUpdateNode munmodify=getmultupdatenode(conj,dpred,AbstractRepair.MODIFYRELATION);
822         MultUpdateNode munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
823         MultUpdateNode munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
824         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
825         RelationDescriptor rd=(RelationDescriptor)ep.getDescriptor();
826         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
827         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
828         boolean inverted=ep.inverted();
829         boolean negated=dpred.isNegated();
830         OpExpr expr=(OpExpr)ep.expr;
831         Opcode opcode=expr.getOpcode();
832         VarDescriptor leftside=VarDescriptor.makeNew("leftside");
833         VarDescriptor rightside=VarDescriptor.makeNew("rightside");
834         VarDescriptor newvalue=VarDescriptor.makeNew("newvalue");
835         if (!inverted) {
836             expr.getLeftExpr().generate(cr,leftside);
837             expr.getRightExpr().generate(cr,newvalue);
838             cr.outputline(rd.getRange().getType().getGenerateType().getSafeSymbol()+" "+rightside.getSafeSymbol()+";");
839             cr.outputline(rd.getSafeSymbol()+"_hash->get("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
840         } else {
841             expr.getLeftExpr().generate(cr,rightside);
842             expr.getRightExpr().generate(cr,newvalue);
843             cr.outputline(rd.getDomain().getType().getGenerateType().getSafeSymbol()+" "+leftside.getSafeSymbol()+";");
844             cr.outputline(rd.getSafeSymbol()+"_hashinv->get("+leftside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
845         }
846         if (negated)
847             if (opcode==Opcode.GT) {
848                 opcode=Opcode.LE;
849             } else if (opcode==Opcode.GE) {
850                 opcode=Opcode.LT;
851             } else if (opcode==Opcode.LT) {
852                 opcode=Opcode.GE;
853             } else if (opcode==Opcode.LE) {
854                 opcode=Opcode.GT;
855             } else if (opcode==Opcode.EQ) {
856                 opcode=Opcode.NE;
857             } else if (opcode==Opcode.NE) {
858                 opcode=Opcode.EQ;
859             } else {
860                 throw new Error("Unrecognized Opcode");
861             }
862
863         if (opcode==Opcode.GT) {
864             cr.outputline(newvalue.getSafeSymbol()+"++;");
865         } else if (opcode==Opcode.GE) {
866             /* Equal */
867         } else if (opcode==Opcode.LT) {
868             cr.outputline(newvalue.getSafeSymbol()+"--;");
869         } else if (opcode==Opcode.LE) {
870             /* Equal */
871         } else if (opcode==Opcode.EQ) {
872             /* Equal */
873         } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
874             cr.outputline(newvalue.getSafeSymbol()+"++;");
875         } else {
876             throw new Error("Unrecognized Opcode");
877         }
878         /* Do abstract repairs */
879         if (usageimage) {
880             cr.outputline(rd.getSafeSymbol()+"_hash->remove("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
881             if (!inverted) {
882                 cr.outputline(rd.getSafeSymbol()+"_hash->add("+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
883             } else {
884                 cr.outputline(rd.getSafeSymbol()+"_hash->add("+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
885             }
886         }
887         if (usageinvimage) {
888             cr.outputline(rd.getSafeSymbol()+"_hashinv->remove("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
889             if (!inverted) {
890                 cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newvalue.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
891             } else {
892                 cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+rightside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
893             }
894         }
895         /* Do concrete repairs */
896         if (munmodify!=null) {
897             for(int i=0;i<state.vRules.size();i++) {
898                 Rule r=(Rule)state.vRules.get(i);
899                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
900                     for(int j=0;j<munmodify.numUpdates();j++) {
901                         UpdateNode un=munmodify.getUpdate(j);
902                         if (un.getRule()==r) {
903                             /* Update for rule r */
904                             String name=(String)updatenames.get(un);
905                             cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
906                         }
907                     }
908                 }
909             }
910
911         } else {
912             /* Start with scheduling removal */
913             for(int i=0;i<state.vRules.size();i++) {
914                 Rule r=(Rule)state.vRules.get(i);
915                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
916                     for(int j=0;j<munremove.numUpdates();j++) {
917                         UpdateNode un=munremove.getUpdate(i);
918                         if (un.getRule()==r) {
919                             /* Update for rule r */
920                             String name=(String)updatenames.get(un);
921                             cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
922                         }
923                     }
924                 }
925             }
926             /* Now do addition */
927             UpdateNode un=munadd.getUpdate(0);
928             String name=(String)updatenames.get(un);
929             if (!inverted) {
930                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
931             } else {
932                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
933             }
934         }
935     }
936
937     public void generatesizerepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr) {
938         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
939         OpExpr expr=(OpExpr)ep.expr;
940         Opcode opcode=expr.getOpcode();
941         opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
942
943         MultUpdateNode munremove;
944
945         MultUpdateNode munadd;
946         if (ep.getDescriptor() instanceof RelationDescriptor) {
947             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
948             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
949         } else {
950             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
951             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
952         }
953         int size=ep.rightSize();
954         VarDescriptor sizevar=VarDescriptor.makeNew("size");
955         ((OpExpr)expr).left.generate(cr, sizevar);
956         VarDescriptor change=VarDescriptor.makeNew("change");
957         cr.outputline("int "+change.getSafeSymbol()+";");
958         boolean generateadd=false;
959         boolean generateremove=false;
960         if (opcode==Opcode.GT) {
961             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
962             generateadd=true;
963             generateremove=false;
964         } else if (opcode==Opcode.GE) {
965             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
966             generateadd=true;
967             generateremove=false;
968         } else if (opcode==Opcode.LT) {
969             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size-1)+"-"+sizevar.getSafeSymbol()+";");
970             generateadd=false;
971             generateremove=true;
972         } else if (opcode==Opcode.LE) {
973             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
974             generateadd=false;
975             generateremove=true;
976         } else if (opcode==Opcode.EQ) {
977             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
978             if (size==0)
979                 generateadd=false;
980             else 
981                 generateadd=true;
982             generateremove=true;
983         } else if (opcode==Opcode.NE) {
984             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
985             generateadd=true;
986             generateremove=false;
987         } else {
988             throw new Error("Unrecognized Opcode");
989         }
990
991 // In some cases the analysis has determined that generating removes
992 // is unnecessary
993         if (generateremove&&munremove==null) 
994             generateremove=false;
995
996         Descriptor d=ep.getDescriptor();
997         if (generateremove) {
998             cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
999             cr.startblock();
1000             /* Find element to remove */
1001             VarDescriptor leftvar=VarDescriptor.makeNew("leftvar");
1002             VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
1003             if (d instanceof RelationDescriptor) {
1004                 if (ep.inverted()) {
1005                     rightvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
1006                     cr.outputline("int "+leftvar.getSafeSymbol()+";");
1007                     cr.outputline(d.getSafeSymbol()+"_hashinv->get((int)"+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1008                 } else {
1009                     leftvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
1010                     cr.outputline("int "+rightvar.getSafeSymbol()+"=0;");
1011                     cr.outputline(d.getSafeSymbol()+"_hash->get((int)"+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1012                 }
1013             } else {
1014                 cr.outputline("int "+leftvar.getSafeSymbol()+"="+d.getSafeSymbol()+"_hash->firstkey();");
1015             }
1016             /* Generate abstract remove instruction */
1017             if (d instanceof RelationDescriptor) {
1018                 RelationDescriptor rd=(RelationDescriptor) d;
1019                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1020                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1021                 if (usageimage)
1022                     cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1023                 if (usageinvimage)
1024                     cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1025             } else {
1026                 cr.outputline(d.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1027             }
1028             /* Generate concrete remove instruction */
1029             for(int i=0;i<state.vRules.size();i++) {
1030                 Rule r=(Rule)state.vRules.get(i);
1031                 if (r.getInclusion().getTargetDescriptors().contains(d)) {
1032                     for(int j=0;j<munremove.numUpdates();j++) {
1033                         UpdateNode un=munremove.getUpdate(j);
1034                         if (un.getRule()==r) {
1035                                 /* Update for rule rule r */
1036                             String name=(String)updatenames.get(un);
1037                             if (d instanceof RelationDescriptor) {
1038                                 cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1039                             } else {
1040                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1041                             }
1042                         }
1043                     }
1044                 }
1045             }
1046             cr.endblock();
1047         }
1048         if (generateadd) {
1049
1050             cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
1051             cr.startblock();
1052             VarDescriptor newobject=VarDescriptor.makeNew("newobject");
1053             if (d instanceof RelationDescriptor) {
1054                 VarDescriptor otherside=((ImageSetExpr)((SizeofExpr)((OpExpr)ep.expr).left).setexpr).vd;
1055                 RelationDescriptor rd=(RelationDescriptor)d;
1056                 if (sources.relsetSource(rd,!ep.inverted())) {
1057                     /* Set Source */
1058                     SetDescriptor sd=sources.relgetSourceSet(rd,!ep.inverted());
1059                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1060                     cr.outputline(sd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1061                     cr.outputline("for("+iterator.getSafeSymbol()+"="+sd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
1062                     cr.startblock();
1063                     if (ep.inverted()) {
1064                         cr.outputline("if !"+rd.getSafeSymbol()+"_hashinv->contains("+iterator.getSafeSymbol()+"->key(),"+otherside.getSafeSymbol()+")");
1065                     } else {
1066                         cr.outputline("if !"+rd.getSafeSymbol()+"_hash->contains("+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+"->key())");
1067                     }
1068                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1069                     cr.outputline(iterator.getSafeSymbol()+"->next();");
1070                     cr.endblock();
1071                 } else if (sources.relallocSource(rd,!ep.inverted())) {
1072                     /* Allocation Source*/
1073                     sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
1074                 } else throw new Error("No source for adding to Relation");
1075                 if (ep.inverted()) {
1076                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1077                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1078                     if (usageimage)
1079                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1080                     if (usageinvimage)
1081                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1082
1083                     UpdateNode un=munadd.getUpdate(0);
1084                     String name=(String)updatenames.get(un);
1085                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1086                 } else {
1087                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1088                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1089                     if (usageimage)
1090                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1091                     if (usageinvimage)
1092                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1093                     UpdateNode un=munadd.getUpdate(0);
1094                     String name=(String)updatenames.get(un);
1095                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1096                 }
1097             } else {
1098                 SetDescriptor sd=(SetDescriptor)d;
1099                 if (sources.setSource(sd)) {
1100                     /* Set Source */
1101                     /* Set Source */
1102                     SetDescriptor sourcesd=sources.getSourceSet(sd);
1103                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1104                     cr.outputline(sourcesd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1105                     cr.outputline("for("+iterator.getSafeSymbol()+"="+sourcesd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
1106                     cr.startblock();
1107                     cr.outputline("if !"+sd.getSafeSymbol()+"_hash->contains("+iterator.getSafeSymbol()+"->key())");
1108                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1109                     cr.outputline(iterator.getSafeSymbol()+"->next();");
1110                     cr.endblock();
1111                 } else if (sources.allocSource(sd)) {
1112                     /* Allocation Source*/
1113                     sources.generateSourceAlloc(cr,newobject,sd);
1114                 } else throw new Error("No source for adding to Set");
1115                 cr.outputline(sd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1116                 UpdateNode un=munadd.getUpdate(0);
1117                 String name=(String)updatenames.get(un);
1118                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1119             }
1120             cr.endblock();
1121         }
1122     }
1123
1124     public void generateinclusionrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1125         InclusionPredicate ip=(InclusionPredicate) dpred.getPredicate();
1126         boolean negated=dpred.isNegated();
1127         MultUpdateNode mun=getmultupdatenode(conj,dpred,-1);
1128         VarDescriptor leftvar=VarDescriptor.makeNew("left");
1129         ip.expr.generate(cr, leftvar);
1130
1131         if (negated) {
1132             if (ip.setexpr instanceof ImageSetExpr) {
1133                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1134                 VarDescriptor rightvar=ise.getVar();
1135                 boolean inverse=ise.inverted();
1136                 RelationDescriptor rd=ise.getRelation();
1137                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1138                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1139                 if (inverse) {
1140                     if (usageimage)
1141                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1142                     if (usageinvimage)
1143                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1144                 } else {
1145                     if (usageimage)
1146                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1147                     if (usageinvimage)
1148                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1149                 }
1150                 for(int i=0;i<state.vRules.size();i++) {
1151                     Rule r=(Rule)state.vRules.get(i);
1152                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1153                         for(int j=0;j<mun.numUpdates();j++) {
1154                             UpdateNode un=mun.getUpdate(i);
1155                             if (un.getRule()==r) {
1156                                 /* Update for rule rule r */
1157                                 String name=(String)updatenames.get(un);
1158                                 if (inverse) {
1159                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1160                                 } else {
1161                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1162                                 }
1163                             }
1164                         }
1165                     }
1166                 }
1167             } else {
1168                 SetDescriptor sd=ip.setexpr.sd;
1169                 cr.outputline(sd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1170
1171                 for(int i=0;i<state.vRules.size();i++) {
1172                     Rule r=(Rule)state.vRules.get(i);
1173                     if (r.getInclusion().getTargetDescriptors().contains(sd)) {
1174                         for(int j=0;j<mun.numUpdates();j++) {
1175                             UpdateNode un=mun.getUpdate(i);
1176                             if (un.getRule()==r) {
1177                                 /* Update for rule rule r */
1178                                 String name=(String)updatenames.get(un);
1179                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+sd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1180                             }
1181                         }
1182                     }
1183                 }
1184             }
1185         } else {
1186             /* Generate update */
1187             if (ip.setexpr instanceof ImageSetExpr) {
1188                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1189                 VarDescriptor rightvar=ise.getVar();
1190                 boolean inverse=ise.inverted();
1191                 RelationDescriptor rd=ise.getRelation();
1192                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1193                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1194                 if (inverse) {
1195                     if (usageimage)
1196                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1197                     if (usageinvimage)
1198                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1199                 } else {
1200                     if (usageimage)
1201                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1202                     if (usageinvimage)
1203                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1204                 }
1205                 UpdateNode un=mun.getUpdate(0);
1206                 String name=(String)updatenames.get(un);
1207                 if (inverse) {
1208                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1209                 } else {
1210                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1211                 }
1212             } else {
1213                 SetDescriptor sd=ip.setexpr.sd;
1214                 cr.outputline(sd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1215
1216                 UpdateNode un=mun.getUpdate(0);
1217                 /* Update for rule rule r */
1218                 String name=(String)updatenames.get(un);
1219                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1220             }
1221         }
1222     }
1223
1224     public static Vector getrulelist(Descriptor d) {
1225         Vector dispatchrules = new Vector();
1226         Vector rules = State.currentState.vRules;
1227
1228         for (int i = 0; i < rules.size(); i++) {
1229             Rule rule = (Rule) rules.elementAt(i);
1230             Set requiredsymbols = rule.getRequiredDescriptors();
1231             
1232             // #TBD#: in general this is wrong because these descriptors may contain descriptors
1233             // bound in "in?" expressions which need to be dealt with in a topologically sorted
1234             // fashion...
1235
1236             if (rule.getRequiredDescriptors().contains(d)) {
1237                 dispatchrules.addElement(rule);
1238             }
1239         }
1240         return dispatchrules;
1241     }
1242
1243     private boolean need_compensation(Rule r) {
1244         if (!Compiler.REPAIR)
1245             return false;
1246         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1247         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1248             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1249             GraphNode gn2=edge.getTarget();
1250             if (!removed.contains(gn2)) {
1251                 TermNode tn2=(TermNode)gn2.getOwner();
1252                 if (tn2.getType()==TermNode.CONSEQUENCE)
1253                     return false;
1254             }
1255         }
1256         return true;
1257     }
1258
1259     private UpdateNode find_compensation(Rule r) {
1260         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1261         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1262             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1263             GraphNode gn2=edge.getTarget();
1264             if (!removed.contains(gn2)) {
1265                 TermNode tn2=(TermNode)gn2.getOwner();
1266                 if (tn2.getType()==TermNode.UPDATE) {
1267                     MultUpdateNode mun=tn2.getUpdate();
1268                     for(int i=0;i<mun.numUpdates();i++) {
1269                         UpdateNode un=mun.getUpdate(i);
1270                         if (un.getRule()==r)
1271                             return un;
1272                     }
1273                 }
1274             }
1275         }
1276         throw new Error("No Compensation Update could be found");
1277     }
1278
1279     public void generate_dispatch(CodeWriter cr, RelationDescriptor rd, String leftvar, String rightvar) {
1280         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1281         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1282
1283         if (!(usageinvimage||usageimage)) /* not used at all*/
1284             return;
1285
1286         cr.outputline("// RELATION DISPATCH ");
1287         if (Compiler.REPAIR) {
1288             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1289             if (usageimage)
1290                 cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
1291             else
1292                 cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
1293
1294             cr.startblock(); {
1295                 /* Adding new item */
1296                 /* Perform safety checks */
1297                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1298                 cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
1299                 cr.startblock(); {
1300                     /* Have update to call into */
1301                     VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
1302                     cr.outputline("int "+mdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->getrelation2("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1303                     
1304                     String parttype="";
1305                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1306                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1307                             parttype=parttype+", int, int";
1308                         else
1309                             parttype=parttype+", int";
1310                     }
1311                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1312                     VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
1313                     
1314                     String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1315                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1316                         Quantifier q=currentrule.getQuantifier(i);
1317                         if (q instanceof SetQuantifier) {
1318                             SetQuantifier sq=(SetQuantifier) q;
1319                             methodcall+=","+sq.getVar().getSafeSymbol();
1320                         } else if (q instanceof RelationQuantifier) {
1321                             RelationQuantifier rq=(RelationQuantifier) q;
1322                             methodcall+=","+rq.x.getSafeSymbol();
1323                             methodcall+=","+rq.y.getSafeSymbol();
1324                         } else if (q instanceof ForQuantifier) {
1325                             ForQuantifier fq=(ForQuantifier) q;
1326                             methodcall+=","+fq.getVar().getSafeSymbol();
1327                         }
1328                     }
1329                     
1330                     
1331                 
1332                     cr.outputline("void *"+tmpptr.getSafeSymbol()+"=");
1333                     cr.outputline("(void *) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1334                     cr.outputline("if ("+mdfyptr.getSafeSymbol()+")");
1335                     {
1336                         cr.startblock();
1337                         cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol());
1338                         cr.outputline(methodcall+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
1339                         cr.endblock();
1340                     }
1341                     cr.outputline("else ");
1342                     {
1343                         cr.startblock();
1344                         cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol());
1345                         cr.outputline(methodcall+");");
1346                         cr.endblock();
1347                     }
1348                     cr.outputline("goto rebuild;");
1349                 }
1350                 cr.endblock();
1351                 
1352                 /* Build standard compensation actions */
1353                 if (need_compensation(currentrule)) {
1354                     UpdateNode un=find_compensation(currentrule);
1355                     String name=(String)updatenames.get(un);
1356                     usedupdates.add(un); /* Mark as used */
1357                     String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1358                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1359                         Quantifier q=currentrule.getQuantifier(i);
1360                         if (q instanceof SetQuantifier) {
1361                             SetQuantifier sq=(SetQuantifier) q;
1362                             methodcall+=","+sq.getVar().getSafeSymbol();
1363                         } else if (q instanceof RelationQuantifier) {
1364                             RelationQuantifier rq=(RelationQuantifier) q;
1365                             methodcall+=","+rq.x.getSafeSymbol();
1366                             methodcall+=","+rq.y.getSafeSymbol();
1367                         } else if (q instanceof ForQuantifier) {
1368                             ForQuantifier fq=(ForQuantifier) q;
1369                             methodcall+=","+fq.getVar().getSafeSymbol();
1370                         }
1371                     }
1372                     methodcall+=");";
1373                     cr.outputline(methodcall);
1374                     cr.outputline("goto rebuild;");
1375                 }
1376             }
1377             cr.endblock();
1378         }
1379
1380         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1381         cr.outputline("int " + addeditem + ";");
1382         if (rd.testUsage(RelationDescriptor.IMAGE)) {
1383             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar+ ");");
1384         }
1385         
1386         if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
1387             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
1388         }
1389         
1390
1391
1392         Vector dispatchrules = getrulelist(rd);
1393         
1394         Set toremove=new HashSet();
1395         for(int i=0;i<dispatchrules.size();i++) {
1396             Rule r=(Rule)dispatchrules.get(i);
1397             if (!ruleset.contains(r))
1398                 toremove.add(r);
1399         }
1400         dispatchrules.removeAll(toremove);
1401         if (dispatchrules.size() == 0) {
1402             cr.outputline("// nothing to dispatch");
1403             return;
1404         }
1405
1406         cr.outputline("if (" + addeditem + ")");
1407         cr.startblock();
1408        
1409         for(int i = 0; i < dispatchrules.size(); i++) {
1410             Rule rule = (Rule) dispatchrules.elementAt(i);
1411             if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
1412                 /* Guard depends on this relation, so we recomput everything */
1413                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1414             } else {
1415                 for (int j=0;j<rule.numQuantifiers();j++) {
1416                     Quantifier q=rule.getQuantifier(j);
1417                     if (q.getRequiredDescriptors().contains(rd)) {
1418                         /* Generate add */
1419                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+leftvar+","+rightvar+");");
1420                     }
1421                 }
1422             }
1423         }
1424
1425         cr.endblock();
1426     }
1427
1428
1429     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
1430                
1431         cr.outputline("// SET DISPATCH ");
1432         if (Compiler.REPAIR) {
1433             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1434             cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
1435             cr.startblock(); {
1436                 /* Adding new item */
1437                 /* Perform safety checks */
1438                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1439                 cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
1440                 cr.startblock(); {
1441                     /* Have update to call into */
1442                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1443                     String parttype="";
1444                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1445                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1446                             parttype=parttype+", int, int";
1447                         else
1448                             parttype=parttype+", int";
1449                     }
1450                     cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
1451                     cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
1452                     String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
1453                         repairtable.getSafeSymbol();
1454                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1455                         Quantifier q=currentrule.getQuantifier(i);
1456                         if (q instanceof SetQuantifier) {
1457                             SetQuantifier sq=(SetQuantifier) q;
1458                             methodcall+=","+sq.getVar().getSafeSymbol();
1459                         } else if (q instanceof RelationQuantifier) {
1460                             RelationQuantifier rq=(RelationQuantifier) q;
1461                             methodcall+=","+rq.x.getSafeSymbol();
1462                             methodcall+=","+rq.y.getSafeSymbol();
1463                         } else if (q instanceof ForQuantifier) {
1464                             ForQuantifier fq=(ForQuantifier) q;
1465                             methodcall+=","+fq.getVar().getSafeSymbol();
1466                         }
1467                     }
1468                     methodcall+=");";
1469                     cr.outputline(methodcall);
1470                     cr.outputline("goto rebuild;");
1471                 }
1472                 cr.endblock();
1473                 /* Build standard compensation actions */
1474                 if (need_compensation(currentrule)) {
1475                     UpdateNode un=find_compensation(currentrule);
1476                     String name=(String)updatenames.get(un);
1477                     usedupdates.add(un); /* Mark as used */
1478                     
1479                     String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
1480                         repairtable.getSafeSymbol();
1481                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1482                         Quantifier q=currentrule.getQuantifier(i);
1483                         if (q instanceof SetQuantifier) {
1484                             SetQuantifier sq=(SetQuantifier) q;
1485                             methodcall+=","+sq.getVar().getSafeSymbol();
1486                         } else if (q instanceof RelationQuantifier) {
1487                             RelationQuantifier rq=(RelationQuantifier) q;
1488                             methodcall+=","+rq.x.getSafeSymbol();
1489                             methodcall+=","+rq.y.getSafeSymbol();
1490                         } else if (q instanceof ForQuantifier) {
1491                             ForQuantifier fq=(ForQuantifier) q;
1492                             methodcall+=","+fq.getVar().getSafeSymbol();
1493                         }
1494                     }
1495                     methodcall+=");";
1496                     cr.outputline(methodcall);
1497                     cr.outputline("goto rebuild;");
1498                 }
1499             }
1500             cr.endblock();
1501         }
1502
1503         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1504         cr.outputline("int " + addeditem + " = 1;");
1505         cr.outputline(addeditem + " = " + sd.getSafeSymbol() + "_hash->add((int)" + setvar +  ", (int)" + setvar + ");");
1506         cr.startblock();
1507         Vector dispatchrules = getrulelist(sd);
1508
1509         Set toremove=new HashSet();
1510         for(int i=0;i<dispatchrules.size();i++) {
1511             Rule r=(Rule)dispatchrules.get(i);
1512             if (!ruleset.contains(r))
1513                 toremove.add(r);
1514         }
1515         dispatchrules.removeAll(toremove);
1516
1517         if (dispatchrules.size() == 0) {
1518             cr.outputline("// nothing to dispatch");
1519             cr.endblock();
1520             return;
1521         }
1522         cr.outputline("if ("+addeditem+")");
1523         cr.startblock();
1524         for(int i = 0; i < dispatchrules.size(); i++) {
1525             Rule rule = (Rule) dispatchrules.elementAt(i);
1526             if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
1527                 /* Guard depends on this relation, so we recompute everything */
1528                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1529             } else {
1530                 for (int j=0;j<rule.numQuantifiers();j++) {
1531                     Quantifier q=rule.getQuantifier(j);
1532                     if (SetDescriptor.expand(q.getRequiredDescriptors()).contains(sd)) {
1533                         /* Generate add */
1534                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+setvar+",0);");
1535                     }
1536                 }
1537             }
1538         }
1539         cr.endblock();
1540         cr.endblock();
1541     }
1542 }