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