it all 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             if (kcache) return keep;
92             kcache = true;
93             for(Forest<T> token : tokens) if (!token.valid()) return keep = false;
94             return keep = creator==null || (creator.needs.size()==0 && creator.hates.size()==0);
95         }
96         public boolean keep(Iterable<Body<T>> h) {
97             if (keep()) return true;
98             for(Forest<T> token : tokens) if (!token.valid()) return false;
99             int needs = 0;
100             for(Body<T> b : h) {
101                 if (creator.hates.contains(b.creator) && b.keep(h)) return false;
102                 if (creator.needs.contains(b.creator) && b.keep(h)) needs--;
103             }
104             return needs <= -1 * creator.needs.size();
105         }
106
107         private boolean rep = false;
108         public String toString() {
109             if (rep) return "***";
110             try {
111                 rep = true;
112                 StringBuffer ret = new StringBuffer();
113                 for(int i=0; i<tokens.length; i++) {
114                     String q = tokens[i]==null ? "null" : tokens[i].toString();
115                     if (q.length() > 0) {
116                         ret.append(q);
117                         ret.append(" ");
118                     }
119                 }
120                 String tail = ret.toString().trim();
121                 String head = (tag!=null && !tag.toString().equals("")) ? (tail.length() > 0 ? tag+":" : tag+"") : "";
122                 if (tail.length() > 0) tail = "{" + tail + "}";
123                 return head + tail;
124             } finally {
125                 rep = false;
126             }
127         }
128     }
129
130
131     // Ref //////////////////////////////////////////////////////////////////////////////
132
133     static abstract class IterableForest<T> extends Forest<T> implements Iterable<Forest.Body<T>> {
134         public abstract Iterator<Forest.Body<T>> iterator();
135     }
136
137     /**
138      *  This class represents a partially complete collection of
139      *  forests to be viewed as a forest at some later date; once
140      *  viewed, it becomes immutable
141      */
142     static class Ref<T> extends IterableForest<T> {
143         private FastSet<Forest> hp = new FastSet<Forest>();
144         private Forest res = null;
145         public boolean valid = false;
146         public Ref() { }
147         public void merge(Forest p) {
148             //if (p==null) throw new Error("bad evil bad!");
149             if (res != null) throw new Error("already resolved!");
150             if (p==null) throw new Error();
151             if (p!=this) hp.add(p, true);
152         }
153         public Iterator<Body<T>> iterator() { return ((IterableForest<T>)resolve()).iterator(); }
154         public HashSet<Tree<T>> expand(boolean toss) { return resolve().expand(toss); }
155         public boolean valid() { if (valid) return true; resolve(); return valid; }
156         public String toString() { return resolve().toString(); }
157         public Forest resolve() {
158             if (hp==null) return res;
159             HashSet<Body> results = null;
160             FastSet<Body> nh      = new FastSet<Body>();
161             for(Forest<?> p : hp)
162                 for(Body<?> b : (IterableForest<?>)p) {
163                     if (b.keep() && (b.creator==null || !b.creator.lame)) {
164                         valid = true;
165                         b.addTo(nh);
166                     } else {
167                         results = new HashSet<Body>();
168                     }
169                 }
170             if (results != null) {
171                 for(Forest<?> p : hp)
172                     for(Body<?> b : (IterableForest<?>)p)
173                         results.add(b);
174                 for(Body b : results) {
175                     if (b.keep() && (b.creator==null || !b.creator.lame)) continue;
176                     if (b.creator!=null && b.creator.lame) continue;
177                     if (!b.keep(results)) continue;
178                     valid = true;
179                     b.addTo(nh);
180                 }
181             }
182             hp = null;
183             res = new MultiForest(nh, valid);
184             return res;
185         }
186     }
187
188     // Implementations //////////////////////////////////////////////////////////////////////////////
189
190     private static class MultiForest<T> extends IterableForest<T> {
191         private final FastSet<Body<T>> results;
192         private boolean valid;
193         public boolean valid() { return valid; }
194         private MultiForest(FastSet<Body<T>> results, boolean valid) { this.results = results; this.valid = valid; }
195         public MultiForest(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
196             this.results = new FastSet<Body<T>>(new Body(loc, tag, tokens, creator, unwrap, singleton));
197             this.valid = true;
198         }
199         public Iterator<Body<T>> iterator() { return results.iterator(); }
200
201         public HashSet<Tree<T>> expand(boolean toss) {
202             HashSet<Tree<T>> ret = new HashSet<Tree<T>>();
203             for(Body<T> b : results)
204                 ret.addAll(b.expand(toss, new ArrayList<Tree<T>>(), 0, new HashSet<Tree<T>>()));
205             if (toss && ret.size() > 1) throw new Parser.Ambiguous(this);
206             return ret;
207         }
208         
209         // Display //////////////////////////////////////////////////////////////////////////////
210         
211         private String toString = null;
212         public String toString() {
213             if (toString != null) return toString;
214             StringBuffer ret = new StringBuffer();
215             if (results.size()==1) {
216                 for(Forest.Body<T> r : results)
217                     ret.append(r);
218                 return toString = ret.toString();
219             }
220             ret.append("<?");
221             boolean first = true;
222             for(Forest.Body<T> r : results) {
223                 if (!first) ret.append(' ');
224                 first = false;
225                 ret.append(r);
226             }
227             ret.append("?>");
228             return toString = ret.toString();
229         }
230     }
231
232     // Statics //////////////////////////////////////////////////////////////////////////////
233
234     private static Tree[] tree_hint = new Tree[0];
235     private static Body[] body_hint = new Body[0];
236     private static final Forest[] emptyForestArray = new Forest[0];
237 }