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 Atom follow = null;
54     public final Topology follow() { return follow; }
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     public Iterable<Sequence> needs() { return needs; }
60     public Iterable<Sequence> hates() { return hates; }
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.Many epsilonForm = null;
81     Forest epsilonForm() {
82         if (epsilonForm!=null) return epsilonForm;
83         epsilonForm = new Forest.Many();
84         epsilonForm.merge(firstp().rewrite(null, false));
85         return epsilonForm;
86     }
87
88     protected abstract <T> Forest<T> postReduce(Input.Region 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.Region loc) { return rewrite(loc, true); }
131         private final <T> Forest<T> rewrite(Input.Region 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.Region loc, Forest<T>[] args, Position p) {
184             return (Forest<T>)Forest.create(loc, result, null, false);
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.Region loc, Forest<T>[] args, Position p) { return args[idx]; }
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.Region 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, true);
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, true);
222         }
223     }
224
225
226
227     static class RegionRewritingSequence extends RewritingSequence {
228         private Functor<Input.Region, Object> tagf;
229         public RegionRewritingSequence(Functor<Input.Region,Object> tagfunctor, Element[] e, boolean[] drops) {
230             super(null, e, drops);
231             this.tagf = tagfunctor;
232         }
233         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
234             this.tag = tagf.invoke(loc);
235             Forest<T> ret = super.postReduce(loc, args, p);
236             this.tag = null;
237             return ret;
238         }
239     }
240
241     static class RewritingSequence extends Sequence {
242         /*private*/public /*final*/ Object tag;
243         private final boolean[] drops;
244         private int count = 0;
245         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
246         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
247         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
248             super(e);
249             this.tag = tag;
250             this.drops = drops == null ? new boolean[e.length] : drops;
251             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
252         }
253         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
254             Forest<T>[] args2 = new Forest[count];
255             int j = 0;
256             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
257             //System.out.println("reduce \""+tag+"\"");
258             return Forest.create(loc, (T)tag, args2, false);
259         }
260         public StringBuffer toString(StringBuffer sb, boolean spacing) {
261             int len = sb.length();
262             if (tag != null)
263                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
264             super.toString(sb, spacing);
265             len = sb.length()-len;
266             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
267             return sb;
268         }
269     }
270
271     // Repeat //////////////////////////////////////////////////////////////////////////////
272
273     /** repeat zero or one times */
274     public  static Element maybe(Element e)                             { return new Repeat(e, true, false, null, null); }
275     public  static Element maybe(Element e, Object tag)                 { return new Repeat(e, true, false, null, tag); }
276     /** repeat zero or more times */
277     public  static Element many0(Element e)                             { return new Repeat(e, true, true, null, null); }
278     public  static Element many0(Element e, Object tag)                 { return new Repeat(e, true, true, null, tag); }
279     /** repeat zero or more times, separated by <tt>sep</tt> */
280     public  static Element many0(Element e, Element sep)                { return new Repeat(e, true, true, sep, null); }
281     public  static Element many0(Element e, Element sep, Object tag)    { return new Repeat(e, true, true, sep, tag); }
282     /** repeat one or more times */
283     public  static Element many1(Element e)                             { return new Repeat(e, false, true, null, null); }
284     public  static Element many1(Element e, Object tag)                 { return new Repeat(e, false, true, null, tag); }
285     /** repeat one or more times, separated by <tt>sep</tt> */
286     public  static Element many1(Element e, Element sep)                { return new Repeat(e, false, true, sep, null); }
287     public  static Element many1(Element e, Element sep, Object tag)    { return new Repeat(e, false, true, sep, tag); }
288
289     /** repeat zero or more times, matching a maximal sequence of atoms */
290     public  static Element maximal0(Atom e)                             { return new Repeat.Maximal(e, true, true, null); }
291     public  static Element maximal0(Atom e, Object tag)                 { return new Repeat.Maximal(e, true, true, tag); }
292     /** repeat one or more times, matching a maximal sequence of atoms */
293     public  static Element maximal1(Atom e)                             { return new Repeat.Maximal(e, false, true, null); }
294     public  static Element maximal1(Atom e, Object tag)                 { return new Repeat.Maximal(e, false, true, tag); }
295     /** repeat one or more times, separated by an atom <tt>sep</tt>, matching a maximal sequence */
296     public  static Element maximal1(Element e, Atom sep)                { return new Repeat.Maximal(e, false, true, sep, null); }
297     public  static Element maximal1(Element e, Atom sep, Object tag)    { return new Repeat.Maximal(e, false, true, sep, tag); }
298
299     public  static Element repeatMaximal(Atom e, boolean zero, boolean many, Object tag) {
300         return new Repeat.Maximal(e, zero, many, tag); }
301     public  static Element repeatMaximal(Element e, boolean zero, boolean many, Atom sep, Object tag) {
302         return new Repeat.Maximal(e, zero, many, sep, tag); }
303     public  static Element repeat(Element e, boolean zero, boolean many, Object tag) {
304         return new Repeat(e, zero, many, tag); }
305     public  static Element repeat(Element e, boolean zero, boolean many, Element sep, Object tag) {
306         return new Repeat(e, zero, many, sep, tag); }
307 }