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