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 Sequence newEmptySequence() { return new Sequence.Constant.Empty(); }
37
38     /** after matching the sequence, do not add anything to the output tree */
39     public static Sequence newDropSequence(Element[] e) { return new Constant.Drop(e); }
40
41     /** after matching the sequence, insert a constant into the output tree */
42     public static Sequence newConstantSequence(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 newSingletonSequence(Element[] e, int idx) { return new Singleton(e, idx); }
46     public static Sequence newSingletonSequence(Element e) { return newSingletonSequence(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 newRewritingSequence(Object tag, Element[] e, boolean[] drops) {
56         return new RewritingSequence(tag, e, drops); }
57
58     public static Sequence newUnwrapSequence(Element[] e, Object tag, boolean[] drops) { return new Unwrap(e, tag, drops); }
59
60     ////////////////////////////////////////////////////////////////////////////////
61
62     /** return a new sequence identical to this one, but with a positive conjunct <tt>s</tt> */
63     public Sequence and(Sequence s) { Sequence ret = dup(); ret.needs.add(s); return ret; }
64
65     /** return a new sequence identical to this one, but with a negative conjunct <tt>s</tt> */
66     public Sequence not(Sequence s) { Sequence ret = dup(); ret.hates.add(s); s.hated.add(ret); return ret; }
67
68     /** return a new sequence identical to this one, but with a follow-set restricted to <tt>a</tt> */
69     public Sequence followedBy(Atom a) { Sequence ret = dup(); ret.follow = a; return ret; }
70
71     Iterable<Sequence> needs() { return needs; }
72     Iterable<Sequence> hates() { return hates; }
73
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.Many epsilonForm = null;
84     Forest epsilonForm() {
85         if (epsilonForm!=null) return epsilonForm;
86         epsilonForm = new Forest.Many();
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     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); }
191             public Drop(Element[] e) { super(e, null); }
192         }
193         static class Empty extends Sequence.Constant.Drop {
194             Sequence _clone() { return new Empty(); }
195             public Empty() { super(new Element[] { }); } }
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     static class Unwrap extends Sequence {
207         private boolean[] drops;
208         private final Object tag;
209         public Unwrap(Element[] e, Object tag)                  { super(e); this.drops = null; this.tag = tag; }
210         public Unwrap(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
211         Sequence _clone() { return new Unwrap(elements, tag, drops); }
212         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
213             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
214             if (drops==null) return Forest.create(loc, (T)tag, args, true);
215             int count = 0;
216             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
217             Forest<T>[] args2 = new Forest[count];
218             int j = 0;
219             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
220             return Forest.create(loc, (T)tag, args2, true);
221         }
222     }
223
224
225
226     static class RegionRewritingSequence extends RewritingSequence {
227         private Functor<Input.Region, Object> tagf;
228         public RegionRewritingSequence(Functor<Input.Region,Object> tagfunctor, Element[] e, boolean[] drops) {
229             super(null, e, drops);
230             this.tagf = tagfunctor;
231         }
232         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
233             this.tag = tagf.invoke(loc);
234             Forest<T> ret = super.postReduce(loc, args, p);
235             this.tag = null;
236             return ret;
237         }
238     }
239
240     static class RewritingSequence extends Sequence {
241         /*private*/public /*final*/ Object tag;
242         private final boolean[] drops;
243         private int count = 0;
244         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
245         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
246         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
247             super(e);
248             this.tag = tag;
249             this.drops = drops == null ? new boolean[e.length] : drops;
250             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
251         }
252         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
253             Forest<T>[] args2 = new Forest[count];
254             int j = 0;
255             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
256             //System.out.println("reduce \""+tag+"\"");
257             return Forest.create(loc, (T)tag, args2, false);
258         }
259         public StringBuffer toString(StringBuffer sb, boolean spacing) {
260             int len = sb.length();
261             if (tag != null)
262                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
263             super.toString(sb, spacing);
264             len = sb.length()-len;
265             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
266             return sb;
267         }
268     }
269
270 }