intermediate checkpoint
[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     public abstract boolean empty();
22
23     static <T> Forest<T>   singleton(Token.Location loc, Sequence creator)                       { return create(loc, null, new Forest[] { }, creator, false, true); }
24     static <T> Forest<T>   singleton(Token.Location loc, Forest<T> body, Sequence creator)       { return create(loc, null, new Forest[] { body }, creator, false, true); }
25     static <T> Forest<T>   leaf(Token.Location loc, T tag,                     Sequence creator) { return create(loc, tag, null, creator, false, false); }
26     public static <T> Forest<T>   create(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
27         return new MultiForest<T>(loc, tag, tokens, creator, unwrap, singleton);
28     }
29
30     // Body //////////////////////////////////////////////////////////////////////////////
31
32     protected static class Body<T> {
33
34         private final Token.Location    location;
35         private final T                 tag;
36         private final Forest<T>[]       tokens;
37         private final Sequence          creator;
38         private final boolean           unwrap;
39         private final boolean           singleton;
40
41         private Body(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
42             this.location = loc;
43             this.tag = tag;
44             this.tokens = tokens==null ? emptyForestArray : new Forest[tokens.length];
45             if (tokens != null) System.arraycopy(tokens, 0, this.tokens, 0, tokens.length);
46             if (tokens != null) for(int i=0; i<tokens.length; i++) if (tokens[i]==null) throw new Error(i+"");
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                 boolean hit = false;
66                 for(Tree<T> r : tokens[i].expand(toss)) {
67                     hit = true;
68                     int old = toks.size();
69                     toks.add(r);
70                     expand(toss, toks, i+1, h);
71                     while(toks.size() > old) toks.remove(toks.size()-1);
72                 }
73                 //if (!hit) throw new Error();
74             }
75             return h;
76         }
77         void addTo(HashSet<Body> h) {
78             if (!singleton) h.add(this);
79             else for(Body b : (IterableForest<T>)tokens[0]) b.addTo(h);
80         }
81         void addTo(FastSet<Body> h) {
82             if (!singleton) h.add(this, true);
83             else for(Body b : (IterableForest<T>)tokens[0]) b.addTo(h);
84         }
85
86
87         private boolean rep = false;
88         public String toString() {
89             if (rep) return "***";
90             try {
91                 rep = true;
92                 StringBuffer ret = new StringBuffer();
93                 for(int i=0; i<tokens.length; i++) {
94                     String q = tokens[i]==null ? "null" : tokens[i].toString();
95                     if (q.length() > 0) {
96                         ret.append(q);
97                         ret.append(" ");
98                     }
99                 }
100                 String tail = ret.toString().trim();
101                 String head = (tag!=null && !tag.toString().equals("")) ? (tail.length() > 0 ? tag+":" : tag+"") : "";
102                 if (tail.length() > 0) tail = "{" + tail + "}";
103                 return head + tail;
104             } finally {
105                 rep = false;
106             }
107         }
108     }
109
110
111     // Ref //////////////////////////////////////////////////////////////////////////////
112
113     static abstract class IterableForest<T> extends Forest<T> implements Iterable<Forest.Body<T>> {
114         public abstract Iterator<Forest.Body<T>> iterator();
115     }
116
117     /**
118      *  This class represents a partially complete collection of
119      *  forests to be viewed as a forest at some later date; once
120      *  viewed, it becomes immutable
121      */
122     static class Ref<T> extends IterableForest<T> {
123         public boolean empty() {
124             if (res!=null) return res.empty();
125             for(Forest f : hp) if (!f.empty()) return false;
126             return true;
127         }
128         private FastSet<Forest> hp = new FastSet<Forest>();
129         private Forest res = null;
130         public Ref() { }
131         public void merge(Forest p) {
132             if (res != null) throw new Error("already resolved!");
133             if (p==null) throw new Error();
134             if (p!=this) hp.add(p, true);
135         }
136         public Iterator<Body<T>> iterator() { return ((IterableForest<T>)resolve()).iterator(); }
137         public HashSet<Tree<T>> expand(boolean toss) { return resolve().expand(toss); }
138         public String toString() { return resolve().toString(); }
139         public Forest resolve() {
140             if (hp==null) return res;
141             FastSet<Body> nh      = new FastSet<Body>();
142             for(Forest<?> p : hp)
143                 for(Body<?> b : (IterableForest<?>)p)
144                     b.addTo(nh);
145             res = new MultiForest(nh);
146             hp = null;
147             return res;
148         }
149     }
150
151     // Implementations //////////////////////////////////////////////////////////////////////////////
152
153     private static class MultiForest<T> extends IterableForest<T> {
154         public boolean empty() { return results.size()>0; }
155         private final FastSet<Body<T>> results;
156         private MultiForest(FastSet<Body<T>> results) { this.results = results; }
157         public MultiForest(Token.Location loc, T tag, Forest<T>[] tokens, Sequence creator, boolean unwrap, boolean singleton) {
158             this.results = new FastSet<Body<T>>(new Body(loc, tag, tokens, creator, unwrap, singleton));
159         }
160         public Iterator<Body<T>> iterator() { return results.iterator(); }
161
162         public HashSet<Tree<T>> expand(boolean toss) {
163             HashSet<Tree<T>> ret = new HashSet<Tree<T>>();
164             for(Body<T> b : results)
165                 ret.addAll(b.expand(toss, new ArrayList<Tree<T>>(), 0, new HashSet<Tree<T>>()));
166             if (toss && ret.size() > 1) throw new Parser.Ambiguous(this);
167             return ret;
168         }
169         
170         // Display //////////////////////////////////////////////////////////////////////////////
171         
172         private String toString = null;
173         public String toString() {
174             if (toString != null) return toString;
175             StringBuffer ret = new StringBuffer();
176             if (results.size()==1) {
177                 for(Forest.Body<T> r : results)
178                     ret.append(r);
179                 return toString = ret.toString();
180             }
181             ret.append("<?");
182             boolean first = true;
183             for(Forest.Body<T> r : results) {
184                 if (!first) ret.append(' ');
185                 first = false;
186                 ret.append(r);
187             }
188             ret.append("?>");
189             return toString = ret.toString();
190         }
191     }
192
193     // Statics //////////////////////////////////////////////////////////////////////////////
194
195     private static Tree[] tree_hint = new Tree[0];
196     private static Body[] body_hint = new Body[0];
197     private static final Forest[] emptyForestArray = new Forest[0];
198 }