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 = StringUtil.escapify(headToString()==null?"":headToString(), "\r\n");
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 boolean ambiguous() {
163             if (hp.size()==0) return false;
164             if (hp.size()==1) return hp.iterator().next().ambiguous();
165             return true;
166         }
167         private FastSet<Forest<T>> hp = new FastSet<Forest<T>>();
168         public Ref() { }
169         public int toInt() {
170             if (hp.size()==1) return hp.iterator().next().toInt();
171             return super.toInt();
172         }
173         public void merge(Forest p) { if (p!=this) hp.add(p, true); }
174
175         public boolean isTransparent() { return hp.size()==1; }
176         public boolean isHidden() { return hp.size()==0; }
177         public void edges(GraphViz.Node n) {
178             if (hp.size()==1) { hp.iterator().next().edges(n); return; }
179             for(Forest f : hp) f.edges(n);
180         }
181         public GraphViz.Node toGraphViz(GraphViz gv) {
182             //if (hp.size()==0) return null;
183             if (hp.size()==1) return hp.iterator().next().toGraphViz(gv);
184             if (gv.hasNode(this)) return gv.createNode(this);
185             GraphViz.Node n = gv.createNode(this);
186             n.label = "?";
187             n.color = "red";
188             for(Forest f : hp) n.edge(f, null);
189             return n;
190         }
191
192         public <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c) {
193             if (hp==null) return;
194             for(Forest<T> f : hp)
195                 f.visit(ivbc, b, c);
196         }
197         public Forest resolve() { return this; }
198     }
199
200     public abstract <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c);
201     private static class TreeMaker2<T> extends TreeMaker<T> {
202         private TreeConsumer<T> tc;
203         public TreeMaker2(boolean toss, TreeConsumer<T> tc) { super(toss); this.tc = tc; }
204         public void finish(T head, Input.Location loc) { tc.addTree(new Tree<T>(loc, head, toks.toArray(tree_hint), labs.toArray(string_hint)));; }
205         public void start(T head, Input.Location loc) { }
206         public void addTree(Tree<T> t, Object label) { toks.add(t); labs.add(label); }
207     }
208     private static abstract class TreeMaker<T> implements Invokable<Forest.Body<T>,Boolean,Integer>/*, TreeConsumer<T>*/ {
209         public ArrayList<Tree<T>> toks = new ArrayList<Tree<T>>();
210         public ArrayList<Object>  labs = new ArrayList<Object>();
211         private boolean toss;
212         protected T head;
213         public TreeMaker(boolean toss) { this.toss = toss; }
214         public abstract void start(T head, Input.Location loc);
215         public abstract void finish(T head, Input.Location loc);
216         public abstract void addTree(Tree<T> t, Object label);
217         public void invoke(Forest.Body<T> bod, Boolean o, Integer i) {
218             if (i==null) {
219                 ArrayList<Tree<T>> toks = this.toks;
220                 this.toks = new ArrayList<Tree<T>>();
221                 ArrayList<Object> labs = this.labs;
222                 this.labs = new ArrayList<Object>();
223                 bod.expand(0, this);
224                 this.toks = toks;
225                 this.labs = labs;
226             } else {
227                 bod.expand(i, this);
228             }
229         }
230     }
231
232     // Statics //////////////////////////////////////////////////////////////////////////////
233
234     private static Tree[] tree_hint = new Tree[0];
235     private static String[] string_hint = new String[0];
236     private static final Forest[] emptyForestArray = new Forest[0];
237
238     protected String  headToString()    { return null; }
239     protected String  headToJava()      { return null; }
240     protected String  left()            { return "<?"; }
241     protected String  right()           { return "?>"; }
242     protected boolean ignoreSingleton() { return true; }
243 }