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