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