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