Result: mostly inert changes
[sbp.git] / src / edu / berkeley / sbp / Result.java
index cb351eb..9db5aee 100644 (file)
@@ -1,30 +1,63 @@
 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
 
 package edu.berkeley.sbp;
-import edu.berkeley.sbp.*;
 import edu.berkeley.sbp.util.*;
-import edu.berkeley.sbp.Parser.Table.*;
 import edu.berkeley.sbp.Sequence.Position;
-import java.io.*;
 import java.util.*;
-import java.lang.reflect.*;
 
-class Result implements GraphViz.ToGraphViz {
+final class Result implements GraphViz.ToGraphViz {
 
     private Forest f;
     private Node parent;
     private GSS.Phase phase;
     private Position reduction;
+    private HashSet<Node> children = new HashSet<Node>();
+    private boolean destroyed = false;
+    private int usedByNonDoomedNode = 0;
 
     public Position reduction() { return reduction; }
     public GSS.Phase phase() { return phase; }
     public Forest getForest() { return f; }
     public Node parent() { return parent; }
+    public void addChild(Node child) {
+        children.add(child);
+        usedByNonDoomedNode += child.state().doomed ? 0 : 1;
+    }
+    public void removeChild(Node child) {
+        children.remove(child);
+        usedByNonDoomedNode -= child.state().doomed ? 0 : 1;
+    }
+
+    public boolean usedByAnyNode() { return children.size() > 0; }
+    public boolean usedByNonDoomedNode() { return usedByNonDoomedNode > 0; }
+
+    public String toString() { return super.toString()+"->"+parent(); }
+
+    public void check() { if (children.size()==0) destroy(); }
+    public void destroy() {
+        if (destroyed) return;
+        if (parent==null) return;  // never destroy the "primordeal" result
+        destroyed = true;
+        if (parent() != null) {
+            parent().removeChild(this);
+            parent().check();
+        }
+        OUTER: while(true) {
+            for(Node n : children) {
+                children.remove(n);
+                n.removeResult(this);
+                n.check();
+                continue OUTER;
+            }
+            break;
+        }
+    }
 
     public Result(Forest f, Node parent, Position reduction) {
         this.f = f;
         this.reduction = reduction;
         this.parent = parent;
+        if (parent != null) parent.addChild(this);
         if (parent != null) phase = parent.phase();
     }