added StringToken
[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     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             this.creator = creator;
48             this.unwrap = unwrap;
49             this.singleton = singleton;
50         }
51
52         private HashSet<Tree<T>> expand(boolean toss, ArrayList<Tree<T>> toks, int i, HashSet<Tree<T>> h) {
53             if (singleton) {
54                 for(Body<T> b : (IterableForest<T>)tokens[0]) b.expand(toss, toks, i, h);
55
56             } else if (i==tokens.length) {
57                 h.add(new Tree<T>(null, tag, toks.toArray(tree_hint)));
58
59             } else if (unwrap && i==tokens.length-1) {
60                 if (tokens[i] != null)
61                     for(Body b : (IterableForest<T>)tokens[i])
62                         b.expand(toss, toks, 0, h);
63
64             } else {
65                 if (tokens[i]!=null) {
66                     HashSet<Tree<T>> exp = tokens[i].expand(toss);
67                     if (exp != null)
68                         for(Tree<T> r : exp) {
69                             int old = toks.size();
70                             toks.add(r);
71                             expand(toss, toks, i+1, h);
72                             while(toks.size() > old) toks.remove(toks.size()-1);
73                         }
74                 }
75             }
76             return h;
77         }
78         void addTo(HashSet<Body> h) {
79             if (!singleton) h.add(this);
80             else for(Body b : (IterableForest<T>)tokens[0]) b.addTo(h);
81         }
82         void addTo(FastSet<Body> h) {
83             if (!singleton) h.add(this, true);
84             else for(Body b : (IterableForest<T>)tokens[0]) b.addTo(h);
85         }
86
87         private boolean kcache = false;
88         private boolean keep = false;
89         public boolean keep() {
90             if (kcache) return keep;
91             kcache = true;
92             for(Forest<T> token : tokens) if (!token.valid()) return keep = false;
93             return keep = creator==null || (creator.needs.size()==0 && creator.hates.size()==0);
94         }
95         public boolean keep(Iterable<Body<T>> h) {
96             if (keep()) return true;
97             for(Forest<T> token : tokens) if (!token.valid()) return false;
98             int needs = 0;
99             for(Body<T> b : h) {
100                 if (creator.hates.contains(b.creator) && b.keep(h)) return false;
101                 if (creator.needs.contains(b.creator) && b.keep(h)) needs--;
102             }
103             return needs <= -1 * creator.needs.size();
104         }
105
106
107         public String toString() {
108             StringBuffer ret = new StringBuffer();
109             for(int i=0; i<tokens.length; i++) {
110                 String q = tokens[i]==null ? "null" : tokens[i].toString();
111                 if (q.length() > 0) {
112                     ret.append(q);
113                     ret.append(" ");
114                 }
115             }
116             String tail = ret.toString().trim();
117             String head = (tag!=null && !tag.toString().equals("")) ? (tail.length() > 0 ? tag+":" : tag+"") : "";
118             if (tail.length() > 0) tail = "{" + tail + "}";
119             return head + tail;
120         }
121     }
122
123
124     // Ref //////////////////////////////////////////////////////////////////////////////
125
126     static abstract class IterableForest<T> extends Forest<T> implements Iterable<Forest.Body<T>> {
127         public abstract Iterator<Forest.Body<T>> iterator();
128     }
129
130     /**
131      *  This class represents a partially complete collection of
132      *  forests to be viewed as a forest at some later date; once
133      *  viewed, it becomes immutable
134      */
135     static class Ref<T> extends IterableForest<T> {
136         private FastSet<Forest> hp = new FastSet<Forest>();
137         private Forest res = null;
138         public boolean valid = false;
139         public Ref() { }
140         public void merge(Forest p) {
141             if (res != null) throw new Error("already resolved!");
142             if (p==null) throw new Error();
143             if (p!=this) hp.add(p);
144         }
145         public Iterator<Body<T>> iterator() { return ((IterableForest<T>)resolve()).iterator(); }
146         public HashSet<Tree<T>> expand(boolean toss) { return resolve().expand(toss); }
147         public boolean valid() { resolve(); return valid; }
148         public String toString() { return resolve().toString(); }
149         public Forest resolve() {
150             if (hp==null) return res;
151             HashSet<Body> results = null;
152             FastSet<Body> nh      = new FastSet<Body>();
153             for(Forest<?> p : hp)
154                 for(Body<?> b : (IterableForest<?>)p) {
155                     if (b.keep() && (b.creator==null || !b.creator.lame)) { valid = true; b.addTo(nh); }
156                     else results = new HashSet<Body>();
157                 }
158             if (results != null) {
159                 for(Forest<?> p : hp) for(Body<?> b : (IterableForest<?>)p) results.add(b);
160                 for(Body b : results) {
161                     if (b.keep() && (b.creator==null || !b.creator.lame)) continue;
162                     if (!b.keep(results)) continue;
163                     if (b.creator!=null && b.creator.lame) continue;
164                     valid = true;
165                     b.addTo(nh);
166                 }
167             }
168             hp = null;
169             return res = new MultiForest(nh, valid);
170         }
171     }
172
173     // Implementations //////////////////////////////////////////////////////////////////////////////
174
175     private static class MultiForest<T> extends IterableForest<T> {
176         private final FastSet<Body<T>> results;
177         private boolean valid;
178         public boolean valid() { return valid; }
179         private MultiForest(FastSet<Body<T>> results, boolean valid) { this.results = results; this.valid = valid; }
180         public MultiForest(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
181             this.results = new FastSet<Body<T>>(new Body(loc, tag, tokens, creator, unwrap, singleton));
182             this.valid = true;
183         }
184         public Iterator<Body<T>> iterator() { return results.iterator(); }
185
186         public HashSet<Tree<T>> expand(boolean toss) {
187             HashSet<Tree<T>> ret = new HashSet<Tree<T>>();
188             for(Body<T> b : results)
189                 ret.addAll(b.expand(toss, new ArrayList<Tree<T>>(), 0, new HashSet<Tree<T>>()));
190             if (toss && ret.size() > 1) throw new Parser.Ambiguous(this);
191             return ret;
192         }
193         
194         // Display //////////////////////////////////////////////////////////////////////////////
195         
196         private String toString = null;
197         public String toString() {
198             if (toString != null) return toString;
199             StringBuffer ret = new StringBuffer();
200             ret.append("<?");
201             boolean first = true;
202             for(Forest.Body<T> r : results) {
203                 if (!first) ret.append(' ');
204                 first = false;
205                 ret.append(r);
206             }
207             ret.append("?>");
208             return toString = ret.toString();
209         }
210     }
211
212     // Statics //////////////////////////////////////////////////////////////////////////////
213
214     private static Tree[] tree_hint = new Tree[0];
215     private static Body[] body_hint = new Body[0];
216     private static final Forest[] emptyForestArray = new Forest[0];
217 }