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