Adding functionality for printing sets.
[repair.git] / Repair / RepairCompiler / MCC / IR / RepairGenerator.java
index bcf68f565730a2ee8e62c1bddbeaf869ba1b111e..71ff6edc3b7c0651e4eae60f558eab817a605cdf 100755 (executable)
@@ -3,6 +3,7 @@ package MCC.IR;
 import java.io.*;
 import java.util.*;
 import MCC.State;
+import MCC.Compiler;
 
 public class RepairGenerator {
     State state;
@@ -25,6 +26,7 @@ public class RepairGenerator {
     static boolean DEBUG=false;
     Cost cost;
     Sources sources;
+    ModelRuleDependence mrd;
 
     public RepairGenerator(State state, Termination t) {
         this.state = state;
@@ -34,14 +36,30 @@ public class RepairGenerator {
        removed=t.removedset;
        togenerate=new HashSet();
         togenerate.addAll(termination.conjunctions);
-        togenerate.removeAll(removed);
+       if (Compiler.REPAIR)
+           togenerate.removeAll(removed);
         GraphNode.computeclosure(togenerate,removed);
-
        cost=new Cost();
        sources=new Sources(state);
+       mrd=ModelRuleDependence.doAnalysis(state);
        Repair.repairgenerator=this;
     }
 
+    private void generatetypechecks(boolean flag) {
+       if (flag) {
+           DotExpr.DOTYPECHECKS=true;
+           VarExpr.DOTYPECHECKS=true;
+           DotExpr.DONULL=true;
+           VarExpr.DONULL=true;
+       } else {
+           VarExpr.DOTYPECHECKS=false;
+           DotExpr.DOTYPECHECKS=false;
+           VarExpr.DONULL=true;
+           DotExpr.DONULL=true;
+       }
+    }
+
+
     private void name_updates() {
        int count=0;
        for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
@@ -63,31 +81,50 @@ public class RepairGenerator {
         this.outputhead = new java.io.PrintWriter(outputhead, true);
         headername=st;
        name_updates();
-
+       generatetypechecks(true);
         generate_tokentable();
         generate_hashtables();
        generate_stateobject();
        generate_call();
-       generate_worklist();
+       generate_start();
         generate_rules();
+       generate_print();
         generate_checks();
         generate_teardown();
        CodeWriter crhead = new StandardCodeWriter(this.outputhead);
        CodeWriter craux = new StandardCodeWriter(this.outputaux);
        crhead.outputline("};");
-       craux.outputline("};");
+       craux.outputline("}");
+       generatetypechecks(false);
+       generate_computesizes();
+       generatetypechecks(true);
+       generate_recomputesizes();
+       generatetypechecks(false);
        generate_updates();
+       StructureGenerator sg=new StructureGenerator(state,this);
+       sg.buildall();
+       crhead.outputline("#endif");
     }
 
+    String ststate="state";
+    String stmodel="model";
+    String strepairtable="repairtable";
+    String stleft="left";
+    String stright="right";
+    String stnew="newvalue";
+
     private void generate_updates() {
        int count=0;
         CodeWriter crhead = new StandardCodeWriter(outputhead);        
         CodeWriter craux = new StandardCodeWriter(outputaux);        
-       String state="state";
-       String model="model";
-       String repairtable="repairtable";
-       String left="left";
-       String right="right";
+
+       /* Rewrite globals */
+
+       for (Iterator it=this.state.stGlobals.descriptors();it.hasNext();) {
+           VarDescriptor vd=(VarDescriptor)it.next();
+           craux.outputline("#define "+vd.getSafeSymbol()+" "+ststate+"->"+vd.getSafeSymbol());
+       }
+
        for(Iterator it=termination.updatenodes.iterator();it.hasNext();) {
            GraphNode gn=(GraphNode) it.next();
            TermNode tn=(TermNode) gn.getOwner();
@@ -101,19 +138,25 @@ public class RepairGenerator {
                switch(mun.op) {
                case MultUpdateNode.ADD:
                    if (isrelation) {
-                       crhead.outputline("void "+methodname+"("+name+"_state * " +state+","+name+" * "+model+", RepairHash * "+repairtable+", int "+left+", int "+right+");");
-                       craux.outputline("void "+methodname+"("+name+"_state * "+ state+","+name+" * "+model+", RepairHash * "+repairtable+", int "+left+", int "+right+")");
+                       crhead.outputline("void "+methodname+"("+name+"_state * " +ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+", int "+stright+");");
+                       craux.outputline("void "+methodname+"("+name+"_state * "+ ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+", int "+stright+")");
                    } else {
-                       crhead.outputline("void "+methodname+"("+name+"_state * "+ state+","+name+" * "+model+", RepairHash * "+repairtable+", int "+left+");");
-                       craux.outputline("void "+methodname+"("+name+"_state * "+state+","+name+" * "+model+", RepairHash * "+repairtable+", int "+left+")");
+                       crhead.outputline("void "+methodname+"("+name+"_state * "+ ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+");");
+                       craux.outputline("void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable+", int "+stleft+")");
                    }
                    craux.startblock();
-                   un.generate(craux, false, left,right);
+                   craux.outputline("int maybe=0;");
+                   final SymbolTable st = un.getRule().getSymbolTable();                
+                   CodeWriter cr = new StandardCodeWriter(outputaux) {
+                        public SymbolTable getSymbolTable() { return st; }
+                    };
+                   un.generate(cr, false, false, stleft,stright, null,this);
+                   craux.outputline("if (maybe) printf(\"REALLY BAD\");");
                    craux.endblock();
                    break;
-               case MultUpdateNode.REMOVE:
+               case MultUpdateNode.REMOVE: {
                    Rule r=un.getRule();
-                   String methodcall="void "+methodname+"("+name+"_state * "+state+","+name+" * "+model+", RepairHash * "+repairtable;
+                   String methodcall="void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable;
                    for(int j=0;j<r.numQuantifiers();j++) {
                        Quantifier q=r.getQuantifier(j);
                        if (q instanceof SetQuantifier) {
@@ -133,10 +176,50 @@ public class RepairGenerator {
                    crhead.outputline(methodcall+";");
                    craux.outputline(methodcall);
                    craux.startblock();
-                   un.generate(craux, true, null,null);
+                   craux.outputline("int maybe=0;");
+                   final SymbolTable st2 = un.getRule().getSymbolTable();
+                   CodeWriter cr2 = new StandardCodeWriter(outputaux) {
+                        public SymbolTable getSymbolTable() { return st2; }
+                    };
+                   un.generate(cr2, true, false, null,null, null,this);
+                   craux.outputline("if (maybe) printf(\"REALLY BAD\");");
                    craux.endblock();
+               }
                    break;
-               case MultUpdateNode.MODIFY:
+               case MultUpdateNode.MODIFY: {
+                   Rule r=un.getRule();
+                   String methodcall="void "+methodname+"("+name+"_state * "+ststate+","+name+" * "+stmodel+", RepairHash * "+strepairtable;
+                   for(int j=0;j<r.numQuantifiers();j++) {
+                       Quantifier q=r.getQuantifier(j);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getType().getGenerateType().getSafeSymbol()+" "+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           
+                           methodcall+=", "+rq.x.getType().getGenerateType().getSafeSymbol()+" "+rq.x.getSafeSymbol();
+                           methodcall+=", "+rq.y.getType().getGenerateType().getSafeSymbol()+" "+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=", int "+fq.getVar().getSafeSymbol();
+                       }
+                   }
+                   methodcall+=", "+stleft+", "+stright+", "+stnew;
+                   methodcall+=")";
+                   crhead.outputline(methodcall+";");
+                   craux.outputline(methodcall);
+                   craux.startblock();
+                   craux.outputline("int maybe=0;");
+                   final SymbolTable st2 = un.getRule().getSymbolTable();
+                   CodeWriter cr2 = new StandardCodeWriter(outputaux) {
+                        public SymbolTable getSymbolTable() { return st2; }
+                    };
+                   un.generate(cr2, false, true, stleft, stright, stnew, this);
+                   craux.outputline("if (maybe) printf(\"REALLY BAD\");");
+                   craux.endblock();
+               }
+                   break;
+
                default:
                    throw new Error("Nonimplement Update");
                }
@@ -189,12 +272,95 @@ public class RepairGenerator {
            VarDescriptor vd=(VarDescriptor) globals.next();
            crhead.outputline(vd.getType().getGenerateType().getSafeSymbol()+" "+vd.getSafeSymbol()+";");
        }
+       crhead.outputline("void computesizes(int *,int **);");
+       crhead.outputline("void recomputesizes();");
     }
 
+    private void generate_computesizes() {
+       int max=TypeDescriptor.counter;
+       TypeDescriptor[] tdarray=new TypeDescriptor[max];
+       for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
+           TypeDescriptor ttd=(TypeDescriptor)it.next();
+           tdarray[ttd.getId()]=ttd;
+       }
+       final SymbolTable st = state.stGlobals;
+       CodeWriter cr = new StandardCodeWriter(outputaux) {
+               public SymbolTable getSymbolTable() { return st; }
+           };
+
+       cr.outputline("void "+name+"_state::computesizes(int *sizearray,int **numele) {");
+       for(int i=0;i<max;i++) {
+           TypeDescriptor td=tdarray[i];
+           Expr size=td.getSizeExpr();
+           VarDescriptor vd=VarDescriptor.makeNew("size");
+           size.generate(cr,vd);
+           cr.outputline("sizearray["+i+"]="+vd.getSafeSymbol()+";");
+       }
+       for(int i=0;i<max;i++) {
+           TypeDescriptor td=tdarray[i];
+           if (td instanceof StructureTypeDescriptor) {
+               StructureTypeDescriptor std=(StructureTypeDescriptor) td;
+               for(int j=0;j<std.fieldlist.size();j++) {
+                   FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
+                   if (fd instanceof ArrayDescriptor) {
+                       ArrayDescriptor ad=(ArrayDescriptor)fd;
+                       Expr index=ad.getIndexBound();
+                       VarDescriptor vd=VarDescriptor.makeNew("index");
+                       index.generate(cr,vd);
+                       cr.outputline("numele["+i+"]["+j+"]="+vd.getSafeSymbol()+";");
+                   }
+               }
+           }
+       }
+       cr.outputline("}");
+    }
+
+    private void generate_recomputesizes() {
+       int max=TypeDescriptor.counter;
+       TypeDescriptor[] tdarray=new TypeDescriptor[max];
+       for(Iterator it=state.stTypes.descriptors();it.hasNext();) {
+           TypeDescriptor ttd=(TypeDescriptor)it.next();
+           tdarray[ttd.getId()]=ttd;
+       }
+       final SymbolTable st = state.stGlobals;
+       CodeWriter cr = new StandardCodeWriter(outputaux) {
+               public SymbolTable getSymbolTable() { return st; }
+           };
+       cr.outputline("void "+name+"_state::recomputesizes() {");
+       for(int i=0;i<max;i++) {
+           TypeDescriptor td=tdarray[i];
+           Expr size=td.getSizeExpr();
+           VarDescriptor vd=VarDescriptor.makeNew("size");
+           size.generate(cr,vd);
+       }
+       for(int i=0;i<max;i++) {
+           TypeDescriptor td=tdarray[i];
+           if (td instanceof StructureTypeDescriptor) {
+               StructureTypeDescriptor std=(StructureTypeDescriptor) td;
+               for(int j=0;j<std.fieldlist.size();j++) {
+                   FieldDescriptor fd=(FieldDescriptor)std.fieldlist.get(j);
+                   if (fd instanceof ArrayDescriptor) {
+                       ArrayDescriptor ad=(ArrayDescriptor)fd;
+                       Expr index=ad.getIndexBound();
+                       VarDescriptor vd=VarDescriptor.makeNew("index");
+                       index.generate(cr,vd);
+                   }
+               }
+           }
+       }
+       cr.outputline("}");
+    }
+
+
     private void generate_hashtables() {
         CodeWriter craux = new StandardCodeWriter(outputaux);
         CodeWriter crhead = new StandardCodeWriter(outputhead);
+       crhead.outputline("#ifndef "+name+"_h");
+       crhead.outputline("#define "+name+"_h");
         crhead.outputline("#include \"SimpleHash.h\"");
+       crhead.outputline("extern \"C\" {");
+        crhead.outputline("#include \"instrument.h\"");
+       crhead.outputline("}");
         crhead.outputline("#include <stdio.h>");
         crhead.outputline("#include <stdlib.h>");
        crhead.outputline("class "+name+" {");
@@ -202,6 +368,7 @@ public class RepairGenerator {
        crhead.outputline(name+"();");
        crhead.outputline("~"+name+"();");
         craux.outputline("#include \""+headername+"\"");
+        craux.outputline("#include \"size.h\"");
 
         craux.outputline(name+"::"+name+"() {");
         craux.outputline("// creating hashtables ");
@@ -273,13 +440,13 @@ public class RepairGenerator {
             }
 
             if (relation.testUsage(RelationDescriptor.INVIMAGE)) {
-                craux.outputline("delete " + relation.getSafeSymbol() + ";");
+                craux.outputline("delete " + relation.getSafeSymbol() + "_hashinv;");
             } 
         }
         craux.outputline("}");
     }
 
-    private void generate_worklist() {
+    private void generate_start() {
         CodeWriter crhead = new StandardCodeWriter(outputhead);
         CodeWriter craux = new StandardCodeWriter(outputaux);
        oldmodel=VarDescriptor.makeNew("oldmodel");
@@ -289,174 +456,210 @@ public class RepairGenerator {
        repairtable=VarDescriptor.makeNew("repairtable");
        crhead.outputline("void doanalysis();");
        craux.outputline("void "+name +"_state::doanalysis()");
-       craux.startblock();
+       craux.startblock();
+       craux.outputline("int highmark;");
+       craux.outputline("initializestack(&highmark);");
+       craux.outputline("typeobject *typeobject1=gettypeobject();");
+       craux.outputline("typeobject1->computesizes(this);");
+       craux.outputline("recomputesizes();");
        craux.outputline(name+ " * "+oldmodel.getSafeSymbol()+"=0;");
         craux.outputline("WorkList * "+worklist.getSafeSymbol()+" = new WorkList();");
        craux.outputline("RepairHash * "+repairtable.getSafeSymbol()+"=0;");
        craux.outputline("while (1)");
        craux.startblock();
-       craux.outputline("int "+goodflag.getSafeSymbol()+"=1;");
        craux.outputline(name+ " * "+newmodel.getSafeSymbol()+"=new "+name+"();");
     }
     
     private void generate_teardown() {
        CodeWriter cr = new StandardCodeWriter(outputaux);        
-       cr.outputline("if ("+repairtable.getSafeSymbol()+")");
-       cr.outputline("delete "+repairtable.getSafeSymbol()+";");
-       cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
-       cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
-       cr.outputline("delete "+newmodel.getSafeSymbol()+";");
-       cr.outputline("delete "+worklist.getSafeSymbol()+";");
        cr.endblock();
     }
 
-    private void generate_rules() {
-       /* first we must sort the rules */
-        Iterator allrules = state.vRules.iterator();
-        Vector emptyrules = new Vector(); // rules with no quantifiers
-        Vector worklistrules = new Vector(); // the rest of the rules
-       RelationDescriptor.prefix = newmodel.getSafeSymbol()+"->";
-       SetDescriptor.prefix = newmodel.getSafeSymbol()+"->";
-
-        while (allrules.hasNext()) {
-            Rule rule = (Rule) allrules.next();
-            ListIterator quantifiers = rule.quantifiers();
-            boolean noquantifiers = true;
-            while (quantifiers.hasNext()) {
-                Quantifier quantifier = (Quantifier) quantifiers.next();
-                if (quantifier instanceof ForQuantifier) {
-                    // ok, because integers exist already!
-                } else {
-                    // real quantifier
-                    noquantifiers = false;
-                    break;
-                }
-            }
-            if (noquantifiers) {
-                emptyrules.add(rule);
-            } else {
-                worklistrules.add(rule);
-            }
-        }
-       
-        Iterator iterator_er = emptyrules.iterator();
-        while (iterator_er.hasNext()) {
-            Rule rule = (Rule) iterator_er.next();
-            {
-                final SymbolTable st = rule.getSymbolTable();                
-                CodeWriter cr = new StandardCodeWriter(outputaux) {
-                        public SymbolTable getSymbolTable() { return st; }
-                    };
-               cr.outputline("// build " +escape(rule.toString()));
-                cr.startblock();
-                ListIterator quantifiers = rule.quantifiers();
-                while (quantifiers.hasNext()) {
-                    Quantifier quantifier = (Quantifier) quantifiers.next();
-                    quantifier.generate_open(cr);
-                }
-                        
-                /* pretty print! */
-                cr.output("//");
-                rule.getGuardExpr().prettyPrint(cr);
-                cr.outputline("");
-
-                /* now we have to generate the guard test */
-               VarDescriptor guardval = VarDescriptor.makeNew();
-                rule.getGuardExpr().generate(cr, guardval);
-               cr.outputline("if (" + guardval.getSafeSymbol() + ")");
-                cr.startblock();
+    private void generate_print() {
+       
+       final SymbolTable st = new SymbolTable();
 
-                /* now we have to generate the inclusion code */
-               currentrule=rule;
-                rule.getInclusion().generate(cr);
-                cr.endblock();
-                while (quantifiers.hasPrevious()) {
-                    Quantifier quantifier = (Quantifier) quantifiers.previous();
-                    cr.endblock();
-                }
-                cr.endblock();
-                cr.outputline("");
-                cr.outputline("");
-            }
-        }
+       CodeWriter cr = new StandardCodeWriter(outputaux) {
+               public SymbolTable getSymbolTable() { return st; }
+           };
 
-        CodeWriter cr2 = new StandardCodeWriter(outputaux);        
+       cr.outputline("// printing sets!");
+       cr.outputline("printf(\"\\n\\nPRINTING SETS AND RELATIONS\\n\");");
 
-        cr2.outputline("while ("+goodflag.getSafeSymbol()+"&&"+worklist.getSafeSymbol()+"->hasMoreElements())");
-        cr2.startblock();
-       VarDescriptor idvar=VarDescriptor.makeNew("id");
-        cr2.outputline("int "+idvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getid();");
-        
-        String elseladder = "if";
+        Iterator setiterator = state.stSets.descriptors();
+       while (setiterator.hasNext()) {
+           SetDescriptor sd = (SetDescriptor) setiterator.next();
+           if (sd.getSymbol().equals("int") || sd.getSymbol().equals("token")) {
+               continue;
+           }
 
-        Iterator iterator_rules = worklistrules.iterator();
-        while (iterator_rules.hasNext()) {
+           String setname = sd.getSafeSymbol();
 
-            Rule rule = (Rule) iterator_rules.next();
-            int dispatchid = rule.getNum();
+           cr.startblock();
+           cr.outputline("// printing set " + setname);
+           cr.outputline("printf(\"\\nPrinting set " + sd.getSymbol() + " - %d elements \\n\", " + setname + "_hash->count());");
+           cr.outputline("SimpleIterator __setiterator;");
+           cr.outputline("" + setname + "_hash->iterator(__setiterator);");
+           cr.outputline("while (__setiterator.hasNext())");
+           cr.startblock();
+           cr.outputline("int __setval = (int) __setiterator.next();");
+
+           TypeDescriptor td = sd.getType();
+           if (td instanceof StructureTypeDescriptor) {
+               StructureTypeDescriptor std = (StructureTypeDescriptor) td;
+               VarDescriptor vd = new VarDescriptor ("__setval", "__setval", td, false);
+               std.generate_printout(cr, vd);
+           } else { // Missing type descriptor or reserved type, just print int
+               cr.outputline("printf(\"<%d> \", __setval);");                  
+           }
 
-            {
-                final SymbolTable st = rule.getSymbolTable();
-                CodeWriter cr = new StandardCodeWriter(outputaux) {
-                        public SymbolTable getSymbolTable() { return st; }
-                    };
 
-                cr.indent();
-                cr.outputline(elseladder + " ("+idvar.getSafeSymbol()+" == " + dispatchid + ")");
-                cr.startblock();
-               VarDescriptor typevar=VarDescriptor.makeNew("type");
-               VarDescriptor leftvar=VarDescriptor.makeNew("left");
-               VarDescriptor rightvar=VarDescriptor.makeNew("right");
-               cr.outputline("int "+typevar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->gettype();");
-               cr.outputline("int "+leftvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getlvalue();");
-               cr.outputline("int "+rightvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getrvalue();");
-               cr.outputline("// build " +escape(rule.toString()));
+           cr.endblock();
+           cr.endblock();
+       }
 
+       cr.outputline("printf(\"\\n\\n------------------- END PRINTING\\n\");");
+    }
 
-               for (int j=0;j<rule.numQuantifiers();j++) {
-                   Quantifier quantifier = rule.getQuantifier(j);
-                   quantifier.generate_open(cr, typevar.getSafeSymbol(),j,leftvar.getSafeSymbol(),rightvar.getSafeSymbol());
+    Set ruleset=null;
+    private void generate_rules() {
+       /* first we must sort the rules */
+       RelationDescriptor.prefix = newmodel.getSafeSymbol()+"->";
+       SetDescriptor.prefix = newmodel.getSafeSymbol()+"->";
+       System.out.println("SCC="+(mrd.numSCC()-1));
+       for(int sccindex=0;sccindex<mrd.numSCC();sccindex++) {
+           ruleset=mrd.getSCC(sccindex);
+           boolean needworklist=mrd.hasCycle(sccindex);
+           
+           if (!needworklist) {
+               Iterator iterator_rs = ruleset.iterator();
+               while (iterator_rs.hasNext()) {
+                   Rule rule = (Rule) iterator_rs.next();
+                   {
+                       final SymbolTable st = rule.getSymbolTable();
+                       CodeWriter cr = new StandardCodeWriter(outputaux) {
+                               public SymbolTable getSymbolTable() { return st; }
+                           };
+                       cr.outputline("// build " +escape(rule.toString()));
+                       cr.startblock();
+                       cr.outputline("int maybe=0;");
+                       ListIterator quantifiers = rule.quantifiers();
+                       while (quantifiers.hasNext()) {
+                           Quantifier quantifier = (Quantifier) quantifiers.next();
+                           quantifier.generate_open(cr);
+                       }
+                       
+                       /* pretty print! */
+                       cr.output("//");
+                       rule.getGuardExpr().prettyPrint(cr);
+                       cr.outputline("");
+                       
+                       /* now we have to generate the guard test */
+                       VarDescriptor guardval = VarDescriptor.makeNew();
+                       rule.getGuardExpr().generate(cr, guardval);
+                       cr.outputline("if (" + guardval.getSafeSymbol() + ")");
+                       cr.startblock();
+                       
+                       /* now we have to generate the inclusion code */
+                       currentrule=rule;
+                       rule.getInclusion().generate(cr);
+                       cr.endblock();
+                       while (quantifiers.hasPrevious()) {
+                           Quantifier quantifier = (Quantifier) quantifiers.previous();
+                           cr.endblock();
+                       }
+                       cr.endblock();
+                       cr.outputline("");
+                       cr.outputline("");
+                   }
                }
-
-                /* pretty print! */
-                cr.output("//");
-
-                rule.getGuardExpr().prettyPrint(cr);
-                cr.outputline("");
-
-                /* now we have to generate the guard test */
-        
-                VarDescriptor guardval = VarDescriptor.makeNew();
-                rule.getGuardExpr().generate(cr, guardval);
-                
-                cr.outputline("if (" + guardval.getSafeSymbol() + ")");
-                cr.startblock();
-
-                /* now we have to generate the inclusion code */
-               currentrule=rule;
-                rule.getInclusion().generate(cr);
-                cr.endblock();
-
-               for (int j=0;j<rule.numQuantifiers();j++) {
-                   cr.endblock();
+           } else {
+               CodeWriter cr2 = new StandardCodeWriter(outputaux);
+               
+               for(Iterator initialworklist=ruleset.iterator();initialworklist.hasNext();) {
+                   /** Construct initial worklist set */
+                   Rule rule=(Rule)initialworklist.next();
+                   cr2.outputline(worklist.getSafeSymbol()+"->add("+rule.getNum()+",-1,0,0);");
                }
 
-                // close startblocks generated by DotExpr memory checks
-                //DotExpr.generate_memory_endblocks(cr);
-
-                cr.endblock(); // end else-if WORKLIST ladder
-
-                elseladder = "else if";
-            }
-        }
-
-        cr2.outputline("else");
-        cr2.startblock();
-        cr2.outputline("printf(\"VERY BAD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\");");
-        cr2.outputline("exit(1);");
-        cr2.endblock();
-        // end block created for worklist
-        cr2.endblock();
+               cr2.outputline("while ("+worklist.getSafeSymbol()+"->hasMoreElements())");
+               cr2.startblock();
+               VarDescriptor idvar=VarDescriptor.makeNew("id");
+               cr2.outputline("int "+idvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getid();");
+               
+               String elseladder = "if";
+               
+               Iterator iterator_rules = ruleset.iterator();
+               while (iterator_rules.hasNext()) {
+                   
+                   Rule rule = (Rule) iterator_rules.next();
+                   int dispatchid = rule.getNum();
+                   
+                   {
+                       final SymbolTable st = rule.getSymbolTable();
+                       CodeWriter cr = new StandardCodeWriter(outputaux) {
+                               public SymbolTable getSymbolTable() { return st; }
+                           };
+                       
+                       cr.indent();
+                       cr.outputline(elseladder + " ("+idvar.getSafeSymbol()+" == " + dispatchid + ")");
+                       cr.startblock();
+                       cr.outputline("int maybe=0;");
+                       VarDescriptor typevar=VarDescriptor.makeNew("type");
+                       VarDescriptor leftvar=VarDescriptor.makeNew("left");
+                       VarDescriptor rightvar=VarDescriptor.makeNew("right");
+                       cr.outputline("int "+typevar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->gettype();");
+                       cr.outputline("int "+leftvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getlvalue();");
+                       cr.outputline("int "+rightvar.getSafeSymbol()+"="+worklist.getSafeSymbol()+"->getrvalue();");
+                       cr.outputline("// build " +escape(rule.toString()));
+                       
+                       
+                       for (int j=0;j<rule.numQuantifiers();j++) {
+                           Quantifier quantifier = rule.getQuantifier(j);
+                           quantifier.generate_open(cr, typevar.getSafeSymbol(),j,leftvar.getSafeSymbol(),rightvar.getSafeSymbol());
+                       }
+                       
+                       /* pretty print! */
+                       cr.output("//");
+                       
+                       rule.getGuardExpr().prettyPrint(cr);
+                       cr.outputline("");
+                       
+                       /* now we have to generate the guard test */
+                       
+                       VarDescriptor guardval = VarDescriptor.makeNew();
+                       rule.getGuardExpr().generate(cr, guardval);
+                       
+                       cr.outputline("if (" + guardval.getSafeSymbol() + ")");
+                       cr.startblock();
+                       
+                       /* now we have to generate the inclusion code */
+                       currentrule=rule;
+                       rule.getInclusion().generate(cr);
+                       cr.endblock();
+                       
+                       for (int j=0;j<rule.numQuantifiers();j++) {
+                           cr.endblock();
+                       }
+                       
+                       // close startblocks generated by DotExpr memory checks
+                       //DotExpr.generate_memory_endblocks(cr);
+                       
+                       cr.endblock(); // end else-if WORKLIST ladder
+                       
+                       elseladder = "else if";
+                   }
+               }
+               cr2.outputline("else");
+               cr2.startblock();
+               cr2.outputline("printf(\"VERY BAD !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\");");
+               cr2.outputline("exit(1);");
+               cr2.endblock();
+               // end block created for worklist
+               cr2.outputline(worklist.getSafeSymbol()+"->pop();");
+               cr2.endblock();
+           }
+       }
     }
 
     public static String escape(String s) {
@@ -474,29 +677,28 @@ public class RepairGenerator {
     private void generate_checks() {
 
         /* do constraint checks */
-        Vector constraints = state.vConstraints;
+       //        Vector constraints = state.vConstraints;
 
-        for (int i = 0; i < constraints.size(); i++) {
-
-            Constraint constraint = (Constraint) constraints.elementAt(i); 
 
+       //        for (int i = 0; i < constraints.size(); i++) {
+       //            Constraint constraint = (Constraint) constraints.elementAt(i); 
+       for (Iterator i = termination.constraintdependence.computeOrdering().iterator(); i.hasNext();) {
+           Constraint constraint = (Constraint) ((GraphNode)i.next()).getOwner();
+           
             {
+               final SymbolTable st = constraint.getSymbolTable();
+               CodeWriter cr = new StandardCodeWriter(outputaux);
+               cr.pushSymbolTable(constraint.getSymbolTable());
 
-                final SymbolTable st = constraint.getSymbolTable();
-                
-                CodeWriter cr = new StandardCodeWriter(outputaux) {
-                        public SymbolTable getSymbolTable() { return st; }
-                    };
-
-                cr.outputline("// checking " + escape(constraint.toString()));
+               cr.outputline("// checking " + escape(constraint.toString()));
                 cr.startblock();
 
                 ListIterator quantifiers = constraint.quantifiers();
 
                 while (quantifiers.hasNext()) {
-                    Quantifier quantifier = (Quantifier) quantifiers.next();                   
+                    Quantifier quantifier = (Quantifier) quantifiers.next();
                     quantifier.generate_open(cr);
-                }            
+                }
 
                 cr.outputline("int maybe = 0;");
                         
@@ -507,15 +709,15 @@ public class RepairGenerator {
                 
                 cr.outputline("if (maybe)");
                 cr.startblock();
-                cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \");");
+                cr.outputline("printf(\"maybe fail " +  escape(constraint.toString()) + ". \\n\");");
                 cr.outputline("exit(1);");
                 cr.endblock();
 
                 cr.outputline("else if (!" + constraintboolean.getSafeSymbol() + ")");
                 cr.startblock();
-                if (DEBUG)
-                   cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \");");
-
+                if (!Compiler.REPAIR)
+                   cr.outputline("printf(\"fail " + escape(constraint.toString()) + ". \\n\");");
+               else {
                /* Do repairs */
                /* Build new repair table */
                cr.outputline("if ("+repairtable.getSafeSymbol()+")");
@@ -527,8 +729,11 @@ public class RepairGenerator {
                VarDescriptor mincost=VarDescriptor.makeNew("mincost");
                VarDescriptor mincostindex=VarDescriptor.makeNew("mincostindex");
                DNFConstraint dnfconst=constraint.dnfconstraint;
-               cr.outputline("int "+mincostindex.getSafeSymbol()+";");
+               if (dnfconst.size()<=1) {
+                   cr.outputline("int "+mincostindex.getSafeSymbol()+"=0;");
+               }
                if (dnfconst.size()>1) {
+                   cr.outputline("int "+mincostindex.getSafeSymbol()+";");
                    boolean first=true;
                    for(int j=0;j<dnfconst.size();j++) {
                        Conjunction conj=dnfconst.get(j);
@@ -571,7 +776,8 @@ public class RepairGenerator {
                cr.outputline("switch("+mincostindex.getSafeSymbol()+") {");
                for(int j=0;j<dnfconst.size();j++) {
                    Conjunction conj=dnfconst.get(j);
-                   GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);                    if (removed.contains(gn))
+                   GraphNode gn=(GraphNode)termination.conjtonodemap.get(conj);
+                   if (removed.contains(gn))
                        continue;
                    cr.outputline("case "+j+":");
                    for(int k=0;k<conj.size();k++) {
@@ -597,31 +803,41 @@ public class RepairGenerator {
                        cr.endblock();
                    }
                    /* Update model */
-                   
                    cr.outputline("break;");
                }
                cr.outputline("}");
 
-               cr.outputline(goodflag.getSafeSymbol()+"=0;");
                cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
                cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
                cr.outputline(oldmodel.getSafeSymbol()+"="+newmodel.getSafeSymbol()+";");
-               cr.outputline("break;");  /* Rebuild model and all */
-
+               cr.outputline("goto rebuild;");  /* Rebuild model and all */
+               }
                 cr.endblock();
-
+               
                 while (quantifiers.hasPrevious()) {
                     Quantifier quantifier = (Quantifier) quantifiers.previous();
                     cr.endblock();
                 }
-               cr.outputline("if ("+goodflag.getSafeSymbol()+")");
-               cr.outputline("break;");
                 cr.endblock();
                 cr.outputline("");
                 cr.outputline("");
             }
         }
-    }    
+       CodeWriter cr = new StandardCodeWriter(outputaux);
+       cr.startblock();
+       cr.outputline("if ("+repairtable.getSafeSymbol()+")");
+       cr.outputline("delete "+repairtable.getSafeSymbol()+";");
+       cr.outputline("if ("+oldmodel.getSafeSymbol()+")");
+       cr.outputline("delete "+oldmodel.getSafeSymbol()+";");
+       cr.outputline("delete "+newmodel.getSafeSymbol()+";");
+       cr.outputline("delete "+worklist.getSafeSymbol()+";");
+       cr.outputline("resettypemap();");
+       cr.outputline("break;");
+       cr.endblock();
+       cr.outputline("rebuild:");
+       cr.outputline(";");     
+       
+    }
     
     private MultUpdateNode getmultupdatenode(Conjunction conj, DNFPredicate dpred, int repairtype) {
        MultUpdateNode mun=null;
@@ -649,7 +865,10 @@ public class RepairGenerator {
        return mun;
     }
 
-    public void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
+    /** Generates abstract (and concrete) repair for a comparison */
+
+    private void generatecomparisonrepair(Conjunction conj, DNFPredicate dpred, CodeWriter cr){
+       MultUpdateNode munmodify=getmultupdatenode(conj,dpred,AbstractRepair.MODIFYRELATION);
        MultUpdateNode munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMRELATION);
        MultUpdateNode munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTORELATION);
        ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
@@ -701,7 +920,7 @@ public class RepairGenerator {
            /* Equal */
        } else if (opcode==Opcode.EQ) {
            /* Equal */
-       } else if (opcode==Opcode.NE) {
+       } else if (opcode==Opcode.NE) { /* search for FLAGNE if this is changed*/
            cr.outputline(newvalue.getSafeSymbol()+"++;");
        } else {
            throw new Error("Unrecognized Opcode");
@@ -724,27 +943,44 @@ public class RepairGenerator {
            }
        }
        /* Do concrete repairs */
-       /* Start with scheduling removal */
-       for(int i=0;i<state.vRules.size();i++) {
-           Rule r=(Rule)state.vRules.get(i);
-           if (r.getInclusion().getTargetDescriptors().contains(rd)) {
-               for(int j=0;j<munremove.numUpdates();j++) {
-                   UpdateNode un=munremove.getUpdate(i);
-                   if (un.getRule()==r) {
-                       /* Update for rule r */
-                       String name=(String)updatenames.get(un);
-                       cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
+       if (munmodify!=null) {
+           for(int i=0;i<state.vRules.size();i++) {
+               Rule r=(Rule)state.vRules.get(i);
+               if (r.getInclusion().getTargetDescriptors().contains(rd)) {
+                   for(int j=0;j<munmodify.numUpdates();j++) {
+                       UpdateNode un=munmodify.getUpdate(j);
+                       if (un.getRule()==r) {
+                           /* Update for rule r */
+                           String name=(String)updatenames.get(un);
+                           cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+","+newvalue.getSafeSymbol()+");");
+                       }
                    }
                }
            }
-       }
-       /* Now do addition */
-       UpdateNode un=munadd.getUpdate(0);
-       String name=(String)updatenames.get(un);
-       if (!inverted) {
-           cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
+
        } else {
-           cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
+           /* Start with scheduling removal */
+           for(int i=0;i<state.vRules.size();i++) {
+               Rule r=(Rule)state.vRules.get(i);
+               if (r.getInclusion().getTargetDescriptors().contains(rd)) {
+                   for(int j=0;j<munremove.numUpdates();j++) {
+                       UpdateNode un=munremove.getUpdate(i);
+                       if (un.getRule()==r) {
+                           /* Update for rule r */
+                           String name=(String)updatenames.get(un);
+                           cr.outputline(repairtable.getSafeSymbol()+"->addrelation("+rd.getNum()+","+r.getNum()+","+leftside.getSafeSymbol()+","+rightside.getSafeSymbol()+",(int) &"+name+");");
+                       }
+                   }
+               }
+           }
+           /* Now do addition */
+           UpdateNode un=munadd.getUpdate(0);
+           String name=(String)updatenames.get(un);
+           if (!inverted) {
+               cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+leftside.getSafeSymbol()+","+newvalue.getSafeSymbol()+");");
+           } else {
+               cr.outputline(name+"(this,"+newmodel.getSafeSymbol()+","+repairtable.getSafeSymbol()+","+newvalue.getSafeSymbol()+","+rightside.getSafeSymbol()+");");
+           }
        }
     }
 
@@ -752,25 +988,8 @@ public class RepairGenerator {
        ExprPredicate ep=(ExprPredicate)dpred.getPredicate();
        OpExpr expr=(OpExpr)ep.expr;
        Opcode opcode=expr.getOpcode();
-       {
-           boolean negated=dpred.isNegated();
-           if (negated)
-               if (opcode==Opcode.GT) {
-                   opcode=Opcode.LE;
-               } else if (opcode==Opcode.GE) {
-                   opcode=Opcode.LT;
-               } else if (opcode==Opcode.LT) {
-                   opcode=Opcode.GE;
-               } else if (opcode==Opcode.LE) {
-                   opcode=Opcode.GT;
-               } else if (opcode==Opcode.EQ) {
-                   opcode=Opcode.NE;
-               } else if (opcode==Opcode.NE) {
-                   opcode=Opcode.EQ;
-               } else {
-                   throw new Error("Unrecognized Opcode");
-               }       
-       }
+       opcode=Opcode.translateOpcode(dpred.isNegated(),opcode);
+
        MultUpdateNode munremove;
 
        MultUpdateNode munadd;
@@ -781,7 +1000,7 @@ public class RepairGenerator {
            munremove=getmultupdatenode(conj,dpred,AbstractRepair.REMOVEFROMSET);
            munadd=getmultupdatenode(conj,dpred,AbstractRepair.ADDTOSET);
        }
-       int size=ep.leftsize();
+       int size=ep.rightSize();
        VarDescriptor sizevar=VarDescriptor.makeNew("size");
        ((OpExpr)expr).left.generate(cr, sizevar);
        VarDescriptor change=VarDescriptor.makeNew("change");
@@ -806,7 +1025,10 @@ public class RepairGenerator {
            generateremove=true;
        } else if (opcode==Opcode.EQ) {
            cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size)+"-"+sizevar.getSafeSymbol()+";");
-           generateadd=true;
+           if (size==0)
+               generateadd=false;
+           else 
+               generateadd=true;
            generateremove=true;
        } else if (opcode==Opcode.NE) {
            cr.outputline(change.getSafeSymbol()+"="+String.valueOf(size+1)+"-"+sizevar.getSafeSymbol()+";");
@@ -815,6 +1037,12 @@ public class RepairGenerator {
        } else {
            throw new Error("Unrecognized Opcode");
        }
+
+// In some cases the analysis has determined that generating removes
+// is unnecessary
+       if (generateremove&&munremove==null) 
+           generateremove=false;
+
        Descriptor d=ep.getDescriptor();
        if (generateremove) {
            cr.outputline("for(;"+change.getSafeSymbol()+"<0;"+change.getSafeSymbol()+"++)");
@@ -829,7 +1057,7 @@ public class RepairGenerator {
                    cr.outputline(d.getSafeSymbol()+"_hashinv->get((int)"+rightvar.getSafeSymbol()+","+leftvar.getSafeSymbol()+");");
                } else {
                    leftvar=((ImageSetExpr)((SizeofExpr)((OpExpr)expr).left).setexpr).getVar();
-                   cr.outputline("int "+rightvar.getSafeSymbol()+";");
+                   cr.outputline("int "+rightvar.getSafeSymbol()+"=0;");
                    cr.outputline(d.getSafeSymbol()+"_hash->get((int)"+leftvar.getSafeSymbol()+","+rightvar.getSafeSymbol()+");");
                }
            } else {
@@ -841,18 +1069,18 @@ public class RepairGenerator {
                boolean usageimage=rd.testUsage(RelationDescriptor.IMAGE);
                boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
                if (usageimage)
-                   cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + rightvar + ");");
+                   cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
                if (usageinvimage)
-                   cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar + ", (int)" + leftvar + ");");
+                   cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
            } else {
-               cr.outputline(d.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + leftvar + ");");
+               cr.outputline(d.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
            }
            /* Generate concrete remove instruction */
            for(int i=0;i<state.vRules.size();i++) {
                Rule r=(Rule)state.vRules.get(i);
                if (r.getInclusion().getTargetDescriptors().contains(d)) {
                    for(int j=0;j<munremove.numUpdates();j++) {
-                       UpdateNode un=munremove.getUpdate(i);
+                       UpdateNode un=munremove.getUpdate(j);
                        if (un.getRule()==r) {
                                /* Update for rule rule r */
                            String name=(String)updatenames.get(un);
@@ -873,7 +1101,7 @@ public class RepairGenerator {
            cr.startblock();
            VarDescriptor newobject=VarDescriptor.makeNew("newobject");
            if (d instanceof RelationDescriptor) {
-               VarDescriptor otherside=((ImageSetExpr)((SizeofExpr)ep.expr).setexpr).vd;
+               VarDescriptor otherside=((ImageSetExpr)((SizeofExpr)((OpExpr)ep.expr).left).setexpr).vd;
                RelationDescriptor rd=(RelationDescriptor)d;
                if (sources.relsetSource(rd,!ep.inverted())) {
                    /* Set Source */
@@ -960,14 +1188,14 @@ public class RepairGenerator {
                boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
                if (inverse) {
                    if (usageimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + rightvar + ", (int)" + leftvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
                    if (usageinvimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + leftvar + ", (int)" + rightvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
                } else {
                    if (usageimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + rightvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
                    if (usageinvimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar + ", (int)" + leftvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hashinv->remove((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
                }
                for(int i=0;i<state.vRules.size();i++) {
                    Rule r=(Rule)state.vRules.get(i);
@@ -988,7 +1216,7 @@ public class RepairGenerator {
                }
            } else {
                SetDescriptor sd=ip.setexpr.sd;
-               cr.outputline(sd.getSafeSymbol() + "_hash->remove((int)" + leftvar + ", (int)" + leftvar + ");");
+               cr.outputline(sd.getSafeSymbol() + "_hash->remove((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
 
                for(int i=0;i<state.vRules.size();i++) {
                    Rule r=(Rule)state.vRules.get(i);
@@ -1015,14 +1243,14 @@ public class RepairGenerator {
                boolean usageinvimage=rd.testUsage(RelationDescriptor.INVIMAGE);
                if (inverse) {
                    if (usageimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + rightvar + ", (int)" + leftvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
                    if (usageinvimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + leftvar + ", (int)" + rightvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
                } else {
                    if (usageimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + rightvar.getSafeSymbol() + ");");
                    if (usageinvimage)
-                       cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
+                       cr.outputline(rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
                }
                UpdateNode un=mun.getUpdate(0);
                String name=(String)updatenames.get(un);
@@ -1033,7 +1261,7 @@ public class RepairGenerator {
                }
            } else {
                SetDescriptor sd=ip.setexpr.sd;
-               cr.outputline(sd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + leftvar + ");");
+               cr.outputline(sd.getSafeSymbol() + "_hash->add((int)" + leftvar.getSafeSymbol() + ", (int)" + leftvar.getSafeSymbol() + ");");
 
                UpdateNode un=mun.getUpdate(0);
                /* Update for rule rule r */
@@ -1043,8 +1271,6 @@ public class RepairGenerator {
        }
     }
 
-
-
     public static Vector getrulelist(Descriptor d) {
         Vector dispatchrules = new Vector();
         Vector rules = State.currentState.vRules;
@@ -1065,6 +1291,8 @@ public class RepairGenerator {
     }
 
     private boolean need_compensation(Rule r) {
+       if (!Compiler.REPAIR)
+           return false;
        GraphNode gn=(GraphNode)termination.scopefalsify.get(r);
        for(Iterator edgeit=gn.edges();edgeit.hasNext();) {
            GraphNode.Edge edge=(GraphNode.Edge)edgeit.next();
@@ -1106,97 +1334,127 @@ public class RepairGenerator {
            return;
 
         cr.outputline("// RELATION DISPATCH ");
-       cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
-       if (usageimage)
-           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
-       else
-           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
-       cr.startblock(); {
-           /* Adding new item */
-           /* Perform safety checks */
-           cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
-           cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
+       if (Compiler.REPAIR) {
+           cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
+           if (usageimage)
+               cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hash->contains("+leftvar+","+rightvar+"))");
+           else
+               cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+rd.getJustSafeSymbol()+"_hashinv->contains("+rightvar+","+leftvar+"))");
+
            cr.startblock(); {
-               /* Have update to call into */
-               VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
-               String parttype="";
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
-                       parttype=parttype+", int, int";
-                   else
-                       parttype=parttype+", int";
-               }
-               cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
-               cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
-               String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               /* Adding new item */
+               /* Perform safety checks */
+               cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
+               cr.outputline(repairtable.getSafeSymbol()+"->containsrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+"))");
+               cr.startblock(); {
+                   /* Have update to call into */
+                   VarDescriptor mdfyptr=VarDescriptor.makeNew("modifyptr");
+                   cr.outputline("int "+mdfyptr.getSafeSymbol()+"="+repairtable.getSafeSymbol()+"->getrelation2("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
+                   
+                   String parttype="";
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
+                           parttype=parttype+", int, int";
+                       else
+                           parttype=parttype+", int";
+                   }
+                   VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
+                   VarDescriptor tmpptr=VarDescriptor.makeNew("tempupdateptr");
+                   
+                   String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
+                   }
+                   
+                   
+               
+                   cr.outputline("void *"+tmpptr.getSafeSymbol()+"=");
+                   cr.outputline("(void *) "+repairtable.getSafeSymbol()+"->getrelation("+rd.getNum()+","+currentrule.getNum()+","+leftvar+","+rightvar+");");
+                   cr.outputline("if ("+mdfyptr.getSafeSymbol()+")");
+                   {
+                       cr.startblock();
+                       cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+",int,int,int)) "+tmpptr.getSafeSymbol());
+                       cr.outputline(methodcall+leftvar+", "+rightvar+", "+mdfyptr.getSafeSymbol() +");");
+                       cr.endblock();
                    }
+                   cr.outputline("else ");
+                   {
+                       cr.startblock();
+                       cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")="+"(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+tmpptr.getSafeSymbol());
+                       cr.outputline(methodcall+");");
+                       cr.endblock();
+                   }
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline(goodflag.getSafeSymbol()+"=0;");
-               cr.outputline("continue;");
-           }
-           cr.endblock();
-           /* Build standard compensation actions */
-           if (need_compensation(currentrule)) {
-               UpdateNode un=find_compensation(currentrule);
-               String name=(String)updatenames.get(un);
-               usedupdates.add(un); /* Mark as used */
-               String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               cr.endblock();
+               
+               /* Build standard compensation actions */
+               if (need_compensation(currentrule)) {
+                   UpdateNode un=find_compensation(currentrule);
+                   String name=(String)updatenames.get(un);
+                   usedupdates.add(un); /* Mark as used */
+                   String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
                    }
+                   methodcall+=");";
+                   cr.outputline(methodcall);
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline(goodflag.getSafeSymbol()+"=0;");
-               cr.outputline("continue;");
            }
+           cr.endblock();
        }
-       cr.endblock();
 
         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
        cr.outputline("int " + addeditem + ";");
        if (rd.testUsage(RelationDescriptor.IMAGE)) {
-           cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar + ");");
+           cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hash->add((int)" + leftvar + ", (int)" + rightvar+ ");");
        }
        
        if (rd.testUsage(RelationDescriptor.INVIMAGE)) {
            cr.outputline(addeditem + " = " + rd.getSafeSymbol() + "_hashinv->add((int)" + rightvar + ", (int)" + leftvar + ");");
        }
        
-       cr.outputline("if (" + addeditem + ")");
-       cr.startblock();
+
 
         Vector dispatchrules = getrulelist(rd);
         
+       Set toremove=new HashSet();
+       for(int i=0;i<dispatchrules.size();i++) {
+           Rule r=(Rule)dispatchrules.get(i);
+           if (!ruleset.contains(r))
+               toremove.add(r);
+       }
+       dispatchrules.removeAll(toremove);
         if (dispatchrules.size() == 0) {
             cr.outputline("// nothing to dispatch");
-           cr.endblock();
             return;
         }
+
+       cr.outputline("if (" + addeditem + ")");
+       cr.startblock();
        
         for(int i = 0; i < dispatchrules.size(); i++) {
             Rule rule = (Rule) dispatchrules.elementAt(i);
@@ -1213,6 +1471,7 @@ public class RepairGenerator {
                }
            }
         }
+
        cr.endblock();
     }
 
@@ -1220,77 +1479,76 @@ public class RepairGenerator {
     public void generate_dispatch(CodeWriter cr, SetDescriptor sd, String setvar) {
                
         cr.outputline("// SET DISPATCH ");
-
-       cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
-       cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
-       cr.startblock(); {
-           /* Adding new item */
-           /* Perform safety checks */
-           cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
-           cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
+       if (Compiler.REPAIR) {
+           cr.outputline("if ("+oldmodel.getSafeSymbol()+"&&");
+           cr.outputline("!"+oldmodel.getSafeSymbol() +"->"+sd.getJustSafeSymbol()+"_hash->contains("+setvar+"))");
            cr.startblock(); {
-               /* Have update to call into */
-               VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
-               String parttype="";
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
-                       parttype=parttype+", int, int";
-                   else
-                       parttype=parttype+", int";
-               }
-               cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
-               cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
-               String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
-                             repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               /* Adding new item */
+               /* Perform safety checks */
+               cr.outputline("if ("+repairtable.getSafeSymbol()+"&&");
+               cr.outputline(repairtable.getSafeSymbol()+"->containsset("+sd.getNum()+","+currentrule.getNum()+","+setvar+"))");
+               cr.startblock(); {
+                   /* Have update to call into */
+                   VarDescriptor funptr=VarDescriptor.makeNew("updateptr");
+                   String parttype="";
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       if (currentrule.getQuantifier(i) instanceof RelationQuantifier)
+                           parttype=parttype+", int, int";
+                       else
+                           parttype=parttype+", int";
                    }
+                   cr.outputline("void (*"+funptr.getSafeSymbol()+") ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")=");
+                   cr.outputline("(void (*) ("+name+"_state *,"+name+"*,RepairHash *"+parttype+")) "+repairtable.getSafeSymbol()+"->getset("+sd.getNum()+","+currentrule.getNum()+","+setvar+");");
+                   String methodcall="("+funptr.getSafeSymbol()+") (this,"+oldmodel.getSafeSymbol()+","+
+                       repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
+                   }
+                   methodcall+=");";
+                   cr.outputline(methodcall);
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline(goodflag.getSafeSymbol()+"=0;");
-               cr.outputline("continue;");
-           }
-           cr.endblock();
-           /* Build standard compensation actions */
-           if (need_compensation(currentrule)) {
-               UpdateNode un=find_compensation(currentrule);
-               String name=(String)updatenames.get(un);
-               usedupdates.add(un); /* Mark as used */
-
-               String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
-                             repairtable.getSafeSymbol();
-               for(int i=0;i<currentrule.numQuantifiers();i++) {
-                   Quantifier q=currentrule.getQuantifier(i);
-                   if (q instanceof SetQuantifier) {
-                       SetQuantifier sq=(SetQuantifier) q;
-                       methodcall+=","+sq.getVar().getSafeSymbol();
-                   } else if (q instanceof RelationQuantifier) {
-                       RelationQuantifier rq=(RelationQuantifier) q;
-                       methodcall+=","+rq.x.getSafeSymbol();
-                       methodcall+=","+rq.y.getSafeSymbol();
-                   } else if (q instanceof ForQuantifier) {
-                       ForQuantifier fq=(ForQuantifier) q;
-                       methodcall+=","+fq.getVar().getSafeSymbol();
+               cr.endblock();
+               /* Build standard compensation actions */
+               if (need_compensation(currentrule)) {
+                   UpdateNode un=find_compensation(currentrule);
+                   String name=(String)updatenames.get(un);
+                   usedupdates.add(un); /* Mark as used */
+                   
+                   String methodcall=name+"(this,"+oldmodel.getSafeSymbol()+","+
+                       repairtable.getSafeSymbol();
+                   for(int i=0;i<currentrule.numQuantifiers();i++) {
+                       Quantifier q=currentrule.getQuantifier(i);
+                       if (q instanceof SetQuantifier) {
+                           SetQuantifier sq=(SetQuantifier) q;
+                           methodcall+=","+sq.getVar().getSafeSymbol();
+                       } else if (q instanceof RelationQuantifier) {
+                           RelationQuantifier rq=(RelationQuantifier) q;
+                           methodcall+=","+rq.x.getSafeSymbol();
+                           methodcall+=","+rq.y.getSafeSymbol();
+                       } else if (q instanceof ForQuantifier) {
+                           ForQuantifier fq=(ForQuantifier) q;
+                           methodcall+=","+fq.getVar().getSafeSymbol();
+                       }
                    }
+                   methodcall+=");";
+                   cr.outputline(methodcall);
+                   cr.outputline("goto rebuild;");
                }
-               methodcall+=");";
-               cr.outputline(methodcall);
-               cr.outputline(goodflag.getSafeSymbol()+"=0;");
-               cr.outputline("continue;");
            }
+           cr.endblock();
        }
-       cr.endblock();
 
         String addeditem = (VarDescriptor.makeNew("addeditem")).getSafeSymbol();
        cr.outputline("int " + addeditem + " = 1;");
@@ -1298,12 +1556,21 @@ public class RepairGenerator {
        cr.startblock();
         Vector dispatchrules = getrulelist(sd);
 
+       Set toremove=new HashSet();
+       for(int i=0;i<dispatchrules.size();i++) {
+           Rule r=(Rule)dispatchrules.get(i);
+           if (!ruleset.contains(r))
+               toremove.add(r);
+       }
+       dispatchrules.removeAll(toremove);
+
         if (dispatchrules.size() == 0) {
             cr.outputline("// nothing to dispatch");
            cr.endblock();
             return;
         }
-
+       cr.outputline("if ("+addeditem+")");
+       cr.startblock();
         for(int i = 0; i < dispatchrules.size(); i++) {
             Rule rule = (Rule) dispatchrules.elementAt(i);
            if (SetDescriptor.expand(rule.getGuardExpr().getRequiredDescriptors()).contains(sd)) {
@@ -1320,8 +1587,6 @@ public class RepairGenerator {
            }
        }
        cr.endblock();
+       cr.endblock();
     }
 }
-
-
-