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