fixed the ugly comma bug; still unsure of the ultimate solution
[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 {
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         //if (toss) scan();
28         final HashSetTreeConsumer<T> ret = new HashSetTreeConsumer<T>();
29         visit(new TreeMaker2<T>(toss, ret), null, null);
30         if (toss && ret.size() > 1) throw new InnerAmbiguous(this);
31         return ret;
32     }
33
34     private static class InnerAmbiguous extends RuntimeException {
35         public final Forest<?> f;
36         public InnerAmbiguous(Forest<?> f) { this.f = f; }
37     }
38
39     public static interface TreeConsumer<T> {
40         public void addTree(Tree<T> t);
41     }
42     public static class HashSetTreeConsumer<T> extends HashSet<Tree<T>> implements TreeConsumer<T> {
43         public void addTree(Tree<T> t) { super.add(t); }
44     }
45
46     static        <T> Forest<T> singleton(Input.Location loc, Position p) {
47         return create(loc, null, new Forest[] { }, false, true, p); }
48     static        <T> Forest<T> singleton(Input.Location loc, Forest<T> body, Position p) {
49         return create(loc, null, new Forest[] { body },  false, true, p); }
50     static        <T> Forest<T> leaf(Input.Location loc, T tag, Position p) { return create(loc, tag, null, false, false, p); }
51
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
56     // Body //////////////////////////////////////////////////////////////////////////////
57
58     protected static interface Body<T> {
59         void expand(int i, TreeMaker<T> h);
60     }
61
62     protected static class MyBody<T> extends Forest<T> implements Body<T> /* extends PrintableTree<Forest<T>> implements */ {
63
64         public <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c) {
65             ivbc.invoke(this, b, c);
66         }
67
68         private final Input.Location    location;
69         private final T                 tag;
70         private final Forest<T>[]       tokens;
71         private final boolean           unwrap;
72         private final boolean           singleton;
73         private final Sequence.Position reduction;
74
75         private MyBody(Input.Location loc, T tag, Forest<T>[] tokens, boolean unwrap, boolean singleton, Position reduction) {
76             this.location = loc;
77             this.tag = tag;
78             this.tokens = tokens==null ? emptyForestArray : new Forest[tokens.length];
79             if (tokens != null) System.arraycopy(tokens, 0, this.tokens, 0, tokens.length);
80             if (tokens != null) for(int i=0; i<tokens.length; i++) if (tokens[i]==null) throw new Error(i+"");
81             this.unwrap = unwrap;
82             this.singleton = singleton;
83             this.reduction = reduction;
84         }
85
86         public void expand(final int i, final TreeMaker<T> h) {
87             if (singleton) {
88                 tokens[0].visit(h, null, i);
89                 return;
90             }
91             if (i==0) h.start(tag, location);
92
93             if (i==tokens.length) {
94                 h.finish(tag, location);
95
96             } else if (unwrap && i==tokens.length-1) {
97                 if (tokens[i] != null)
98                     tokens[i].visit(h, null, 0);
99
100             } else {
101                 tokens[i].visit(new TreeMaker<T>(h.toss) {
102                     public void start(T head, Input.Location loc) { }
103                     public void addTree(Tree<T> t) { toks.add(t); }
104                     public void finish(T head, Input.Location loc) {
105                         int old = h.toks.size();
106                         h.addTree(new Tree<T>(loc, head, toks.toArray(tree_hint)));
107                         expand(i+1, h);
108                         while(h.toks.size() > old) h.toks.remove(h.toks.size()-1);
109                     }
110                 }, null, null);
111             }
112         }
113
114         protected String  headToString()         { return null; }
115         protected String  headToJava()           { return null; }
116         protected String  left()                 { return "{"; }
117         protected String  right()                { return "}"; }
118         protected boolean ignoreSingleton()      { return false; }
119     }
120
121
122     // Ref //////////////////////////////////////////////////////////////////////////////
123
124     /**
125      *  This class represents a partially complete collection of
126      *  forests to be viewed as a forest at some later date; once
127      *  viewed, it becomes immutable
128      */
129     static class Ref<T> extends Forest<T> {
130         private FastSet<Forest<T>> hp = new FastSet<Forest<T>>();
131         public Ref() { }
132         public int toInt() {
133             if (hp.size()==1) return hp.iterator().next().toInt();
134             return super.toInt();
135         }
136         public void merge(Forest p) { if (p!=this) hp.add(p, true); }
137         public <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c) {
138             if (hp==null) return;
139             for(Forest<T> f : hp)
140                 f.visit(ivbc, b, c);
141         }
142         public Forest resolve() { return this; }
143     }
144
145     public abstract <B,C> void visit(Invokable<Forest.Body<T>,B,C> ivbc, B b, C c);
146     private static class TreeMaker2<T> extends TreeMaker<T> {
147         private TreeConsumer<T> tc;
148         public TreeMaker2(boolean toss, TreeConsumer<T> tc) { super(toss); this.tc = tc; }
149         public void finish(T head, Input.Location loc) { tc.addTree(new Tree<T>(loc, head, toks.toArray(tree_hint)));; }
150         public void start(T head, Input.Location loc) { }
151         public void addTree(Tree<T> t) { toks.add(t); }
152     }
153     private static abstract class TreeMaker<T> implements Invokable<Forest.Body<T>,Boolean,Integer>, TreeConsumer<T> {
154         public ArrayList<Tree<T>> toks = new ArrayList<Tree<T>>();
155         private boolean toss;
156         protected T head;
157         public TreeMaker(boolean toss) { this.toss = toss; }
158         public abstract void start(T head, Input.Location loc);
159         public abstract void finish(T head, Input.Location loc);
160         public abstract void addTree(Tree<T> t);
161         public void invoke(Forest.Body<T> bod, Boolean o, Integer i) {
162             if (i==null) {
163                 ArrayList<Tree<T>> toks = this.toks;
164                 this.toks = new ArrayList<Tree<T>>();
165                 bod.expand(0, this);
166                 this.toks = toks;
167             } else {
168                 bod.expand(i, this);
169             }
170         }
171     }
172
173     // Statics //////////////////////////////////////////////////////////////////////////////
174
175     private static Tree[] tree_hint = new Tree[0];
176     private static final Forest[] emptyForestArray = new Forest[0];
177
178     protected String  headToString()    { return null; }
179     protected String  headToJava()      { return null; }
180     protected String  left()            { return "<?"; }
181     protected String  right()           { return "?>"; }
182     protected boolean ignoreSingleton() { return true; }
183 }