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     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.follow = follow;
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     public static Sequence singleton(Element e) { return singleton(new Element[] { e }, 0); }
36
37     /**
38      *  after matching the sequence, create the specified output tree
39      *  @param tag   the tag for the output tree
40      *  @param e     the elements to match
41      *  @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
42      **/
43     public static Sequence rewritingSequence(Object tag, Element[] e, Object[] labs, boolean[] drops) {
44         return new RewritingSequence(tag, e, labs, drops); }
45
46     ////////////////////////////////////////////////////////////////////////////////
47
48     public Element follow = null;
49     public final Topology follow() { return follow==null ? null : Atom.toAtom(follow); }
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     public Sequence and(Sequence s) { Sequence ret = dup(); ret.needs.add(s); s.needed.add(ret); return ret; }
57     public Sequence not(Sequence s) { Sequence ret = dup(); ret.hates.add(s); s.hated.add(ret); return ret; }
58
59     protected final Element[] elements;
60
61     final HashSet<Sequence> needed = new HashSet<Sequence>();
62     final HashSet<Sequence> hated = new HashSet<Sequence>();
63     final HashSet<Sequence> needs = new HashSet<Sequence>();
64     final HashSet<Sequence> hates = new HashSet<Sequence>();
65     public boolean           lame  = false;
66
67     final Position          firstp;
68     Position firstp() { return firstp; }
69
70     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
71     protected Sequence(Element[] elements) {
72         this.elements = elements;
73         this.firstp = new Position(0);
74     }
75
76     // DO NOT MESS WITH THE FOLLOWING LINE!!!
77     private Forest.Ref epsilonForm = null;
78     Forest epsilonForm() {
79         if (epsilonForm!=null) return epsilonForm;
80         epsilonForm = new Forest.Ref();
81         epsilonForm.merge(firstp().rewrite(null, false));
82         return epsilonForm;
83     }
84
85     protected abstract <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p);
86
87
88     // Position //////////////////////////////////////////////////////////////////////////////
89
90     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
91     public class Position implements IntegerMappable {
92
93         private Forest zero = null;
94         public Forest zero() {
95             if (zero != null) return zero;
96             if (pos > 0) throw new Error();
97             return zero = rewrite(null);
98         }
99
100
101                 final int      pos;
102         private final Position next;
103                 final Forest[] holder;
104         
105         private Position(int pos) {
106             this.pos      = pos;
107             this.next     = pos==elements.length ? null : new Position(pos+1);
108             this.holder   = new Forest[elements.length];
109         }
110
111         boolean isFirst() { return pos==0; }
112
113         /** the element immediately after this Position, or null if this is the last Position */
114         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
115
116         /** the element which produces the sequence to which this Position belongs */
117         public Sequence owner() { return Sequence.this; }
118
119         /** the next Position (the Position after <tt>this.element()</tt>) */
120         public Position next() { return next; }
121
122         /** true iff this Position is the last one in the sequence */
123         public boolean isLast() { return next()==null; }
124
125         // Position /////////////////////////////////////////////////////////////////////////////////
126
127         final <T> Forest<T> rewrite(Input.Location loc) { return rewrite(loc, true); }
128         private final <T> Forest<T> rewrite(Input.Location loc, boolean epsilonCheck) {
129             if (epsilonCheck && this==firstp()) return epsilonForm();
130             for(int i=0; i<pos; i++) if (holder[i]==null) throw new Error("realbad " + i);
131             for(int i=pos; i<elements.length; i++) {
132                 if (holder[i]==null) holder[i] = elements[i].epsilonForm();
133                 if (holder[i]==null) throw new Error("bad " + i);
134             }
135             Forest<T> ret = Sequence.this.postReduce(loc, holder, this);
136             for(int k=0; k<pos; k++) holder[k] = null; // to help GC
137             return ret;
138         }
139
140         public String   toString() {
141             StringBuffer ret = new StringBuffer();
142             ret.append("<{");
143             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
144                 ret.append(' ');
145                 if (p==this) ret.append(" | ");
146                 if (p.element()!=null) ret.append(p.element());
147                 else                   ret.append(' ');
148             }
149             ret.append("}>");
150             return ret.toString();
151         }
152         private final int idx = master_position_idx++;
153         public int toInt() { return idx; }
154     }
155     private static int master_position_idx = 0;
156
157     // toString //////////////////////////////////////////////////////////////////////////////
158
159     public String toString() { return toString(new StringBuffer(), false).toString(); }
160     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
161     StringBuffer toString(StringBuffer sb, boolean spacing) {
162         for(int i=0; i<elements.length; i++) {
163             sb.append(elements[i].toString());
164             sb.append(' ');
165         }
166         if (follow != null) {
167             sb.append("-> ");
168             sb.append(follow);
169         }
170         return sb;
171     }
172
173
174     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
175
176     static class Constant extends Sequence {
177         private final Object result;
178         public Constant(Element[] e, Object result) { super(e); this.result = result; }
179         Sequence _clone() { return new Constant(elements, result); }
180         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) {
181             return (Forest<T>)Forest.leaf(loc, result, p);
182         }
183         static class Drop extends Constant {
184             Sequence _clone() { return new Drop(elements, lame); }
185             public Drop(Element[] e, boolean lame) {
186                 super(e, null);
187                 this.lame = lame;
188             }
189         }
190         static class Empty extends Sequence.Constant.Drop {
191             Sequence _clone() { return new Empty(); }
192             public Empty() { super(new Element[] { }, false); } }
193     }
194
195     static class Singleton extends Sequence {
196         private final int idx;
197         public Singleton(Element e) { this(new Element[] { e }, 0); }
198         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
199         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) { return (Forest<T>)Forest.singleton(loc, args[idx], p); }
200         Sequence _clone() { return new Singleton(elements,idx); }
201     }
202
203     public static Unwrap unwrap(Element[] e, Object tag, boolean[] drops) { return new Unwrap(e, tag, drops); }
204     static class Unwrap extends Sequence {
205         private boolean[] drops;
206         private final Object tag;
207         public Unwrap(Element[] e, Object tag)                  { super(e); this.drops = null; this.tag = tag; }
208         public Unwrap(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
209         Sequence _clone() { return new Unwrap(elements, drops); }
210         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) {
211             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
212             if (drops==null) return Forest.create(loc, (T)tag, args, new Object[args.length], true, false, p);
213             int count = 0;
214             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
215             Forest<T>[] args2 = new Forest[count];
216             int j = 0;
217             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
218             return Forest.create(loc, (T)tag, args2, new Object[args.length], true, false, p);
219         }
220     }
221
222     static class RewritingSequence extends Sequence {
223         /*private*/public final Object tag;
224         private final boolean[] drops;
225         private final Object[] labs;
226         private int count = 0;
227         Sequence _clone() { return new RewritingSequence(tag, elements, labs, drops); }
228         public RewritingSequence(Object tag, Element[] e, Object[] labs) { this(tag, e, labs, null); }
229         public RewritingSequence(Object tag, Element[] e, Object[] labs, boolean[] drops) {
230             super(e);
231             this.tag = tag;
232             this.drops = drops == null ? new boolean[e.length] : drops;
233             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
234             this.labs = labs;
235         }
236         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args, Position p) {
237             Forest<T>[] args2 = new Forest[count];
238             Object[] labs2 = new Object[count];
239             int j = 0;
240             for(int i=0; i<args.length; i++) if (!drops[i]) { labs2[j] = labs==null?null:labs[i]; args2[j++] = args[i]; }
241             //System.out.println("reduce \""+tag+"\"");
242             return Forest.create(loc, (T)tag, args2, labs2, false, false, p);
243         }
244         public StringBuffer toString(StringBuffer sb, boolean spacing) {
245             int len = sb.length();
246             if (tag != null)
247                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
248             super.toString(sb, spacing);
249             len = sb.length()-len;
250             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
251             return sb;
252         }
253     }
254
255     // Repeat //////////////////////////////////////////////////////////////////////////////
256
257     /** repeat zero or one times */
258     public  static Repeat maybe(Element e)                             { return new Repeat(e, true, false, null, null); }
259     public  static Repeat maybe(Element e, Object tag)                 { return new Repeat(e, true, false, null, tag); }
260     /** repeat zero or more times */
261     public  static Repeat many0(Element e)                             { return new Repeat(e, true, true, null, null); }
262     public  static Repeat many0(Element e, Object tag)                 { return new Repeat(e, true, true, null, tag); }
263     /** repeat zero or more times, separated by <tt>sep</tt> */
264     public  static Repeat many0(Element e, Element sep)                { return new Repeat(e, true, true, sep, null); }
265     public  static Repeat many0(Element e, Element sep, Object tag)    { return new Repeat(e, true, true, sep, tag); }
266     /** repeat one or more times */
267     public  static Repeat many1(Element e)                             { return new Repeat(e, false, true, null, null); }
268     public  static Repeat many1(Element e, Object tag)                 { return new Repeat(e, false, true, null, tag); }
269     /** repeat one or more times, separated by <tt>sep</tt> */
270     public  static Repeat many1(Element e, Element sep)                { return new Repeat(e, false, true, sep, null); }
271     public  static Repeat many1(Element e, Element sep, Object tag)    { return new Repeat(e, false, true, sep, tag); }
272
273     /** repeat zero or more times, matching a maximal sequence of atoms */
274     public  static Repeat maximal0(Element e)                          { return new Repeat.Maximal(e, true, true, null); }
275     public  static Repeat maximal0(Element e, Object tag)              { return new Repeat.Maximal(e, true, true, tag); }
276     /** repeat one or more times, matching a maximal sequence of atoms */
277     public  static Repeat maximal1(Element e)                          { return new Repeat.Maximal(e, false, true, null); }
278     public  static Repeat maximal1(Element e, Object tag)              { return new Repeat.Maximal(e, false, true, tag); }
279     /** repeat one or more times, separated by an atom <tt>sep</tt>, matching a maximal sequence */
280     public  static Repeat maximal1(Element e, Element sep)             { return new Repeat.Maximal(e, false, true, sep, null); }
281     public  static Repeat maximal1(Element e, Element sep, Object tag) { return new Repeat.Maximal(e, false, true, sep, tag); }
282
283
284 }