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