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