Change to the spec...missed a consistency property. Adding timing option.
[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         if (Compiler.ALLOCATECPLUSPLUS) {
391             for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
392                 TypeDescriptor td=(TypeDescriptor)it.next();
393                 if (td instanceof StructureTypeDescriptor) {
394                     if (((StructureTypeDescriptor)td).size()>0) {
395                         FieldDescriptor fd=((StructureTypeDescriptor)td).get(0);
396                         if (fd.getSymbol().startsWith("_vptr_")) {
397                             String vtable="_ZTV";
398                             vtable+=td.getSymbol().length();
399                             vtable+=td.getSymbol();
400                             craux.outputline("extern void * "+vtable+";");
401                         }
402                     }
403                 }
404             }
405         }
406         craux.outputline(name+"::"+name+"() {");
407         craux.outputline("// creating hashtables ");
408         
409         /* build sets */
410         Iterator sets = state.stSets.descriptors();
411         
412         /* first pass create all the hash tables */
413         while (sets.hasNext()) {
414             SetDescriptor set = (SetDescriptor) sets.next();
415             crhead.outputline("SimpleHash* " + set.getSafeSymbol() + "_hash;");
416             craux.outputline(set.getSafeSymbol() + "_hash = new SimpleHash();");
417         }
418         
419         /* second pass build relationships between hashtables */
420         sets = state.stSets.descriptors();
421         
422         while (sets.hasNext()) {
423             SetDescriptor set = (SetDescriptor) sets.next();
424             Iterator subsets = set.subsets();
425             
426             while (subsets.hasNext()) {
427                 SetDescriptor subset = (SetDescriptor) subsets.next();                
428                 craux.outputline(subset.getSafeSymbol() + "_hash->addParent(" + set.getSafeSymbol() + "_hash);");
429             }
430         } 
431
432         /* build relations */
433         Iterator relations = state.stRelations.descriptors();
434         
435         /* first pass create all the hash tables */
436         while (relations.hasNext()) {
437             RelationDescriptor relation = (RelationDescriptor) relations.next();
438             
439             if (relation.testUsage(RelationDescriptor.IMAGE)) {
440                 crhead.outputline("SimpleHash* " + relation.getSafeSymbol() + "_hash;");
441                 craux.outputline(relation.getSafeSymbol() + "_hash = new SimpleHash();");
442             }
443
444             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
445                 crhead.outputline("SimpleHash* " + relation.getSafeSymbol() + "_hashinv;");
446                 craux.outputline(relation.getSafeSymbol() + "_hashinv = new SimpleHash();");
447             } 
448         }
449
450         craux.outputline("}");
451         crhead.outputline("};");
452         craux.outputline(name+"::~"+name+"() {");
453         craux.outputline("// deleting hashtables");
454
455         /* build destructor */
456         sets = state.stSets.descriptors();
457         
458         /* first pass create all the hash tables */
459         while (sets.hasNext()) {
460             SetDescriptor set = (SetDescriptor) sets.next();
461             craux.outputline("delete "+set.getSafeSymbol() + "_hash;");
462         } 
463         
464         /* destroy relations */
465         relations = state.stRelations.descriptors();
466         
467         /* first pass create all the hash tables */
468         while (relations.hasNext()) {
469             RelationDescriptor relation = (RelationDescriptor) relations.next();
470             
471             if (relation.testUsage(RelationDescriptor.IMAGE)) {
472                 craux.outputline("delete "+relation.getSafeSymbol() + "_hash;");
473             }
474
475             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
476                 craux.outputline("delete " + relation.getSafeSymbol() + "_hashinv;");
477             } 
478         }
479         craux.outputline("}");
480     }
481
482     private void generate_start() {
483         CodeWriter crhead = new StandardCodeWriter(outputhead);
484         CodeWriter craux = new StandardCodeWriter(outputaux);
485         oldmodel=VarDescriptor.makeNew("oldmodel");
486         newmodel=VarDescriptor.makeNew("newmodel");
487         worklist=VarDescriptor.makeNew("worklist");
488         goodflag=VarDescriptor.makeNew("goodflag");
489         repairtable=VarDescriptor.makeNew("repairtable");
490
491         if (Compiler.GENERATEINSTRUMENT) {
492             craux.outputline("int updatecount;");
493             craux.outputline("int rebuildcount;");
494             craux.outputline("int abstractcount;");
495         }
496         
497         crhead.outputline("void doanalysis();");
498         craux.outputline("void "+name +"_state::doanalysis()");
499         craux.startblock();
500         if (Compiler.TIME) {
501             craux.outputline("struct timeval _begin_time,_end_time;");
502             craux.outputline("gettimeofday(&_begin_time,NULL);");
503         }
504
505         if (Compiler.GENERATEINSTRUMENT) {
506             craux.outputline("updatecount=0;");
507             craux.outputline("rebuildcount=0;");
508             craux.outputline("abstractcount=0;");
509         }
510         craux.outputline("int highmark;");
511         craux.outputline("initializestack(&highmark);");
512         craux.outputline("typeobject *typeobject1=gettypeobject();");
513         craux.outputline("typeobject1->computesizes(this);");
514         craux.outputline("recomputesizes();");
515         craux.outputline(name+ " * "+oldmodel.getSafeSymbol()+"=0;");
516         craux.outputline("WorkList * "+worklist.getSafeSymbol()+" = new WorkList();");
517         craux.outputline("RepairHash * "+repairtable.getSafeSymbol()+"=0;");
518         craux.outputline("while (1)");
519         craux.startblock();
520         craux.outputline(name+ " * "+newmodel.getSafeSymbol()+"=new "+name+"();");
521         craux.outputline(worklist.getSafeSymbol()+"->reset();");
522         if (Compiler.GENERATEINSTRUMENT)
523             craux.outputline("rebuildcount++;");
524     }
525     
526     private void generate_teardown() {
527         CodeWriter cr = new StandardCodeWriter(outputaux);        
528         cr.endblock();
529         if (Compiler.TIME) {
530             cr.outputline("gettimeofday(&_end_time,NULL);");
531             cr.outputline("printf(\"time=%ld uS\\n\",(_end_time.tv_sec-_begin_time.tv_sec)*1000000+_end_time.tv_usec-_begin_time.tv_usec)");
532         }
533
534         if (Compiler.GENERATEINSTRUMENT) {
535             cr.outputline("printf(\"updatecount=%d\\n\",updatecount);");
536             cr.outputline("printf(\"rebuildcount=%d\\n\",rebuildcount);");
537             cr.outputline("printf(\"abstractcount=%d\\n\",abstractcount);");
538         }
539
540     }
541
542     private void generate_print() {
543         
544         final SymbolTable st = new SymbolTable();
545
546         CodeWriter cr = new StandardCodeWriter(outputaux) {
547                 public SymbolTable getSymbolTable() { return st; }
548             };
549
550         cr.outputline("// printing sets!");
551         cr.outputline("printf(\"\\n\\nPRINTING SETS AND RELATIONS\\n\");");
552
553         Iterator setiterator = state.stSets.descriptors();
554         while (setiterator.hasNext()) {
555             SetDescriptor sd = (SetDescriptor) setiterator.next();
556             if (sd.getSymbol().equals("int") || sd.getSymbol().equals("token")) {
557                 continue;
558             }
559
560             String setname = sd.getSafeSymbol();
561
562             cr.startblock();
563             cr.outputline("// printing set " + setname);
564             cr.outputline("printf(\"\\nPrinting set " + sd.getSymbol() + " - %d elements \\n\", " + setname + "_hash->count());");
565             cr.outputline("SimpleIterator __setiterator;");
566             cr.outputline("" + setname + "_hash->iterator(__setiterator);");
567             cr.outputline("while (__setiterator.hasNext())");
568             cr.startblock();
569             cr.outputline("int __setval = (int) __setiterator.next();");
570
571             TypeDescriptor td = sd.getType();
572             if (td instanceof StructureTypeDescriptor) {
573                 StructureTypeDescriptor std = (StructureTypeDescriptor) td;
574                 VarDescriptor vd = new VarDescriptor ("__setval", "__setval", td, false);
575                 std.generate_printout(cr, vd);
576             } else { // Missing type descriptor or reserved type, just print int
577                 cr.outputline("printf(\"<%d> \", __setval);");                  
578             }
579
580
581             cr.endblock();
582             cr.endblock();
583         }
584
585         cr.outputline("printf(\"\\n\\n------------------- END PRINTING\\n\");");
586     }
587
588     Set ruleset=null;
589     private void generate_rules() {
590         /* first we must sort the rules */
591         RelationDescriptor.prefix = newmodel.getSafeSymbol()+"->";
592         SetDescriptor.prefix = newmodel.getSafeSymbol()+"->";
593         System.out.println("SCC="+(mrd.numSCC()-1));
594         for(int sccindex=0;sccindex<mrd.numSCC();sccindex++) {
595             ruleset=mrd.getSCC(sccindex);
596             boolean needworklist=mrd.hasCycle(sccindex);
597             
598             if (!needworklist) {
599                 Iterator iterator_rs = ruleset.iterator();
600                 while (iterator_rs.hasNext()) {
601                     Rule rule = (Rule) iterator_rs.next();
602                     if (rule.getnogenerate())
603                         continue;
604                     {
605                         final SymbolTable st = rule.getSymbolTable();
606                         CodeWriter cr = new StandardCodeWriter(outputaux) {
607                                 public SymbolTable getSymbolTable() { return st; }
608                             };
609                         InvariantValue ivalue=new InvariantValue();
610                         cr.setInvariantValue(ivalue);
611
612                         cr.outputline("// build " +escape(rule.toString()));
613                         cr.startblock();
614                         cr.outputline("int maybe=0;");
615
616                         Expr ruleexpr=rule.getGuardExpr();
617                         HashSet invariantvars=new HashSet();
618                         Set invariants=ruleexpr.findInvariants(invariantvars);
619
620                         if ((ruleexpr instanceof BooleanLiteralExpr)&&
621                             ((BooleanLiteralExpr)ruleexpr).getValue()) {
622                             if (rule.getInclusion() instanceof SetInclusion) {
623                                 invariants.addAll(((SetInclusion)rule.getInclusion()).getExpr().findInvariants(invariantvars));
624                             } else if (rule.getInclusion() instanceof RelationInclusion) {
625                                 invariants.addAll(((RelationInclusion)rule.getInclusion()).getLeftExpr().findInvariants(invariantvars));
626                                 invariants.addAll(((RelationInclusion)rule.getInclusion()).getRightExpr().findInvariants(invariantvars));
627                             }
628                         }
629                         ListIterator quantifiers = rule.quantifiers();                  
630                         while (quantifiers.hasNext()) {
631                             Quantifier quantifier = (Quantifier) quantifiers.next();
632                             if (quantifier instanceof ForQuantifier) {
633                                 ForQuantifier fq=(ForQuantifier)quantifier;
634                                 invariants.addAll(fq.lower.findInvariants(invariantvars));
635                                 invariants.addAll(fq.upper.findInvariants(invariantvars));
636                             }
637                         }
638
639                         for(Iterator invit=invariants.iterator();invit.hasNext();) {
640                             Expr invexpr=(Expr)invit.next();
641                             VarDescriptor tmpvd=VarDescriptor.makeNew("tmpvar");
642                             VarDescriptor maybevd=VarDescriptor.makeNew("maybevar");
643                             invexpr.generate(cr,tmpvd);
644                             cr.outputline("int "+maybevd.getSafeSymbol()+"=maybe;");
645                             cr.outputline("maybe=0;");
646                             ivalue.assignPair(invexpr,tmpvd,maybevd);
647                         }
648
649                         quantifiers = rule.quantifiers();
650                         while (quantifiers.hasNext()) {
651                             Quantifier quantifier = (Quantifier) quantifiers.next();
652                             quantifier.generate_open(cr);
653                         }
654                         
655                         /* pretty print! */
656                         cr.output("//");
657                         rule.getGuardExpr().prettyPrint(cr);
658                         cr.outputline("");
659                         
660                         /* now we have to generate the guard test */
661                         VarDescriptor guardval = VarDescriptor.makeNew();
662                         rule.getGuardExpr().generate(cr, guardval);
663                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
664                         cr.startblock();
665                         
666                         /* now we have to generate the inclusion code */
667                         currentrule=rule;
668                         rule.getInclusion().generate(cr);
669                         cr.endblock();
670                         while (quantifiers.hasPrevious()) {
671                             Quantifier quantifier = (Quantifier) quantifiers.previous();
672                             cr.endblock();
673                         }
674                         cr.endblock();
675                         cr.outputline("");
676                         cr.outputline("");
677                     }
678                 }
679             } else {
680                 CodeWriter cr2 = new StandardCodeWriter(outputaux);
681                 
682                 for(Iterator initialworklist=ruleset.iterator();initialworklist.hasNext();) {
683                     /** Construct initial worklist set */
684                     Rule rule=(Rule)initialworklist.next();
685                     cr2.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
686                 }
687
688                 cr2.outputline("while ("+worklist.getSafeSymbol()+"->hasMoreElements())");
689                 cr2.startblock();
690                 VarDescriptor idvar=VarDescriptor.makeNew("id");
691                 cr2.outputline("int "+idvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getid();");
692                 
693                 String elseladder = "if";
694                 
695                 Iterator iterator_rules = ruleset.iterator();
696                 while (iterator_rules.hasNext()) {
697                     
698                     Rule rule = (Rule) iterator_rules.next();
699                     int dispatchid = rule.getNum();
700                     
701                     {
702                         final SymbolTable st = rule.getSymbolTable();
703                         CodeWriter cr = new StandardCodeWriter(outputaux) {
704                                 public SymbolTable getSymbolTable() { return st; }
705                             };
706                         
707                         cr.indent();
708                         cr.outputline(elseladder + " ("+idvar.getSafeSymbol()+" == " + dispatchid + ")");
709                         cr.startblock();
710                         cr.outputline("int maybe=0;");
711                         VarDescriptor typevar=VarDescriptor.makeNew("type");
712                         VarDescriptor leftvar=VarDescriptor.makeNew("left");
713                         VarDescriptor rightvar=VarDescriptor.makeNew("right");
714                         cr.outputline("int "+typevar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->gettype();");
715                         cr.outputline("int "+leftvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getlvalue();");
716                         cr.outputline("int "+rightvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getrvalue();");
717                         cr.outputline("// build " +escape(rule.toString()));
718                         
719                         
720                         for (int j=0;j<rule.numQuantifiers();j++) {
721                             Quantifier quantifier = rule.getQuantifier(j);
722                             quantifier.generate_open(cr, typevar.getSafeSymbol(),j,leftvar.getSafeSymbol(),rightvar.getSafeSymbol());
723                         }
724                         
725                         /* pretty print! */
726                         cr.output("//");
727                         
728                         rule.getGuardExpr().prettyPrint(cr);
729                         cr.outputline("");
730                         
731                         /* now we have to generate the guard test */
732                         
733                         VarDescriptor guardval = VarDescriptor.makeNew();
734                         rule.getGuardExpr().generate(cr, guardval);
735                         
736                         cr.outputline("if (" + guardval.getSafeSymbol() + ")");
737                         cr.startblock();
738                         
739                         /* now we have to generate the inclusion code */
740                         currentrule=rule;
741                         rule.getInclusion().generate(cr);
742                         cr.endblock();
743                         
744                         for (int j=0;j<rule.numQuantifiers();j++) {
745                             cr.endblock();
746                         }
747                         
748                         // close startblocks generated by DotExpr memory checks
749                         //DotExpr.generate_memory_endblocks(cr);
750                         
751                         cr.endblock(); // end else-if WORKLIST ladder
752                         
753                         elseladder = "else if";
754                     }
755                 }
756                 cr2.outputline("else");
757                 cr2.startblock();
758                 cr2.outputline("printf(\"VERY BAD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\");");
759                 cr2.outputline("exit(1);");
760                 cr2.endblock();
761                 // end block created for worklist
762                 cr2.outputline(worklist.getSafeSymbol()+"->pop();");
763                 cr2.endblock();
764             }
765         }
766     }
767
768     public static String escape(String s) {
769         String newstring="";
770         for(int i=0;i<s.length();i++) {
771             char c=s.charAt(i);
772             if (c=='"')
773                 newstring+="\"";
774             else
775                 newstring+=c;
776         }
777         return newstring;
778     }
779
780     private void generate_checks() {
781         /* do constraint checks */
782         Iterator i;
783         if (Compiler.REPAIR)
784             i=termination.constraintdependence.computeOrdering().iterator();
785         else
786             i=state.vConstraints.iterator();
787         for (; i.hasNext();) {
788             Constraint constraint;
789             if (Compiler.REPAIR)
790                 constraint= (Constraint) ((GraphNode)i.next()).getOwner();
791             else
792                 constraint=(Constraint)i.next();
793             
794             {
795                 final SymbolTable st = constraint.getSymbolTable();
796                 CodeWriter cr = new StandardCodeWriter(outputaux);
797                 cr.pushSymbolTable(constraint.getSymbolTable());
798
799                 cr.outputline("// checking " + escape(constraint.toString()));
800                 cr.startblock();
801
802                 ListIterator quantifiers = constraint.quantifiers();
803
804                 while (quantifiers.hasNext()) {
805                     Quantifier quantifier = (Quantifier) quantifiers.next();
806                     quantifier.generate_open(cr);
807                 }
808
809                 cr.outputline("int maybe = 0;");
810                         
811                 /* now we have to generate the guard test */
812         
813                 VarDescriptor constraintboolean = VarDescriptor.makeNew("constraintboolean");
814                 constraint.getLogicStatement().generate(cr, constraintboolean);
815                 
816                 cr.outputline("if (maybe)");
817                 cr.startblock();
818                 cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
819                 //cr.outputline("exit(1);");
820                 cr.endblock();
821
822                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
823                 cr.startblock();
824                 if (!Compiler.REPAIR||Compiler.GENERATEDEBUGHOOKS)
825                     cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
826                 
827                 if (Compiler.REPAIR) {
828                 /* Do repairs */
829                 /* Build new repair table */
830                 cr.outputline("if ("+repairtable.getSafeSymbol()+")");
831                 cr.outputline("delete "+repairtable.getSafeSymbol()+";");
832                 cr.outputline(repairtable.getSafeSymbol()+"=new RepairHash();");
833                 
834                 if (Compiler.GENERATEDEBUGHOOKS)
835                     cr.outputline("debughook();");
836                 /* Compute cost of each repair */
837                 VarDescriptor mincost=VarDescriptor.makeNew("mincost");
838                 VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
839                 Vector dnfconst=new Vector();
840                 dnfconst.addAll((Set)termination.conjunctionmap.get(constraint));
841
842                 if (dnfconst.size()<=1) {
843                     cr.outputline("int "+mincostindex.getSafeSymbol()+"=0;");
844                 }
845                 if (dnfconst.size()>1) {
846                     cr.outputline("int "+mincostindex.getSafeSymbol()+";");
847                     boolean first=true;
848                     for(int j=0;j<dnfconst.size();j++) {
849                         GraphNode gn=(GraphNode)dnfconst.get(j);
850                         Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
851                         if (removed.contains(gn))
852                             continue;
853                         
854                         VarDescriptor costvar;
855                         if (first) {
856                             costvar=mincost;
857                         } else
858                             costvar=VarDescriptor.makeNew("cost");
859                         for(int k=0;k<conj.size();k++) {
860                             DNFPredicate dpred=conj.get(k);
861                             Predicate p=dpred.getPredicate();
862                             boolean negate=dpred.isNegated();
863                             VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
864                             p.generate(cr,predvalue);
865                             if (k==0)
866                                 cr.outputline("int "+costvar.getSafeSymbol()+"=0;");
867                             
868                             if (negate)
869                                 cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
870                             else
871                                 cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
872                             cr.outputline(costvar.getSafeSymbol()+"+="+cost.getCost(dpred)+";");
873                         }
874                         
875                         if(!first) {
876                             cr.outputline("if ("+costvar.getSafeSymbol()+"<"+mincost.getSafeSymbol()+")");
877                             cr.startblock();
878                             cr.outputline(mincost.getSafeSymbol()+"="+costvar.getSafeSymbol()+";");
879                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
880                             cr.endblock();
881                         } else
882                             cr.outputline(mincostindex.getSafeSymbol()+"="+j+";");
883                         first=false;
884                     }
885                 }
886                 cr.outputline("switch("+mincostindex.getSafeSymbol()+") {");
887                 for(int j=0;j<dnfconst.size();j++) {
888                     GraphNode gn=(GraphNode)dnfconst.get(j);
889                     Conjunction conj=((TermNode)gn.getOwner()).getConjunction();
890                     if (removed.contains(gn))
891                         continue;
892                     cr.outputline("case "+j+":");
893                     cr.startblock();
894                     for(int k=0;k<conj.size();k++) {
895                         DNFPredicate dpred=conj.get(k);
896                         Predicate p=dpred.getPredicate();
897                         boolean negate=dpred.isNegated();
898                         VarDescriptor predvalue=VarDescriptor.makeNew("Predicatevalue");
899                         p.generate(cr,predvalue);
900                         if (negate)
901                             cr.outputline("if (maybe||"+predvalue.getSafeSymbol()+")");
902                         else
903                             cr.outputline("if (maybe||!"+predvalue.getSafeSymbol()+")");
904                         cr.startblock();
905                         if (Compiler.GENERATEINSTRUMENT)
906                             cr.outputline("abstractcount++;");
907                         if (p instanceof InclusionPredicate)
908                             generateinclusionrepair(conj,dpred, cr);
909                         else if (p instanceof ExprPredicate) {
910                             ExprPredicate ep=(ExprPredicate)p;
911                             if (ep.getType()==ExprPredicate.SIZE)
912                                 generatesizerepair(conj,dpred,cr);
913                             else if (ep.getType()==ExprPredicate.COMPARISON)
914                                 generatecomparisonrepair(conj,dpred,cr);
915                         } else throw new Error("Unrecognized Predicate");
916                         cr.endblock();
917                     }
918                     /* Update model */
919                     cr.endblock();
920                     cr.outputline("break;");
921                 }
922                 cr.outputline("}");
923                 
924                 cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
925                 cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
926                 cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
927                 cr.outputline("goto rebuild;");  /* Rebuild model and all */
928                 }
929                 cr.endblock();
930                 
931                 while (quantifiers.hasPrevious()) {
932                     Quantifier quantifier = (Quantifier) quantifiers.previous();
933                     cr.endblock();
934                 }
935                 cr.endblock();
936                 cr.outputline("");
937                 cr.outputline("");
938             }
939         }
940         CodeWriter cr = new StandardCodeWriter(outputaux);
941         cr.startblock();
942         cr.outputline("if ("+repairtable.getSafeSymbol()+")");
943         cr.outputline("delete "+repairtable.getSafeSymbol()+";");
944         cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
945         cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
946         cr.outputline("delete "+newmodel.getSafeSymbol()+";");
947         cr.outputline("delete "+worklist.getSafeSymbol()+";");
948         cr.outputline("resettypemap();");
949         cr.outputline("break;");
950         cr.endblock();
951         cr.outputline("rebuild:");
952         cr.outputline(";");     
953     }
954     
955     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
956         Set nodes=getmultupdatenodeset(conj,dpred,repairtype);
957         Iterator it=nodes.iterator();
958         if (it.hasNext())
959             return (MultUpdateNode)it.next();
960         else
961             return null;
962     }
963
964     private Set getmultupdatenodeset(Conjunction conj, DNFPredicate dpred, int repairtype) {
965         HashSet hs=new HashSet();
966         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
967         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
968             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
969             TermNode tn2=(TermNode)gn2.getOwner();
970             if (tn2.getType()==TermNode.ABSTRACT) {
971                 AbstractRepair ar=tn2.getAbstract();
972                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
973                     ar.getPredicate()==dpred) {
974                     for(Iterator edgeit2=gn2.edges();edgeit2.hasNext();) {
975                         GraphNode gn3=((GraphNode.Edge) edgeit2.next()).getTarget();
976                         if (!removed.contains(gn3)) {
977                             TermNode tn3=(TermNode)gn3.getOwner();
978                             if (tn3.getType()==TermNode.UPDATE) {
979                                 hs.add(tn3.getUpdate());
980                             }
981                         }
982                     }
983                 }
984             }
985         }
986         return hs;
987     }
988
989     private AbstractRepair getabstractrepair(Conjunction conj, DNFPredicate dpred, int repairtype) {
990         HashSet hs=new HashSet();
991         MultUpdateNode mun=null;
992         GraphNode gn=(GraphNode) termination.conjtonodemap.get(conj);
993         for(Iterator edgeit=gn.edges();(mun==null)&&edgeit.hasNext();) {
994             GraphNode gn2=((GraphNode.Edge) edgeit.next()).getTarget();
995             TermNode tn2=(TermNode)gn2.getOwner();
996             if (tn2.getType()==TermNode.ABSTRACT) {
997                 AbstractRepair ar=tn2.getAbstract();
998                 if (((repairtype==-1)||(ar.getType()==repairtype))&&
999                     ar.getPredicate()==dpred) {
1000                     return ar;
1001                 }
1002             }
1003         }
1004         return null;
1005     }
1006
1007
1008     /** Generates abstract (and concrete) repair for a comparison */
1009
1010     private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1011         Set updates=getmultupdatenodeset(conj,dpred,AbstractRepair.MODIFYRELATION);
1012         AbstractRepair ar=getabstractrepair(conj,dpred,AbstractRepair.MODIFYRELATION);
1013         MultUpdateNode munmodify=null;
1014         MultUpdateNode munadd=null;
1015         MultUpdateNode munremove=null;
1016         for(Iterator it=updates.iterator();it.hasNext();) {
1017             MultUpdateNode mun=(MultUpdateNode)it.next();
1018             if (mun.getType()==MultUpdateNode.ADD) {
1019                 munadd=mun;
1020             } else if (mun.getType()==MultUpdateNode.REMOVE) { 
1021                 munremove=mun;
1022             } else if (mun.getType()==MultUpdateNode.MODIFY) {
1023                 munmodify=mun;
1024             }
1025         }
1026         
1027         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
1028         RelationDescriptor rd=(RelationDescriptor)ep.getDescriptor();
1029         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1030         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1031         boolean inverted=ep.inverted();
1032         boolean negated=dpred.isNegated();
1033         OpExpr expr=(OpExpr)ep.expr;
1034         Opcode opcode=expr.getOpcode();
1035         VarDescriptor leftside=VarDescriptor.makeNew("leftside");
1036         VarDescriptor rightside=VarDescriptor.makeNew("rightside");
1037         VarDescriptor newvalue=VarDescriptor.makeNew("newvalue");
1038         boolean needremoveloop=ar.mayNeedFunctionEnforcement(state)&&ar.needsRemoves(state);
1039
1040         if (needremoveloop&&((munadd==null)||(munremove==null))) {
1041             System.out.println("Warning:  need to have individual remove operations for"+dpred.name());
1042             needremoveloop=false;
1043         }
1044         if (needremoveloop)
1045             cr.outputline("while (1) {");
1046
1047         if (!inverted) {
1048             ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,leftside);
1049             expr.getRightExpr().generate(cr,newvalue);
1050             cr.outputline(rd.getRange().getType().getGenerateType().getSafeSymbol()+" "+rightside.getSafeSymbol()+";");
1051             cr.outputline(rd.getSafeSymbol()+"_hash->get("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1052         } else {
1053             ((RelationExpr)expr.getLeftExpr()).getExpr().generate(cr,rightside);
1054             expr.getRightExpr().generate(cr,newvalue);
1055             cr.outputline(rd.getDomain().getType().getGenerateType().getSafeSymbol()+" "+leftside.getSafeSymbol()+";");
1056             cr.outputline(rd.getSafeSymbol()+"_hashinv->get("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1057         }
1058
1059         opcode=Opcode.translateOpcode(negated,opcode);
1060
1061         if (opcode==Opcode.GT) {
1062             cr.outputline(newvalue.getSafeSymbol()+"++;");
1063         } else if (opcode==Opcode.GE) {
1064             /* Equal */
1065         } else if (opcode==Opcode.LT) {
1066             cr.outputline(newvalue.getSafeSymbol()+"--;");
1067         } else if (opcode==Opcode.LE) {
1068             /* Equal */
1069         } else if (opcode==Opcode.EQ) {
1070             /* Equal */
1071         } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
1072             cr.outputline(newvalue.getSafeSymbol()+"++;");
1073         } else {
1074             throw new Error("Unrecognized Opcode");
1075         }
1076         /* Do abstract repairs */
1077         if (usageimage) {
1078             cr.outputline(rd.getSafeSymbol()+"_hash->remove("+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1079         }
1080         if (usageinvimage) {
1081             cr.outputline(rd.getSafeSymbol()+"_hashinv->remove("+rightside.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1082         }
1083
1084         if (needremoveloop) {
1085             if (!inverted) {
1086                 cr.outputline("if ("+rd.getSafeSymbol()+"_hash->contains("+leftside.getSafeSymbol()+")) {");
1087             } else {
1088                 cr.outputline("if ("+rd.getSafeSymbol()+"_hashinv->contains("+rightside.getSafeSymbol()+")) {");
1089             }
1090             for(int i=0;i<state.vRules.size();i++) {
1091                 Rule r=(Rule)state.vRules.get(i);
1092                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1093                     for(int j=0;j<munremove.numUpdates();j++) {
1094                         UpdateNode un=munremove.getUpdate(i);
1095                         if (un.getRule()==r) {
1096                                 /* Update for rule r */
1097                             String name=(String)updatenames.get(un);
1098                             cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
1099                         }
1100                     }
1101                 }
1102             }
1103             cr.outputline("continue;");
1104             cr.outputline("}");
1105         }
1106
1107         if (usageimage) {
1108             if (!inverted) {
1109                 cr.outputline(rd.getSafeSymbol()+"_hash->add("+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1110             } else {
1111                 cr.outputline(rd.getSafeSymbol()+"_hash->add("+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1112             }
1113         }
1114         if (usageinvimage) {
1115             if (!inverted) {
1116                 cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newvalue.getSafeSymbol()+","+leftside.getSafeSymbol()+");");
1117             } else {
1118                 cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+rightside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1119             }
1120         }
1121         /* Do concrete repairs */
1122         if (munmodify!=null&&(!ar.mayNeedFunctionEnforcement(state))||(munadd==null)||(ar.needsRemoves(state)&&(munremove==null))) {
1123             for(int i=0;i<state.vRules.size();i++) {
1124                 Rule r=(Rule)state.vRules.get(i);
1125                 if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1126                     for(int j=0;j<munmodify.numUpdates();j++) {
1127                         UpdateNode un=munmodify.getUpdate(j);
1128                         if (un.getRule()==r) {
1129                             /* Update for rule r */
1130                             String name=(String)updatenames.get(un);
1131                             cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
1132                         }
1133                     }
1134                 }
1135             }
1136         } else {
1137             /* Start with scheduling removal */
1138             if (ar.needsRemoves(state))
1139                 for(int i=0;i<state.vRules.size();i++) {
1140                     Rule r=(Rule)state.vRules.get(i);
1141                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1142                         for(int j=0;j<munremove.numUpdates();j++) {
1143                             UpdateNode un=munremove.getUpdate(i);
1144                             if (un.getRule()==r) {
1145                                 /* Update for rule r */
1146                                 String name=(String)updatenames.get(un);
1147                                 cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
1148                             }
1149                         }
1150                     }
1151                 }
1152             /* Now do addition */
1153             UpdateNode un=munadd.getUpdate(0);
1154             String name=(String)updatenames.get(un);
1155             if (!inverted) {
1156                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
1157             } else {
1158                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
1159             }
1160         }
1161         if (needremoveloop) {
1162             cr.outputline("break;");
1163             cr.outputline("}");
1164         }
1165     }
1166
1167     public void generatesizerepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr) {
1168         ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
1169         OpExpr expr=(OpExpr)ep.expr;
1170         Opcode opcode=expr.getOpcode();
1171         opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
1172
1173         MultUpdateNode munremove;
1174
1175         MultUpdateNode munadd;
1176         if (ep.getDescriptor() instanceof RelationDescriptor) {
1177             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
1178             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
1179         } else {
1180             munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
1181             munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
1182         }
1183         int size=ep.rightSize();
1184         VarDescriptor sizevar=VarDescriptor.makeNew("size");
1185         ((OpExpr)expr).left.generate(cr, sizevar);
1186         VarDescriptor change=VarDescriptor.makeNew("change");
1187         cr.outputline("int "+change.getSafeSymbol()+";");
1188         boolean generateadd=false;
1189         boolean generateremove=false;
1190         if (opcode==Opcode.GT) {
1191             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
1192             generateadd=true;
1193             generateremove=false;
1194         } else if (opcode==Opcode.GE) {
1195             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1196             generateadd=true;
1197             generateremove=false;
1198         } else if (opcode==Opcode.LT) {
1199             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size-1)+"-"+sizevar.getSafeSymbol()+";");
1200             generateadd=false;
1201             generateremove=true;
1202         } else if (opcode==Opcode.LE) {
1203             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1204             generateadd=false;
1205             generateremove=true;
1206         } else if (opcode==Opcode.EQ) {
1207             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
1208             if (size==0)
1209                 generateadd=false;
1210             else 
1211                 generateadd=true;
1212             generateremove=true;
1213         } else if (opcode==Opcode.NE) {
1214             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
1215             generateadd=true;
1216             generateremove=false;
1217         } else {
1218             throw new Error("Unrecognized Opcode");
1219         }
1220
1221 // In some cases the analysis has determined that generating removes
1222 // is unnecessary
1223         if (generateremove&&munremove==null) 
1224             generateremove=false;
1225
1226         Descriptor d=ep.getDescriptor();
1227         if (generateremove) {
1228             cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
1229             cr.startblock();
1230             /* Find element to remove */
1231             VarDescriptor leftvar=VarDescriptor.makeNew("leftvar");
1232             VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
1233             if (d instanceof RelationDescriptor) {
1234                 if (ep.inverted()) {
1235                     ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,rightvar);
1236                     cr.outputline("int "+leftvar.getSafeSymbol()+";");
1237                     cr.outputline(d.getSafeSymbol()+"_hashinv->get((int)"+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1238                 } else {
1239                     ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,leftvar);
1240                     cr.outputline("int "+rightvar.getSafeSymbol()+"=0;");
1241                     cr.outputline(d.getSafeSymbol()+"_hash->get((int)"+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1242                 }
1243             } else {
1244                 cr.outputline("int "+leftvar.getSafeSymbol()+"="+d.getSafeSymbol()+"_hash->firstkey();");
1245             }
1246             /* Generate abstract remove instruction */
1247             if (d instanceof RelationDescriptor) {
1248                 RelationDescriptor rd=(RelationDescriptor) d;
1249                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1250                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1251                 if (usageimage)
1252                     cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1253                 if (usageinvimage)
1254                     cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1255             } else {
1256                 cr.outputline(d.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1257             }
1258             /* Generate concrete remove instruction */
1259             for(int i=0;i<state.vRules.size();i++) {
1260                 Rule r=(Rule)state.vRules.get(i);
1261                 if (r.getInclusion().getTargetDescriptors().contains(d)) {
1262                     for(int j=0;j<munremove.numUpdates();j++) {
1263                         UpdateNode un=munremove.getUpdate(j);
1264                         if (un.getRule()==r) {
1265                                 /* Update for rule rule r */
1266                             String name=(String)updatenames.get(un);
1267                             if (d instanceof RelationDescriptor) {
1268                                 cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1269                             } else {
1270                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1271                             }
1272                         }
1273                     }
1274                 }
1275             }
1276             cr.endblock();
1277         }
1278
1279 // In some cases the analysis has determined that generating removes
1280 // is unnecessary
1281         if (generateadd&&munadd==null) 
1282             generateadd=false;
1283
1284         if (generateadd) {
1285
1286             cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
1287             cr.startblock();
1288             VarDescriptor newobject=VarDescriptor.makeNew("newobject");
1289             if (d instanceof RelationDescriptor) {
1290                 VarDescriptor otherside=VarDescriptor.makeNew("otherside");
1291                 ((ImageSetExpr)((SizeofExpr)expr.left).setexpr).generate_leftside(cr,otherside);
1292                 
1293                 RelationDescriptor rd=(RelationDescriptor)d;
1294                 if (termination.sources.relsetSource(rd,!ep.inverted())) {
1295                     /* Set Source */
1296                     SetDescriptor sd=termination.sources.relgetSourceSet(rd,!ep.inverted());
1297                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1298                     cr.outputline(sd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1299                     cr.outputline("SimpleIterator "+iterator.getSafeSymbol()+";");
1300                     cr.outputline("for("+sd.getSafeSymbol()+"_hash->iterator("+ iterator.getSafeSymbol() +");"+iterator.getSafeSymbol()+".hasNext();)");
1301                     cr.startblock();
1302                     if (ep.inverted()) {
1303                         cr.outputline("if (!"+rd.getSafeSymbol()+"_hashinv->contains("+iterator.getSafeSymbol()+".key(),"+otherside.getSafeSymbol()+"))");
1304                     } else {
1305                         cr.outputline("if (!"+rd.getSafeSymbol()+"_hash->contains("+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+".key()))");
1306                     }
1307                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1308                     cr.outputline(iterator.getSafeSymbol()+".next();");
1309                     cr.endblock();
1310                 } else if (termination.sources.relallocSource(rd,!ep.inverted())) {
1311                     /* Allocation Source*/
1312                     termination.sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
1313                 } else throw new Error("No source for adding to Relation");
1314                 if (ep.inverted()) {
1315                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1316                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1317                     if (usageimage)
1318                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1319                     if (usageinvimage)
1320                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1321
1322                     UpdateNode un=munadd.getUpdate(0);
1323                     String name=(String)updatenames.get(un);
1324                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1325                 } else {
1326                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1327                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1328                     if (usageimage)
1329                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1330                     if (usageinvimage)
1331                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1332                     UpdateNode un=munadd.getUpdate(0);
1333                     String name=(String)updatenames.get(un);
1334                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1335                 }
1336             } else {
1337                 SetDescriptor sd=(SetDescriptor)d;
1338                 if (termination.sources.setSource(sd)) {
1339                     /* Set Source */
1340                     /* Set Source */
1341                     SetDescriptor sourcesd=termination.sources.getSourceSet(sd);
1342                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1343                     cr.outputline(sourcesd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1344                     cr.outputline("SimpleIterator "+iterator.getSafeSymbol()+";");
1345                     cr.outputline("for("+sourcesd.getSafeSymbol()+"_hash->iterator("+iterator.getSafeSymbol()+");"+iterator.getSafeSymbol()+".hasNext();)");
1346                     cr.startblock();
1347                     cr.outputline("if (!"+sd.getSafeSymbol()+"_hash->contains("+iterator.getSafeSymbol()+".key()))");
1348                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1349                     cr.outputline(iterator.getSafeSymbol()+".next();");
1350                     cr.endblock();
1351                 } else if (termination.sources.allocSource(sd)) {
1352                     /* Allocation Source*/
1353                     termination.sources.generateSourceAlloc(cr,newobject,sd);
1354                 } else throw new Error("No source for adding to Set");
1355                 cr.outputline(sd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1356                 UpdateNode un=munadd.getUpdate(0);
1357                 String name=(String)updatenames.get(un);
1358                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1359             }
1360             cr.endblock();
1361         }
1362     }
1363
1364     public void generateinclusionrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1365         InclusionPredicate ip=(InclusionPredicate) dpred.getPredicate();
1366         boolean negated=dpred.isNegated();
1367         MultUpdateNode mun=getmultupdatenode(conj,dpred,-1);
1368         VarDescriptor leftvar=VarDescriptor.makeNew("left");
1369         ip.expr.generate(cr, leftvar);
1370
1371         if (negated) {
1372             if (ip.setexpr instanceof ImageSetExpr) {
1373                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1374                 VarDescriptor rightvar=ise.getVar();
1375                 boolean inverse=ise.inverted();
1376                 RelationDescriptor rd=ise.getRelation();
1377                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1378                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1379                 if (inverse) {
1380                     if (usageimage)
1381                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1382                     if (usageinvimage)
1383                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1384                 } else {
1385                     if (usageimage)
1386                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1387                     if (usageinvimage)
1388                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1389                 }
1390                 for(int i=0;i<state.vRules.size();i++) {
1391                     Rule r=(Rule)state.vRules.get(i);
1392                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1393                         for(int j=0;j<mun.numUpdates();j++) {
1394                             UpdateNode un=mun.getUpdate(j);
1395                             if (un.getRule()==r) {
1396                                 /* Update for rule rule r */
1397                                 String name=(String)updatenames.get(un);
1398                                 if (inverse) {
1399                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1400                                 } else {
1401                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1402                                 }
1403                             }
1404                         }
1405                     }
1406                 }
1407             } else {
1408                 SetDescriptor sd=ip.setexpr.sd;
1409                 cr.outputline(sd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1410
1411                 for(int i=0;i<state.vRules.size();i++) {
1412                     Rule r=(Rule)state.vRules.get(i);
1413                     if (r.getInclusion().getTargetDescriptors().contains(sd)) {
1414                         for(int j=0;j<mun.numUpdates();j++) {
1415                             UpdateNode un=mun.getUpdate(j);
1416                             if (un.getRule()==r) {
1417                                 /* Update for rule rule r */
1418                                 String name=(String)updatenames.get(un);
1419                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+sd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1420                             }
1421                         }
1422                     }
1423                 }
1424             }
1425         } else {
1426             /* Generate update */
1427             if (ip.setexpr instanceof ImageSetExpr) {
1428                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1429                 VarDescriptor rightvar=ise.getVar();
1430                 boolean inverse=ise.inverted();
1431                 RelationDescriptor rd=ise.getRelation();
1432                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1433                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1434                 if (inverse) {
1435                     if (usageimage)
1436                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1437                     if (usageinvimage)
1438                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1439                 } else {
1440                     if (usageimage)
1441                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
1442                     if (usageinvimage)
1443                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1444                 }
1445                 UpdateNode un=mun.getUpdate(0);
1446                 String name=(String)updatenames.get(un);
1447                 if (inverse) {
1448                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1449                 } else {
1450                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1451                 }
1452             } else {
1453                 SetDescriptor sd=ip.setexpr.sd;
1454                 cr.outputline(sd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
1455
1456                 UpdateNode un=mun.getUpdate(0);
1457                 /* Update for rule rule r */
1458                 String name=(String)updatenames.get(un);
1459                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1460             }
1461         }
1462     }
1463
1464     public static Vector getrulelist(Descriptor d) {
1465         Vector dispatchrules = new Vector();
1466         Vector rules = State.currentState.vRules;
1467
1468         for (int i = 0; i < rules.size(); i++) {
1469             Rule rule = (Rule) rules.elementAt(i);
1470             Set requiredsymbols = rule.getRequiredDescriptors();
1471             
1472             // #TBD#: in general this is wrong because these descriptors may contain descriptors
1473             // bound in "in?" expressions which need to be dealt with in a topologically sorted
1474             // fashion...
1475
1476             if (rule.getRequiredDescriptors().contains(d)) {
1477                 dispatchrules.addElement(rule);
1478             }
1479         }
1480         return dispatchrules;
1481     }
1482
1483     private boolean need_compensation(Rule r) {
1484         if (!Compiler.REPAIR)
1485             return false;
1486         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1487         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1488             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1489             GraphNode gn2=edge.getTarget();
1490             if (!removed.contains(gn2)) {
1491                 TermNode tn2=(TermNode)gn2.getOwner();
1492                 if (tn2.getType()==TermNode.CONSEQUENCE)
1493                     return false;
1494             }
1495         }
1496         return true;
1497     }
1498
1499     private UpdateNode find_compensation(Rule r) {
1500         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1501         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1502             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1503             GraphNode gn2=edge.getTarget();
1504             if (!removed.contains(gn2)) {
1505                 TermNode tn2=(TermNode)gn2.getOwner();
1506                 if (tn2.getType()==TermNode.UPDATE) {
1507                     MultUpdateNode mun=tn2.getUpdate();
1508                     for(int i=0;i<mun.numUpdates();i++) {
1509                         UpdateNode un=mun.getUpdate(i);
1510                         if (un.getRule()==r)
1511                             return un;
1512                     }
1513                 }
1514             }
1515         }
1516         throw new Error("No Compensation Update could be found");
1517     }
1518
1519     public void generate_dispatch(CodeWriter cr, RelationDescriptor rd, String leftvar, String rightvar) {
1520         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1521         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1522
1523         if (!(usageinvimage||usageimage)) /* not used at all*/
1524             return;
1525
1526         cr.outputline("// RELATION DISPATCH ");
1527         if (Compiler.REPAIR) {
1528             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1529             if (usageimage)
1530                 cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
1531             else
1532                 cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
1533
1534             cr.startblock(); {
1535                 /* Adding new item */
1536                 /* Perform safety checks */
1537                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1538                 cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
1539                 cr.startblock(); {
1540                     /* Have update to call into */
1541                     VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
1542                     VarDescriptor ismdfyptr=VarDescriptor.makeNew("ismodifyptr");
1543                     cr.outputline("int "+ismdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->ismodify("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1544
1545
1546
1547                     
1548                     String parttype="";
1549                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1550                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1551                             parttype=parttype+", int, int";
1552                         else
1553                             parttype=parttype+", int";
1554                     }
1555                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1556                     VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
1557                     
1558                     String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1559                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1560                         Quantifier q=currentrule.getQuantifier(i);
1561                         if (q instanceof SetQuantifier) {
1562                             SetQuantifier sq=(SetQuantifier) q;
1563                             methodcall+=","+sq.getVar().getSafeSymbol();
1564                         } else if (q instanceof RelationQuantifier) {
1565                             RelationQuantifier rq=(RelationQuantifier) q;
1566                             methodcall+=","+rq.x.getSafeSymbol();
1567                             methodcall+=","+rq.y.getSafeSymbol();
1568                         } else if (q instanceof ForQuantifier) {
1569                             ForQuantifier fq=(ForQuantifier) q;
1570                             methodcall+=","+fq.getVar().getSafeSymbol();
1571                         }
1572                     }
1573                     
1574                     
1575                     
1576                     cr.outputline("void *"+tmpptr.getSafeSymbol()+"=");
1577                     cr.outputline("(void *) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1578                     cr.outputline("if ("+ismdfyptr.getSafeSymbol()+")");
1579                     {
1580                         cr.startblock();
1581                         cr.outputline("int "+mdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->getrelation2("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1582                         cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol()+";");
1583                         cr.outputline(methodcall+","+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
1584                         cr.endblock();
1585                     }
1586                     cr.outputline("else ");
1587                     {
1588                         cr.startblock();
1589                         cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol()+";");
1590                         cr.outputline(methodcall+");");
1591                         cr.endblock();
1592                     }
1593                     cr.outputline("delete "+newmodel.getSafeSymbol()+";");
1594                     cr.outputline("goto rebuild;");
1595                 }
1596                 cr.endblock();
1597                 
1598                 /* Build standard compensation actions */
1599                 if (need_compensation(currentrule)) {
1600                     UpdateNode un=find_compensation(currentrule);
1601                     String name=(String)updatenames.get(un);
1602                     usedupdates.add(un); /* Mark as used */
1603                     String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1604                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1605                         Quantifier q=currentrule.getQuantifier(i);
1606                         if (q instanceof SetQuantifier) {
1607                             SetQuantifier sq=(SetQuantifier) q;
1608                             methodcall+=","+sq.getVar().getSafeSymbol();
1609                         } else if (q instanceof RelationQuantifier) {
1610                             RelationQuantifier rq=(RelationQuantifier) q;
1611                             methodcall+=","+rq.x.getSafeSymbol();
1612                             methodcall+=","+rq.y.getSafeSymbol();
1613                         } else if (q instanceof ForQuantifier) {
1614                             ForQuantifier fq=(ForQuantifier) q;
1615                             methodcall+=","+fq.getVar().getSafeSymbol();
1616                         }
1617                     }
1618                     methodcall+=");";
1619                     cr.outputline(methodcall);
1620                     cr.outputline("delete "+newmodel.getSafeSymbol()+";");
1621                     cr.outputline("goto rebuild;");
1622                 }
1623             }
1624             cr.endblock();
1625         }
1626
1627         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1628         cr.outputline("int " + addeditem + "=0;");
1629
1630         String ifstring="if (!maybe&&";
1631         boolean dogenerate=false;
1632         if (rd.getDomain().getType() instanceof StructureTypeDescriptor)  {
1633             dogenerate=true;
1634             ifstring+=leftvar;
1635         }
1636
1637         if (rd.getRange().getType() instanceof StructureTypeDescriptor)  {
1638             if (dogenerate)
1639                 ifstring+="&&"+rightvar;
1640             else
1641                 ifstring+=rightvar;
1642             dogenerate=true;
1643         }
1644
1645         ifstring+=")";
1646
1647         if (rd.testUsage(RelationDescriptor.IMAGE)) {
1648             cr.outputline(ifstring);
1649             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar+ ");");
1650         }
1651         
1652         if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
1653             cr.outputline(ifstring);
1654             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
1655         }
1656         
1657
1658         Vector dispatchrules = getrulelist(rd);
1659         
1660         Set toremove=new HashSet();
1661         for(int i=0;i<dispatchrules.size();i++) {
1662             Rule r=(Rule)dispatchrules.get(i);
1663             if (!ruleset.contains(r))
1664                 toremove.add(r);
1665         }
1666         dispatchrules.removeAll(toremove);
1667         if (dispatchrules.size() == 0) {
1668             cr.outputline("// nothing to dispatch");
1669             return;
1670         }
1671
1672         cr.outputline("if (" + addeditem + ")");
1673         cr.startblock();
1674        
1675         for(int i = 0; i < dispatchrules.size(); i++) {
1676             Rule rule = (Rule) dispatchrules.elementAt(i);
1677             if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
1678                 /* Guard depends on this relation, so we recomput everything */
1679                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1680             } else {
1681                 for (int j=0;j<rule.numQuantifiers();j++) {
1682                     Quantifier q=rule.getQuantifier(j);
1683                     if (q.getRequiredDescriptors().contains(rd)) {
1684                         /* Generate add */
1685                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+leftvar+","+rightvar+");");
1686                     }
1687                 }
1688             }
1689         }
1690
1691         cr.endblock();
1692     }
1693
1694
1695     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
1696         cr.outputline("// SET DISPATCH ");
1697         if (Compiler.REPAIR) {
1698             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1699             cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
1700             cr.startblock(); {
1701                 /* Adding new item */
1702                 /* See if there is an outstanding update in the repairtable */
1703                 cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1704                 cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
1705                 cr.startblock(); {
1706                     /* Have update to call into */
1707                     VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1708                     String parttype="";
1709                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1710                         if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1711                             parttype=parttype+", int, int";
1712                         else
1713                             parttype=parttype+", int";
1714                     }
1715                     cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
1716                     cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
1717                     String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
1718                         repairtable.getSafeSymbol();
1719                     for(int i=0;i<currentrule.numQuantifiers();i++) {
1720                         Quantifier q=currentrule.getQuantifier(i);
1721                         if (q instanceof SetQuantifier) {
1722                             SetQuantifier sq=(SetQuantifier) q;
1723                             methodcall+=","+sq.getVar().getSafeSymbol();
1724                         } else if (q instanceof RelationQuantifier) {
1725                             RelationQuantifier rq=(RelationQuantifier) q;
1726                             methodcall+=","+rq.x.getSafeSymbol();
1727                             methodcall+=","+rq.y.getSafeSymbol();
1728                         } else if (q instanceof ForQuantifier) {
1729                             ForQuantifier fq=(ForQuantifier) q;
1730                             methodcall+=","+fq.getVar().getSafeSymbol();
1731                         }
1732                     }
1733                     methodcall+=");";
1734                     cr.outputline(methodcall);
1735                     cr.outputline("delete "+newmodel.getSafeSymbol()+";");
1736                     cr.outputline("goto rebuild;");
1737                 }
1738                 cr.endblock();
1739                 /* Build standard compensation actions */
1740                 Vector ruleset=new Vector();
1741                 ruleset.add(currentrule);
1742                 if (state.implicitruleinv.containsKey(currentrule))
1743                     ruleset.addAll((Set)state.implicitruleinv.get(currentrule));
1744                 for(int i=0;i<ruleset.size();i++) {
1745                     Rule itrule=(Rule)ruleset.get(i);
1746                     
1747                     if (need_compensation(itrule)) {
1748                         UpdateNode un=find_compensation(itrule);
1749                         String name=(String)updatenames.get(un);
1750                         usedupdates.add(un); /* Mark as used */
1751                         
1752                         String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
1753                             repairtable.getSafeSymbol();
1754                         for(int j=0;j<currentrule.numQuantifiers();j++) {
1755                             Quantifier q=currentrule.getQuantifier(j);
1756                             if (q instanceof SetQuantifier) {
1757                                 SetQuantifier sq=(SetQuantifier) q;
1758                                 methodcall+=","+sq.getVar().getSafeSymbol();
1759                             } else if (q instanceof RelationQuantifier) {
1760                                 RelationQuantifier rq=(RelationQuantifier) q;
1761                                 methodcall+=","+rq.x.getSafeSymbol();
1762                                 methodcall+=","+rq.y.getSafeSymbol();
1763                             } else if (q instanceof ForQuantifier) {
1764                                 ForQuantifier fq=(ForQuantifier) q;
1765                                 methodcall+=","+fq.getVar().getSafeSymbol();
1766                             }
1767                         }
1768                         methodcall+=");";
1769                         if (currentrule!=itrule) {
1770                             SetDescriptor sdrule=((SetInclusion)itrule.getInclusion()).getSet();
1771                             cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1772                             cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sdrule.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
1773                             cr.startblock();
1774                         }
1775                         cr.outputline(methodcall);
1776                         cr.outputline("delete "+newmodel.getSafeSymbol()+";");
1777                         cr.outputline("goto rebuild;");
1778                         cr.endblock();
1779                     }
1780                     if (currentrule==itrule)
1781                         cr.endblock();
1782                 }
1783             }
1784         }
1785
1786         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1787         cr.outputline("int " + addeditem + " = 0;");
1788         if (sd.getType() instanceof StructureTypeDescriptor)  {
1789             cr.outputline("if (!maybe&&"+setvar+")");
1790         } else
1791             cr.outputline("if (!maybe)");
1792         cr.outputline(addeditem + " = " + sd.getSafeSymbol() + "_hash->add((int)" + setvar +  ", (int)" + setvar + ");");
1793         cr.startblock();
1794         Vector dispatchrules = getrulelist(sd);
1795
1796         Set toremove=new HashSet();
1797         for(int i=0;i<dispatchrules.size();i++) {
1798             Rule r=(Rule)dispatchrules.get(i);
1799             if (!ruleset.contains(r))
1800                 toremove.add(r);
1801         }
1802         dispatchrules.removeAll(toremove);
1803
1804         if (dispatchrules.size() == 0) {
1805             cr.outputline("// nothing to dispatch");
1806             cr.endblock();
1807             return;
1808         }
1809         /* Add item to worklist if new */
1810         cr.outputline("if ("+addeditem+")");
1811         cr.startblock();
1812         for(int i = 0; i < dispatchrules.size(); i++) {
1813             Rule rule = (Rule) dispatchrules.elementAt(i);
1814             if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
1815                 /* Guard depends on this relation, so we recompute everything */
1816                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1817             } else {
1818                 for (int j=0;j<rule.numQuantifiers();j++) {
1819                     Quantifier q=rule.getQuantifier(j);
1820                     if (SetDescriptor.expand(q.getRequiredDescriptors()).contains(sd)) {
1821                         /* Generate add */
1822                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+setvar+",0);");
1823                     }
1824                 }
1825             }
1826         }
1827         cr.endblock();
1828         cr.endblock();
1829     }
1830 }