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