yay, new boolean resolution approach works
[sbp.git] / src / edu / berkeley / sbp / Forest.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.util.*;
5 import java.io.*;
6 import java.util.*;
7 import java.lang.reflect.*;
8
9 /** an efficient representation of a collection of trees (Tomita's shared packed parse forest) */
10 public abstract class Forest<T> {
11
12     /** assume that this forest contains exactly one tree and return it; otherwise throw an exception */
13     public final Tree<T> expand1() throws Parser.Ambiguous, Parser.Failed {
14         Iterator<Tree<T>> it = expand(true).iterator();
15         if (!it.hasNext()) throw new Parser.Failed();
16         return it.next();
17     }
18
19     /** expand this forest into a set of trees */
20     public abstract HashSet<Tree<T>>  expand(boolean toss);
21
22     abstract boolean valid();
23
24     static <T> Forest<T>   singleton(Token.Location loc, Sequence creator)                       { return create(loc, null, new Forest[] { }, creator, false, true); }
25     static <T> Forest<T>   singleton(Token.Location loc, Forest<T> body, Sequence creator)       { return create(loc, null, new Forest[] { body }, creator, false, true); }
26     static <T> Forest<T>   leaf(Token.Location loc, T tag,                     Sequence creator) { return create(loc, tag, null, creator, false, false); }
27     public static <T> Forest<T>   create(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
28         return new MultiForest<T>(loc, tag, tokens, creator, unwrap, singleton);
29     }
30
31     // Body //////////////////////////////////////////////////////////////////////////////
32
33     protected static class Body<T> {
34
35         private final Token.Location    location;
36         private final T                 tag;
37         private final Forest<T>[]       tokens;
38         private final Sequence          creator;
39         private final boolean           unwrap;
40         private final boolean           singleton;
41
42         private Body(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
43             this.location = loc;
44             this.tag = tag;
45             this.tokens = tokens==null ? emptyForestArray : new Forest[tokens.length];
46             if (tokens != null) System.arraycopy(tokens, 0, this.tokens, 0, tokens.length);
47             if (tokens != null) for(int i=0; i<tokens.length; i++) if (tokens[i]==null) throw new Error(i+"");
48             this.creator = creator;
49             this.unwrap = unwrap;
50             this.singleton = singleton;
51         }
52
53         private HashSet<Tree<T>> expand(boolean toss, ArrayList<Tree<T>> toks, int i, HashSet<Tree<T>> h) {
54             if (singleton) {
55                 for(Body<T> b : (IterableForest<T>)tokens[0]) b.expand(toss, toks, i, h);
56
57             } else if (i==tokens.length) {
58                 h.add(new Tree<T>(null, tag, toks.toArray(tree_hint)));
59
60             } else if (unwrap && i==tokens.length-1) {
61                 if (tokens[i] != null)
62                     for(Body b : (IterableForest<T>)tokens[i])
63                         b.expand(toss, toks, 0, h);
64
65             } else {
66                 if (tokens[i]!=null) {
67                     HashSet<Tree<T>> exp = tokens[i].expand(toss);
68                     if (exp != null)
69                         for(Tree<T> r : exp) {
70                             int old = toks.size();
71                             toks.add(r);
72                             expand(toss, toks, i+1, h);
73                             while(toks.size() > old) toks.remove(toks.size()-1);
74                         }
75                 }
76             }
77             return h;
78         }
79         void addTo(HashSet<Body> h) {
80             if (!singleton) h.add(this);
81             else for(Body b : (IterableForest<T>)tokens[0]) b.addTo(h);
82         }
83         void addTo(FastSet<Body> h) {
84             if (!singleton) h.add(this, true);
85             else for(Body b : (IterableForest<T>)tokens[0]) b.addTo(h);
86         }
87
88         private boolean kcache = false;
89         private boolean keep = false;
90         public boolean keep() {
91             return true;
92             /*
93             if (kcache) return keep;
94             kcache = true;
95             for(Forest<T> token : tokens) if (!token.valid()) return keep = false;
96             return keep = creator==null || (creator.needs.size()==0 && creator.hates.size()==0);
97             */
98         }
99         public boolean keep(Iterable<Body<T>> h) {
100             if (keep()) return true;
101             for(Forest<T> token : tokens) if (!token.valid()) return false;
102             int needs = 0;
103             for(Body<T> b : h) {
104                 if (creator.hates.contains(b.creator) && b.keep(h)) return false;
105                 if (creator.needs.contains(b.creator) && b.keep(h)) needs--;
106             }
107             return needs <= -1 * creator.needs.size();
108         }
109
110         private boolean rep = false;
111         public String toString() {
112             if (rep) return "***";
113             try {
114                 rep = true;
115                 StringBuffer ret = new StringBuffer();
116                 for(int i=0; i<tokens.length; i++) {
117                     String q = tokens[i]==null ? "null" : tokens[i].toString();
118                     if (q.length() > 0) {
119                         ret.append(q);
120                         ret.append(" ");
121                     }
122                 }
123                 String tail = ret.toString().trim();
124                 String head = (tag!=null && !tag.toString().equals("")) ? (tail.length() > 0 ? tag+":" : tag+"") : "";
125                 if (tail.length() > 0) tail = "{" + tail + "}";
126                 return head + tail;
127             } finally {
128                 rep = false;
129             }
130         }
131     }
132
133
134     // Ref //////////////////////////////////////////////////////////////////////////////
135
136     static abstract class IterableForest<T> extends Forest<T> implements Iterable<Forest.Body<T>> {
137         public abstract Iterator<Forest.Body<T>> iterator();
138     }
139
140     /**
141      *  This class represents a partially complete collection of
142      *  forests to be viewed as a forest at some later date; once
143      *  viewed, it becomes immutable
144      */
145     static class Ref<T> extends IterableForest<T> {
146         private FastSet<Forest> hp = new FastSet<Forest>();
147         private Forest res = null;
148         public boolean valid = false;
149         public Ref() { }
150         public void merge(Forest p) {
151             //if (p==null) throw new Error("bad evil bad!");
152             if (res != null) throw new Error("already resolved!");
153             if (p==null) throw new Error();
154             if (p!=this) hp.add(p, true);
155         }
156         public Iterator<Body<T>> iterator() { return ((IterableForest<T>)resolve()).iterator(); }
157         public HashSet<Tree<T>> expand(boolean toss) { return resolve().expand(toss); }
158         public boolean valid() { return true; /*if (valid) return true; resolve(); return valid;*/ }
159         public String toString() { return resolve().toString(); }
160         public Forest resolve() {
161             if (hp==null) return res;
162             HashSet<Body> results = null;
163             FastSet<Body> nh      = new FastSet<Body>();
164             for(Forest<?> p : hp)
165                 for(Body<?> b : (IterableForest<?>)p) {
166                     if (b.keep() && (b.creator==null || !b.creator.lame)) {
167                         valid = true;
168                         b.addTo(nh);
169                     } else {
170                         results = new HashSet<Body>();
171                     }
172                 }
173             if (results != null) {
174                 for(Forest<?> p : hp)
175                     for(Body<?> b : (IterableForest<?>)p)
176                         results.add(b);
177                 for(Body b : results) {
178                     if (b.keep() && (b.creator==null || !b.creator.lame)) continue;
179                     if (b.creator!=null && b.creator.lame) continue;
180                     if (!b.keep(results)) continue;
181                     valid = true;
182                     b.addTo(nh);
183                 }
184             }
185             hp = null;
186             res = new MultiForest(nh, valid);
187             return res;
188         }
189     }
190
191     // Implementations //////////////////////////////////////////////////////////////////////////////
192
193     private static class MultiForest<T> extends IterableForest<T> {
194         private final FastSet<Body<T>> results;
195         private boolean valid;
196         public boolean valid() { /*return valid;*/ return true; }
197         private MultiForest(FastSet<Body<T>> results, boolean valid) { this.results = results; this.valid = valid; }
198         public MultiForest(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
199             this.results = new FastSet<Body<T>>(new Body(loc, tag, tokens, creator, unwrap, singleton));
200             this.valid = true;
201         }
202         public Iterator<Body<T>> iterator() { return results.iterator(); }
203
204         public HashSet<Tree<T>> expand(boolean toss) {
205             HashSet<Tree<T>> ret = new HashSet<Tree<T>>();
206             for(Body<T> b : results)
207                 ret.addAll(b.expand(toss, new ArrayList<Tree<T>>(), 0, new HashSet<Tree<T>>()));
208             if (toss && ret.size() > 1) throw new Parser.Ambiguous(this);
209             return ret;
210         }
211         
212         // Display //////////////////////////////////////////////////////////////////////////////
213         
214         private String toString = null;
215         public String toString() {
216             if (toString != null) return toString;
217             StringBuffer ret = new StringBuffer();
218             if (results.size()==1) {
219                 for(Forest.Body<T> r : results)
220                     ret.append(r);
221                 return toString = ret.toString();
222             }
223             ret.append("<?");
224             boolean first = true;
225             for(Forest.Body<T> r : results) {
226                 if (!first) ret.append(' ');
227                 first = false;
228                 ret.append(r);
229             }
230             ret.append("?>");
231             return toString = ret.toString();
232         }
233     }
234
235     // Statics //////////////////////////////////////////////////////////////////////////////
236
237     private static Tree[] tree_hint = new Tree[0];
238     private static Body[] body_hint = new Body[0];
239     private static final Forest[] emptyForestArray = new Forest[0];
240 }