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