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