added tracking of position to Forest nodes
[sbp.git] / src / edu / berkeley / sbp / Sequence.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.*;
5 import java.io.*;
6 import java.util.*;
7 import java.lang.reflect.*;
8 import java.lang.ref.*;
9
10 /** juxtaposition; zero or more adjacent Elements; can specify a rewriting */
11 public abstract class Sequence extends Element implements Iterable<Element> {
12
13     // Static Constructors //////////////////////////////////////////////////////////////////////////////
14
15     abstract Sequence _clone();
16     Sequence dup() {
17         Sequence ret = _clone();
18         for(Sequence s : needs) { ret.needs.add(s); s.needed.add(ret); }
19         for(Sequence s : hates) { ret.hates.add(s); s.hated.add(ret); }
20         ret.noFollow = noFollow;
21         return ret;
22     }
23
24     /** the empty sequence (matches the empty string) */
25     public static final Sequence empty = new Sequence.Constant.Empty();
26
27     /** after matching the sequence, do not add anything to the output tree */
28     public static Sequence drop(Element[] e, boolean lame) { return new Constant.Drop(e, lame); }
29
30     /** after matching the sequence, insert a constant into the output tree */
31     public static Sequence constant(Element[] e, Object o) { return new Constant(e, o); }
32
33     /** after matching the sequence, place the result of the <tt>idx</tt>th match in the output tree */
34     public static Sequence singleton(Element[] e, int idx) { return new Singleton(e, idx); }
35
36     /**
37      *  after matching the sequence, create the specified output tree
38      *  @param tag   the tag for the output tree
39      *  @param e     the elements to match
40      *  @param drops only elements of <tt>e</tt> whose corresponding <tt>boolean</tt> in <tt>drops</tt> is <i>false</i> will be included in the output tree
41      **/
42     public static Sequence rewritingSequence(Object tag, Element[] e, boolean[] drops) { return new RewritingSequence(tag, e, drops); }
43
44     ////////////////////////////////////////////////////////////////////////////////
45
46     public Element noFollow = null;
47     public final Topology noFollow() { return noFollow==null ? null : Atom.toAtom(noFollow); }
48
49     Topology toAtom() {
50         if (elements.length!=1) throw new RuntimeException("cannot invoke toAtom() on a Sequence with " + elements.length + " elements: " + this);
51         return Atom.toAtom(elements[0]);
52     }
53
54     public Sequence and(Sequence s) { Sequence ret = dup(); ret.needs.add(s); s.needed.add(ret); return ret; }
55     public Sequence not(Sequence s) { Sequence ret = dup(); ret.hates.add(s); s.hated.add(ret); return ret; }
56
57     protected final Element[] elements;
58
59     final HashSet<Sequence> needed = new HashSet<Sequence>();
60     final HashSet<Sequence> hated = new HashSet<Sequence>();
61     final HashSet<Sequence> needs = new HashSet<Sequence>();
62     final HashSet<Sequence> hates = new HashSet<Sequence>();
63     public boolean           lame  = false;
64
65     final Position          firstp;
66     Position firstp() { return firstp; }
67
68     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
69     protected Sequence(Element[] elements) {
70         this.elements = elements;
71         this.firstp = new Position(0);
72     }
73
74     // DO NOT MESS WITH THE FOLLOWING LINE!!!
75     private Forest.Ref epsilonForm = null;
76     Forest epsilonForm() {
77         if (epsilonForm!=null) return epsilonForm;
78         epsilonForm = new Forest.Ref();
79         epsilonForm.merge(firstp().rewrite(null, false));
80         return epsilonForm;
81     }
82
83     protected abstract <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p);
84
85
86     // Position //////////////////////////////////////////////////////////////////////////////
87
88     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
89     public class Position implements IntegerMappable {
90
91         private Forest zero = null;
92         public Forest zero() {
93             if (zero != null) return zero;
94             if (pos > 0) throw new Error();
95             return zero = rewrite(null);
96         }
97
98
99                 final int      pos;
100         private final Position next;
101                 final Forest[] holder;
102         
103         private Position(int pos) {
104             this.pos      = pos;
105             this.next     = pos==elements.length ? null : new Position(pos+1);
106             this.holder   = new Forest[elements.length];
107         }
108
109         boolean isFirst() { return pos==0; }
110
111         /** the element immediately after this Position, or null if this is the last Position */
112         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
113
114         /** the element which produces the sequence to which this Position belongs */
115         public Sequence owner() { return Sequence.this; }
116
117         /** the next Position (the Position after <tt>this.element()</tt>) */
118         public Position next() { return next; }
119
120         /** true iff this Position is the last one in the sequence */
121         public boolean isLast() { return next()==null; }
122
123         // Position /////////////////////////////////////////////////////////////////////////////////
124
125         final <T> Forest<T> rewrite(Input.Location loc) { return rewrite(loc, true); }
126         private final <T> Forest<T> rewrite(Input.Location loc, boolean epsilonCheck) {
127             if (epsilonCheck && this==firstp()) return epsilonForm();
128             for(int i=0; i<pos; i++) if (holder[i]==null) throw new Error("realbad " + i);
129             for(int i=pos; i<elements.length; i++) {
130                 if (holder[i]==null) holder[i] = elements[i].epsilonForm();
131                 if (holder[i]==null) throw new Error("bad " + i);
132             }
133             Forest<T> ret = Sequence.this.postReduce(loc, holder, this);
134             for(int k=0; k<pos; k++) holder[k] = null; // to help GC
135             return ret;
136         }
137
138         public String   toString() {
139             StringBuffer ret = new StringBuffer();
140             ret.append("<{");
141             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
142                 ret.append(' ');
143                 if (p==this) ret.append(" | ");
144                 if (p.element()!=null) ret.append(p.element());
145                 else                   ret.append(' ');
146             }
147             ret.append("}>");
148             return ret.toString();
149         }
150         private final int idx = master_position_idx++;
151         public int toInt() { return idx; }
152     }
153     private static int master_position_idx = 0;
154
155     // toString //////////////////////////////////////////////////////////////////////////////
156
157     public String toString() { return toString(new StringBuffer(), false).toString(); }
158     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
159     StringBuffer toString(StringBuffer sb, boolean spacing) {
160         for(int i=0; i<elements.length; i++) {
161             sb.append(elements[i].toString());
162             sb.append(' ');
163         }
164         return sb;
165     }
166
167
168     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
169
170     static class Constant extends Sequence {
171         private final Object result;
172         public Constant(Element[] e, Object result) { super(e); this.result = result; }
173         Sequence _clone() { return new Constant(elements, result); }
174         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) {
175             return (Forest<T>)Forest.leaf(loc, result, p);
176         }
177         static class Drop extends Constant {
178             Sequence _clone() { return new Drop(elements, lame); }
179             public Drop(Element[] e, boolean lame) {
180                 super(e, null);
181                 this.lame = lame;
182             }
183         }
184         static class Empty extends Sequence.Constant.Drop {
185             Sequence _clone() { return new Empty(); }
186             public Empty() { super(new Element[] { }, false); } }
187     }
188
189     static class Singleton extends Sequence {
190         private final int idx;
191         public Singleton(Element e) { this(new Element[] { e }, 0); }
192         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
193         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) { return (Forest<T>)Forest.singleton(loc, args[idx], p); }
194         Sequence _clone() { return new Singleton(elements,idx); }
195     }
196
197     public static class Unwrap extends Sequence {
198         private boolean[] drops;
199         public Unwrap(Element[] e)                  { super(e); this.drops = null; }
200         public Unwrap(Element[] e, boolean[] drops) { super(e); this.drops = drops; }
201         Sequence _clone() { return new Unwrap(elements, drops); }
202         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) {
203             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
204             if (drops==null) return Forest.create(loc, null, args, true, false, p);
205             int count = 0;
206             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
207             Forest<T>[] args2 = new Forest[count];
208             int j = 0;
209             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
210             return Forest.create(loc, null, args2, true, false, p);
211         }
212     }
213
214     static class RewritingSequence extends Sequence {
215         /*private*/public final Object tag;
216         private final boolean[] drops;
217         private int count = 0;
218         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
219         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
220         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
221             super(e);
222             this.tag = tag;
223             this.drops = drops == null ? new boolean[e.length] : drops;
224             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
225         }
226         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) {
227             Forest<T>[] args2 = new Forest[count];
228             int j = 0;
229             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
230             //System.out.println("reduce \""+tag+"\"");
231             return Forest.create(loc, (T)tag, args2, false, false, p);
232         }
233         public StringBuffer toString(StringBuffer sb, boolean spacing) {
234             int len = sb.length();
235             super.toString(sb, spacing);
236             len = sb.length()-len;
237             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
238             sb.append(" => ");
239             sb.append(tag);
240             return sb;
241         }
242     }
243 }