tentative checkpoint
[sbp.git] / src / edu / berkeley / sbp / Forest.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.Sequence.Position;
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> /*extends PrintableTree<Forest.MyBody<T>>*/
11     implements Visitable<Forest.Body<T>>,
12                IntegerMappable,
13                GraphViz.ToGraphViz {
14
15     private static int master_idx = 0;
16     private final int idx = master_idx++;
17     public int toInt() { return idx; }
18
19     /** assume that this forest contains exactly one tree and return it; otherwise throw an exception */
20     public final Tree<T> expand1() throws Ambiguous, ParseFailed {
21         try {
22             Iterator<Tree<T>> it = expand(true).iterator();
23             if (!it.hasNext()) throw new ParseFailed();
24             return it.next();
25         } catch (InnerAmbiguous ia) { throw new Ambiguous(ia.f); }
26     }
27
28     /** expand this forest into a set of trees */
29     public HashSet<Tree<T>> expand(boolean toss) {
30         final HashSetTreeConsumer<T> ret = new HashSetTreeConsumer<T>();
31         visit(new TreeMaker2<T>(toss, ret), null, null);
32         if (toss && ret.size() > 1) throw new InnerAmbiguous(this);
33         return ret;
34     }
35
36     private static class InnerAmbiguous extends RuntimeException {
37         public final Forest<?> f;
38         public InnerAmbiguous(Forest<?> f) { this.f = f; }
39     }
40
41     static interface TreeConsumer<T> {
42         public void addTree(Tree<T> t);
43     }
44     static class HashSetTreeConsumer<T> extends HashSet<Tree<T>> implements TreeConsumer<T> {
45         public void addTree(Tree<T> t) {
46             super.add(t);
47         }
48     }
49
50     static        <T> Forest<T> singleton(Input.Location loc, Position p) {
51         return create(loc, null, new Forest[] { }, new Object[0], false, true, p); }
52     static        <T> Forest<T> singleton(Input.Location loc, Forest<T> body, Position p) {
53         //return create(loc, null, new Forest[] { body },  false, true, p);
54         return body;
55     }
56     static        <T> Forest<T> leaf(Input.Location loc, T tag, Position p) { return create(loc, tag, null, null, false, false, p); }
57     public static <T> Forest<T> create(Input.Location loc, T tag, Forest<T>[] tokens, Object[] labels, boolean unwrap, boolean singleton, Position p) {
58         return new MyBody<T>(loc, tag, tokens, labels, unwrap, singleton, p);
59     }
60     // Body //////////////////////////////////////////////////////////////////////////////
61
62     protected static interface Body<T> extends GraphViz.ToGraphViz {
63         void expand(int i, TreeMaker<T> h);
64     }
65     public abstract void edges(GraphViz.Node n);
66     public boolean ambiguous() { return false; }
67     protected static class MyBody<T> extends Forest<T> implements Body<T> /* extends PrintableTree<Forest<T>> implements */ {
68
69         public boolean isTransparent() { return false; }
70         public boolean isHidden() { return false; }
71         public GraphViz.Node toGraphViz(GraphViz gv) {
72             if (gv.hasNode(this)) return gv.createNode(this);
73             GraphViz.Node n = gv.createNode(this);
74             n.label = headToString()==null?"":headToString();
75             n.directed = true;
76             n.comment = reduction==null?null:reduction+"";
77             edges(n);
78             return n;
79         }
80         boolean edges = false;
81         public void edges(GraphViz.Node n) {
82             if (edges) return;
83             edges = true;
84             for(int i=0; i<tokens.length; i++) {
85                 if (i==tokens.length-1 && unwrap && !tokens[i].ambiguous()) {
86                     tokens[i].edges(n);
87                 } else {
88                     n.edge(tokens[i], labels==null?null:labels[i]);
89                 }
90             }
91         }
92
93         public <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c) {
94             ivbc.invoke(this, b, c);
95         }
96
97         private final Input.Location    location;
98         private final T                 tag;
99         private final Forest<T>[]       tokens;
100         private final Object[]          labels;
101         private final boolean           unwrap;
102         private final boolean           singleton;
103         private final Sequence.Position reduction;
104
105         private MyBody(Input.Location loc, T tag, Forest<T>[] tokens, Object[] labels, boolean unwrap, boolean singleton, Position reduction) {
106             this.location = loc;
107             this.tag = tag;
108             this.tokens = tokens==null ? emptyForestArray : new Forest[tokens.length];
109             if (tokens != null) System.arraycopy(tokens, 0, this.tokens, 0, tokens.length);
110             if (tokens != null) for(int i=0; i<tokens.length; i++) if (tokens[i]==null) throw new Error(i+"");
111             this.unwrap = unwrap;
112             this.singleton = singleton;
113             this.reduction = reduction;
114             this.labels = labels;
115         }
116
117         public void expand(final int i, final TreeMaker<T> h) {
118             if (singleton) {
119                 tokens[0].visit(h, null, i);
120                 return;
121             }
122             if (i==0) h.start(tag, location);
123
124             if (i==tokens.length) {
125                 h.finish(tag, location);
126
127             } else if (unwrap && i==tokens.length-1) {
128                 if (tokens[i] != null)
129                     tokens[i].visit(h, null, 0);
130
131             } else {
132                 tokens[i].visit(new TreeMaker<T>(h.toss) {
133                     public void start(T head, Input.Location loc) { }
134                     public void addTree(Tree<T> t, Object label) { toks.add(t); labs.add(label); }
135                     public void finish(T head, Input.Location loc) {
136                         int old = h.toks.size();
137                         h.addTree(new Tree<T>(loc, head, toks.toArray(tree_hint), labs.toArray(string_hint)), labels==null?null:labels[i]);
138                         expand(i+1, h);
139                         while(h.toks.size() > old) h.toks.remove(h.toks.size()-1);
140                         while(h.labs.size() > old) h.labs.remove(h.labs.size()-1);
141                     }
142                 }, null, null);
143             }
144         }
145
146         protected String  headToString()         { return tag==null?null:tag.toString(); }
147         protected String  headToJava()           { return null; }
148         protected String  left()                 { return "{"; }
149         protected String  right()                { return "}"; }
150         protected boolean ignoreSingleton()      { return false; }
151     }
152
153
154     // Ref //////////////////////////////////////////////////////////////////////////////
155
156     /**
157      *  This class represents a partially complete collection of
158      *  forests to be viewed as a forest at some later date; once
159      *  viewed, it becomes immutable
160      */
161     static class Ref<T> extends Forest<T> {
162         public HashSet<GSS.Phase.Node> parents = new HashSet<GSS.Phase.Node>();
163         public boolean contains(Forest f) {
164             return hp.contains(f);
165         }
166         public boolean ambiguous() {
167             if (hp.size()==0) return false;
168             if (hp.size()==1) return hp.iterator().next().ambiguous();
169             return true;
170         }
171         private FastSet<Forest<T>> hp = new FastSet<Forest<T>>();
172         public Ref() { }
173         public int toInt() {
174             if (hp.size()==1) return hp.iterator().next().toInt();
175             return super.toInt();
176         }
177         public void merge(Forest p) { if (p!=this) hp.add(p, true); }
178
179         public boolean isTransparent() { return hp.size()==1; }
180         public boolean isHidden() { return hp.size()==0; }
181         public void edges(GraphViz.Node n) {
182             if (hp.size()==1) { hp.iterator().next().edges(n); return; }
183             for(Forest f : hp) f.edges(n);
184         }
185         public GraphViz.Node toGraphViz(GraphViz gv) {
186             //if (hp.size()==0) return null;
187             if (hp.size()==1) return hp.iterator().next().toGraphViz(gv);
188             if (gv.hasNode(this)) return gv.createNode(this);
189             GraphViz.Node n = gv.createNode(this);
190             n.label = "?";
191             n.color = "red";
192             for(Forest f : hp) n.edge(f, null);
193             return n;
194         }
195
196         public <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c) {
197             if (hp==null) return;
198             for(Forest<T> f : hp)
199                 f.visit(ivbc, b, c);
200         }
201         public Forest resolve() { return this; }
202     }
203
204     public abstract <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c);
205     private static class TreeMaker2<T> extends TreeMaker<T> {
206         private TreeConsumer<T> tc;
207         public TreeMaker2(boolean toss, TreeConsumer<T> tc) { super(toss); this.tc = tc; }
208         public void finish(T head, Input.Location loc) { tc.addTree(new Tree<T>(loc, head, toks.toArray(tree_hint), labs.toArray(string_hint)));; }
209         public void start(T head, Input.Location loc) { }
210         public void addTree(Tree<T> t, Object label) { toks.add(t); labs.add(label); }
211     }
212     private static abstract class TreeMaker<T> implements Invokable<Forest.Body<T>,Boolean,Integer>/*, TreeConsumer<T>*/ {
213         public ArrayList<Tree<T>> toks = new ArrayList<Tree<T>>();
214         public ArrayList<Object>  labs = new ArrayList<Object>();
215         private boolean toss;
216         protected T head;
217         public TreeMaker(boolean toss) { this.toss = toss; }
218         public abstract void start(T head, Input.Location loc);
219         public abstract void finish(T head, Input.Location loc);
220         public abstract void addTree(Tree<T> t, Object label);
221         public void invoke(Forest.Body<T> bod, Boolean o, Integer i) {
222             if (i==null) {
223                 ArrayList<Tree<T>> toks = this.toks;
224                 this.toks = new ArrayList<Tree<T>>();
225                 ArrayList<Object> labs = this.labs;
226                 this.labs = new ArrayList<Object>();
227                 bod.expand(0, this);
228                 this.toks = toks;
229                 this.labs = labs;
230             } else {
231                 bod.expand(i, this);
232             }
233         }
234     }
235
236     // Statics //////////////////////////////////////////////////////////////////////////////
237
238     private static Tree[] tree_hint = new Tree[0];
239     private static String[] string_hint = new String[0];
240     private static final Forest[] emptyForestArray = new Forest[0];
241
242     protected String  headToString()    { return null; }
243     protected String  headToJava()      { return null; }
244     protected String  left()            { return "<?"; }
245     protected String  right()           { return "?>"; }
246     protected boolean ignoreSingleton() { return true; }
247 }