Added support for stack allocation. Check for NULL before calling memory checker.
[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             generateadd=true;
946             generateremove=true;
947         } else if (opcode==Opcode.NE) {
948             cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
949             generateadd=true;
950             generateremove=false;
951         } else {
952             throw new Error("Unrecognized Opcode");
953         }
954         Descriptor d=ep.getDescriptor();
955         if (generateremove) {
956             cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
957             cr.startblock();
958             /* Find element to remove */
959             VarDescriptor leftvar=VarDescriptor.makeNew("leftvar");
960             VarDescriptor rightvar=VarDescriptor.makeNew("rightvar");
961             if (d instanceof RelationDescriptor) {
962                 if (ep.inverted()) {
963                     rightvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
964                     cr.outputline("int "+leftvar.getSafeSymbol()+";");
965                     cr.outputline(d.getSafeSymbol()+"_hashinv->get((int)"+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
966                 } else {
967                     leftvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
968                     cr.outputline("int "+rightvar.getSafeSymbol()+";");
969                     cr.outputline(d.getSafeSymbol()+"_hash->get((int)"+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
970                 }
971             } else {
972                 cr.outputline("int "+leftvar.getSafeSymbol()+"="+d.getSafeSymbol()+"_hash->firstkey();");
973             }
974             /* Generate abstract remove instruction */
975             if (d instanceof RelationDescriptor) {
976                 RelationDescriptor rd=(RelationDescriptor) d;
977                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
978                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
979                 if (usageimage)
980                     cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + rightvar + ");");
981                 if (usageinvimage)
982                     cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar + ", (int)" + leftvar + ");");
983             } else {
984                 cr.outputline(d.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + leftvar + ");");
985             }
986             /* Generate concrete remove instruction */
987             for(int i=0;i<state.vRules.size();i++) {
988                 Rule r=(Rule)state.vRules.get(i);
989                 if (r.getInclusion().getTargetDescriptors().contains(d)) {
990                     for(int j=0;j<munremove.numUpdates();j++) {
991                         UpdateNode un=munremove.getUpdate(i);
992                         if (un.getRule()==r) {
993                                 /* Update for rule rule r */
994                             String name=(String)updatenames.get(un);
995                             if (d instanceof RelationDescriptor) {
996                                 cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
997                             } else {
998                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+d.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
999                             }
1000                         }
1001                     }
1002                 }
1003             }
1004             cr.endblock();
1005         }
1006         if (generateadd) {
1007
1008             cr.outputline("for(;"+change.getSafeSymbol()+">0;"+change.getSafeSymbol()+"--)");
1009             cr.startblock();
1010             VarDescriptor newobject=VarDescriptor.makeNew("newobject");
1011             if (d instanceof RelationDescriptor) {
1012                 VarDescriptor otherside=((ImageSetExpr)((SizeofExpr)ep.expr).setexpr).vd;
1013                 RelationDescriptor rd=(RelationDescriptor)d;
1014                 if (sources.relsetSource(rd,!ep.inverted())) {
1015                     /* Set Source */
1016                     SetDescriptor sd=sources.relgetSourceSet(rd,!ep.inverted());
1017                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1018                     cr.outputline(sd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1019                     cr.outputline("for("+iterator.getSafeSymbol()+"="+sd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
1020                     cr.startblock();
1021                     if (ep.inverted()) {
1022                         cr.outputline("if !"+rd.getSafeSymbol()+"_hashinv->contains("+iterator.getSafeSymbol()+"->key(),"+otherside.getSafeSymbol()+")");
1023                     } else {
1024                         cr.outputline("if !"+rd.getSafeSymbol()+"_hash->contains("+otherside.getSafeSymbol()+","+iterator.getSafeSymbol()+"->key())");
1025                     }
1026                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1027                     cr.outputline(iterator.getSafeSymbol()+"->next();");
1028                     cr.endblock();
1029                 } else if (sources.relallocSource(rd,!ep.inverted())) {
1030                     /* Allocation Source*/
1031                     sources.relgenerateSourceAlloc(cr,newobject,rd,!ep.inverted());
1032                 } else throw new Error("No source for adding to Relation");
1033                 if (ep.inverted()) {
1034                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1035                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1036                     if (usageimage)
1037                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1038                     if (usageinvimage)
1039                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1040
1041                     UpdateNode un=munadd.getUpdate(0);
1042                     String name=(String)updatenames.get(un);
1043                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1044                 } else {
1045                     boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1046                     boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1047                     if (usageimage)
1048                         cr.outputline(rd.getSafeSymbol()+"_hash->add("+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1049                     if (usageinvimage)
1050                         cr.outputline(rd.getSafeSymbol()+"_hashinv->add("+newobject.getSafeSymbol()+","+otherside.getSafeSymbol()+");");
1051                     UpdateNode un=munadd.getUpdate(0);
1052                     String name=(String)updatenames.get(un);
1053                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+otherside.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1054                 }
1055             } else {
1056                 SetDescriptor sd=(SetDescriptor)d;
1057                 if (sources.setSource(sd)) {
1058                     /* Set Source */
1059                     /* Set Source */
1060                     SetDescriptor sourcesd=sources.getSourceSet(sd);
1061                     VarDescriptor iterator=VarDescriptor.makeNew("iterator");
1062                     cr.outputline(sourcesd.getType().getGenerateType().getSafeSymbol() +" "+newobject.getSafeSymbol()+";");
1063                     cr.outputline("for("+iterator.getSafeSymbol()+"="+sourcesd.getSafeSymbol()+"_hash->iterator();"+iterator.getSafeSymbol()+".hasNext();)");
1064                     cr.startblock();
1065                     cr.outputline("if !"+sd.getSafeSymbol()+"_hash->contains("+iterator.getSafeSymbol()+"->key())");
1066                     cr.outputline(newobject.getSafeSymbol()+"="+iterator.getSafeSymbol()+".key();");
1067                     cr.outputline(iterator.getSafeSymbol()+"->next();");
1068                     cr.endblock();
1069                 } else if (sources.allocSource(sd)) {
1070                     /* Allocation Source*/
1071                     sources.generateSourceAlloc(cr,newobject,sd);
1072                 } else throw new Error("No source for adding to Set");
1073                 cr.outputline(sd.getSafeSymbol()+"_hash->add("+newobject.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1074                 UpdateNode un=munadd.getUpdate(0);
1075                 String name=(String)updatenames.get(un);
1076                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newobject.getSafeSymbol()+");");
1077             }
1078             cr.endblock();
1079         }
1080     }
1081
1082     public void generateinclusionrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
1083         InclusionPredicate ip=(InclusionPredicate) dpred.getPredicate();
1084         boolean negated=dpred.isNegated();
1085         MultUpdateNode mun=getmultupdatenode(conj,dpred,-1);
1086         VarDescriptor leftvar=VarDescriptor.makeNew("left");
1087         ip.expr.generate(cr, leftvar);
1088
1089         if (negated) {
1090             if (ip.setexpr instanceof ImageSetExpr) {
1091                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1092                 VarDescriptor rightvar=ise.getVar();
1093                 boolean inverse=ise.inverted();
1094                 RelationDescriptor rd=ise.getRelation();
1095                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1096                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1097                 if (inverse) {
1098                     if (usageimage)
1099                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + rightvar + ", (int)" + leftvar + ");");
1100                     if (usageinvimage)
1101                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + leftvar + ", (int)" + rightvar + ");");
1102                 } else {
1103                     if (usageimage)
1104                         cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + rightvar + ");");
1105                     if (usageinvimage)
1106                         cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar + ", (int)" + leftvar + ");");
1107                 }
1108                 for(int i=0;i<state.vRules.size();i++) {
1109                     Rule r=(Rule)state.vRules.get(i);
1110                     if (r.getInclusion().getTargetDescriptors().contains(rd)) {
1111                         for(int j=0;j<mun.numUpdates();j++) {
1112                             UpdateNode un=mun.getUpdate(i);
1113                             if (un.getRule()==r) {
1114                                 /* Update for rule rule r */
1115                                 String name=(String)updatenames.get(un);
1116                                 if (inverse) {
1117                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1118                                 } else {
1119                                     cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+",(int) &"+name+");");
1120                                 }
1121                             }
1122                         }
1123                     }
1124                 }
1125             } else {
1126                 SetDescriptor sd=ip.setexpr.sd;
1127                 cr.outputline(sd.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + leftvar + ");");
1128
1129                 for(int i=0;i<state.vRules.size();i++) {
1130                     Rule r=(Rule)state.vRules.get(i);
1131                     if (r.getInclusion().getTargetDescriptors().contains(sd)) {
1132                         for(int j=0;j<mun.numUpdates();j++) {
1133                             UpdateNode un=mun.getUpdate(i);
1134                             if (un.getRule()==r) {
1135                                 /* Update for rule rule r */
1136                                 String name=(String)updatenames.get(un);
1137                                 cr.outputline(repairtable.getSafeSymbol()+"->addset("+sd.getNum()+","+r.getNum()+","+leftvar.getSafeSymbol()+",(int) &"+name+");");
1138                             }
1139                         }
1140                     }
1141                 }
1142             }
1143         } else {
1144             /* Generate update */
1145             if (ip.setexpr instanceof ImageSetExpr) {
1146                 ImageSetExpr ise=(ImageSetExpr) ip.setexpr;
1147                 VarDescriptor rightvar=ise.getVar();
1148                 boolean inverse=ise.inverted();
1149                 RelationDescriptor rd=ise.getRelation();
1150                 boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1151                 boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1152                 if (inverse) {
1153                     if (usageimage)
1154                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + rightvar + ", (int)" + leftvar + ");");
1155                     if (usageinvimage)
1156                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + leftvar + ", (int)" + rightvar + ");");
1157                 } else {
1158                     if (usageimage)
1159                         cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar + ");");
1160                     if (usageinvimage)
1161                         cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
1162                 }
1163                 UpdateNode un=mun.getUpdate(0);
1164                 String name=(String)updatenames.get(un);
1165                 if (inverse) {
1166                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1167                 } else {
1168                     cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
1169                 }
1170             } else {
1171                 SetDescriptor sd=ip.setexpr.sd;
1172                 cr.outputline(sd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + leftvar + ");");
1173
1174                 UpdateNode un=mun.getUpdate(0);
1175                 /* Update for rule rule r */
1176                 String name=(String)updatenames.get(un);
1177                 cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
1178             }
1179         }
1180     }
1181
1182
1183
1184     public static Vector getrulelist(Descriptor d) {
1185         Vector dispatchrules = new Vector();
1186         Vector rules = State.currentState.vRules;
1187
1188         for (int i = 0; i < rules.size(); i++) {
1189             Rule rule = (Rule) rules.elementAt(i);
1190             Set requiredsymbols = rule.getRequiredDescriptors();
1191             
1192             // #TBD#: in general this is wrong because these descriptors may contain descriptors
1193             // bound in "in?" expressions which need to be dealt with in a topologically sorted
1194             // fashion...
1195
1196             if (rule.getRequiredDescriptors().contains(d)) {
1197                 dispatchrules.addElement(rule);
1198             }
1199         }
1200         return dispatchrules;
1201     }
1202
1203     private boolean need_compensation(Rule r) {
1204         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1205         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1206             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1207             GraphNode gn2=edge.getTarget();
1208             if (!removed.contains(gn2)) {
1209                 TermNode tn2=(TermNode)gn2.getOwner();
1210                 if (tn2.getType()==TermNode.CONSEQUENCE)
1211                     return false;
1212             }
1213         }
1214         return true;
1215     }
1216
1217     private UpdateNode find_compensation(Rule r) {
1218         GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
1219         for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
1220             GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
1221             GraphNode gn2=edge.getTarget();
1222             if (!removed.contains(gn2)) {
1223                 TermNode tn2=(TermNode)gn2.getOwner();
1224                 if (tn2.getType()==TermNode.UPDATE) {
1225                     MultUpdateNode mun=tn2.getUpdate();
1226                     for(int i=0;i<mun.numUpdates();i++) {
1227                         UpdateNode un=mun.getUpdate(i);
1228                         if (un.getRule()==r)
1229                             return un;
1230                     }
1231                 }
1232             }
1233         }
1234         throw new Error("No Compensation Update could be found");
1235     }
1236
1237     public void generate_dispatch(CodeWriter cr, RelationDescriptor rd, String leftvar, String rightvar) {
1238         boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
1239         boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
1240
1241         if (!(usageinvimage||usageimage)) /* not used at all*/
1242             return;
1243
1244         cr.outputline("// RELATION DISPATCH ");
1245         cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1246         if (usageimage)
1247             cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
1248         else
1249             cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
1250         cr.startblock(); {
1251             /* Adding new item */
1252             /* Perform safety checks */
1253             cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1254             cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
1255             cr.startblock(); {
1256                 /* Have update to call into */
1257                 VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1258                 String parttype="";
1259                 for(int i=0;i<currentrule.numQuantifiers();i++) {
1260                     if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1261                         parttype=parttype+", int, int";
1262                     else
1263                         parttype=parttype+", int";
1264                 }
1265                 cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
1266                 cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
1267                 String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1268                 for(int i=0;i<currentrule.numQuantifiers();i++) {
1269                     Quantifier q=currentrule.getQuantifier(i);
1270                     if (q instanceof SetQuantifier) {
1271                         SetQuantifier sq=(SetQuantifier) q;
1272                         methodcall+=","+sq.getVar().getSafeSymbol();
1273                     } else if (q instanceof RelationQuantifier) {
1274                         RelationQuantifier rq=(RelationQuantifier) q;
1275                         methodcall+=","+rq.x.getSafeSymbol();
1276                         methodcall+=","+rq.y.getSafeSymbol();
1277                     } else if (q instanceof ForQuantifier) {
1278                         ForQuantifier fq=(ForQuantifier) q;
1279                         methodcall+=","+fq.getVar().getSafeSymbol();
1280                     }
1281                 }
1282                 methodcall+=");";
1283                 cr.outputline(methodcall);
1284                 cr.outputline(goodflag.getSafeSymbol()+"=0;");
1285                 cr.outputline("continue;");
1286             }
1287             cr.endblock();
1288             /* Build standard compensation actions */
1289             if (need_compensation(currentrule)) {
1290                 UpdateNode un=find_compensation(currentrule);
1291                 String name=(String)updatenames.get(un);
1292                 usedupdates.add(un); /* Mark as used */
1293                 String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
1294                 for(int i=0;i<currentrule.numQuantifiers();i++) {
1295                     Quantifier q=currentrule.getQuantifier(i);
1296                     if (q instanceof SetQuantifier) {
1297                         SetQuantifier sq=(SetQuantifier) q;
1298                         methodcall+=","+sq.getVar().getSafeSymbol();
1299                     } else if (q instanceof RelationQuantifier) {
1300                         RelationQuantifier rq=(RelationQuantifier) q;
1301                         methodcall+=","+rq.x.getSafeSymbol();
1302                         methodcall+=","+rq.y.getSafeSymbol();
1303                     } else if (q instanceof ForQuantifier) {
1304                         ForQuantifier fq=(ForQuantifier) q;
1305                         methodcall+=","+fq.getVar().getSafeSymbol();
1306                     }
1307                 }
1308                 methodcall+=");";
1309                 cr.outputline(methodcall);
1310                 cr.outputline(goodflag.getSafeSymbol()+"=0;");
1311                 cr.outputline("continue;");
1312             }
1313         }
1314         cr.endblock();
1315
1316         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1317         cr.outputline("int " + addeditem + ";");
1318         if (rd.testUsage(RelationDescriptor.IMAGE)) {
1319             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar + ");");
1320         }
1321         
1322         if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
1323             cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
1324         }
1325         
1326         cr.outputline("if (" + addeditem + ")");
1327         cr.startblock();
1328
1329         Vector dispatchrules = getrulelist(rd);
1330         
1331         if (dispatchrules.size() == 0) {
1332             cr.outputline("// nothing to dispatch");
1333             cr.endblock();
1334             return;
1335         }
1336        
1337         for(int i = 0; i < dispatchrules.size(); i++) {
1338             Rule rule = (Rule) dispatchrules.elementAt(i);
1339             if (rule.getGuardExpr().getRequiredDescriptors().contains(rd)) {
1340                 /* Guard depends on this relation, so we recomput everything */
1341                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1342             } else {
1343                 for (int j=0;j<rule.numQuantifiers();j++) {
1344                     Quantifier q=rule.getQuantifier(j);
1345                     if (q.getRequiredDescriptors().contains(rd)) {
1346                         /* Generate add */
1347                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+leftvar+","+rightvar+");");
1348                     }
1349                 }
1350             }
1351         }
1352         cr.endblock();
1353     }
1354
1355
1356     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
1357                
1358         cr.outputline("// SET DISPATCH ");
1359
1360         cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
1361         cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
1362         cr.startblock(); {
1363             /* Adding new item */
1364             /* Perform safety checks */
1365             cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
1366             cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
1367             cr.startblock(); {
1368                 /* Have update to call into */
1369                 VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
1370                 String parttype="";
1371                 for(int i=0;i<currentrule.numQuantifiers();i++) {
1372                     if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
1373                         parttype=parttype+", int, int";
1374                     else
1375                         parttype=parttype+", int";
1376                 }
1377                 cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
1378                 cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
1379                 String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
1380                               repairtable.getSafeSymbol();
1381                 for(int i=0;i<currentrule.numQuantifiers();i++) {
1382                     Quantifier q=currentrule.getQuantifier(i);
1383                     if (q instanceof SetQuantifier) {
1384                         SetQuantifier sq=(SetQuantifier) q;
1385                         methodcall+=","+sq.getVar().getSafeSymbol();
1386                     } else if (q instanceof RelationQuantifier) {
1387                         RelationQuantifier rq=(RelationQuantifier) q;
1388                         methodcall+=","+rq.x.getSafeSymbol();
1389                         methodcall+=","+rq.y.getSafeSymbol();
1390                     } else if (q instanceof ForQuantifier) {
1391                         ForQuantifier fq=(ForQuantifier) q;
1392                         methodcall+=","+fq.getVar().getSafeSymbol();
1393                     }
1394                 }
1395                 methodcall+=");";
1396                 cr.outputline(methodcall);
1397                 cr.outputline(goodflag.getSafeSymbol()+"=0;");
1398                 cr.outputline("continue;");
1399             }
1400             cr.endblock();
1401             /* Build standard compensation actions */
1402             if (need_compensation(currentrule)) {
1403                 UpdateNode un=find_compensation(currentrule);
1404                 String name=(String)updatenames.get(un);
1405                 usedupdates.add(un); /* Mark as used */
1406
1407                 String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
1408                               repairtable.getSafeSymbol();
1409                 for(int i=0;i<currentrule.numQuantifiers();i++) {
1410                     Quantifier q=currentrule.getQuantifier(i);
1411                     if (q instanceof SetQuantifier) {
1412                         SetQuantifier sq=(SetQuantifier) q;
1413                         methodcall+=","+sq.getVar().getSafeSymbol();
1414                     } else if (q instanceof RelationQuantifier) {
1415                         RelationQuantifier rq=(RelationQuantifier) q;
1416                         methodcall+=","+rq.x.getSafeSymbol();
1417                         methodcall+=","+rq.y.getSafeSymbol();
1418                     } else if (q instanceof ForQuantifier) {
1419                         ForQuantifier fq=(ForQuantifier) q;
1420                         methodcall+=","+fq.getVar().getSafeSymbol();
1421                     }
1422                 }
1423                 methodcall+=");";
1424                 cr.outputline(methodcall);
1425                 cr.outputline(goodflag.getSafeSymbol()+"=0;");
1426                 cr.outputline("continue;");
1427             }
1428         }
1429         cr.endblock();
1430
1431         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
1432         cr.outputline("int " + addeditem + " = 1;");
1433         cr.outputline(addeditem + " = " + sd.getSafeSymbol() + "_hash->add((int)" + setvar +  ", (int)" + setvar + ");");
1434         cr.startblock();
1435         Vector dispatchrules = getrulelist(sd);
1436
1437         if (dispatchrules.size() == 0) {
1438             cr.outputline("// nothing to dispatch");
1439             cr.endblock();
1440             return;
1441         }
1442
1443         for(int i = 0; i < dispatchrules.size(); i++) {
1444             Rule rule = (Rule) dispatchrules.elementAt(i);
1445             if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
1446                 /* Guard depends on this relation, so we recompute everything */
1447                 cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
1448             } else {
1449                 for (int j=0;j<rule.numQuantifiers();j++) {
1450                     Quantifier q=rule.getQuantifier(j);
1451                     if (SetDescriptor.expand(q.getRequiredDescriptors()).contains(sd)) {
1452                         /* Generate add */
1453                         cr.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+","+j+","+setvar+",0);");
1454                     }
1455                 }
1456             }
1457         }
1458         cr.endblock();
1459     }
1460 }