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