c41be4ff9d62da6ba0537477b13c3db22aaed42d
[sbp.git] / src / edu / berkeley / sbp / Sequence.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.util.*;
5 import edu.berkeley.sbp.*;
6 import edu.berkeley.sbp.*;
7 import java.io.*;
8 import java.util.*;
9 import java.lang.reflect.*;
10 import java.lang.ref.*;
11
12 /** <font color=green>juxtaposition; zero or more adjacent Elements; can specify a rewriting</font> */
13 public abstract class Sequence implements Iterable<Element>, SequenceOrElement {
14
15     protected final Element[] elements;
16
17     boolean needed_or_hated = false;
18     boolean in_a_union = false;
19
20     final HashSet<Sequence> needs  = new HashSet<Sequence>();
21     final HashSet<Sequence> hates  = new HashSet<Sequence>();
22
23     // FIXME: these are ugly -- migrate into Grammar
24     HashMap<Sequence,Boolean> canNeed = new HashMap<Sequence,Boolean>();
25     HashMap<Sequence,Boolean> canKill = new HashMap<Sequence,Boolean>();
26
27     final Position          firstp;
28
29     Atom follow = null;
30
31     // Static Constructors //////////////////////////////////////////////////////////////////////////////
32
33     /** create a sequence of one element */
34     public static Sequence create(Element e) { return create(new Element[] { e }, 0); }
35
36     /** create a sequence which drops the result of all but one of its element */
37     public static Sequence create(Element[] e, int which) { return new Singleton(e, which); }
38
39     /** create a sequence which always evaluates to a constant result  */
40     public static Sequence create(Element[] e, Object result) { return new Constant(e, result); }
41
42     /**
43      *  create a sequence (general form)
44      *  @param head   the head of the output tree
45      *  @param e      the elements to match
46      *  @param drop   only elements of <tt>e</tt> whose corresponding <tt>boolean</tt> in <tt>drops</tt>
47      *                is <i>false</i> will be included in the output tree
48      *  @param foster if true, all children of the last child (ie
49      *                grandchildren) are promoted to children of this
50      *                node; this is very useful for matching repetitions
51      **/
52     public static Sequence create(Object head, Element[] e, boolean[] drop, boolean foster) {
53         return foster
54             ? new Unwrap(e, head, drop)
55             : new RewritingSequence(head, e, drop);
56     }
57     public static Sequence createLeft(Object head, Element[] e, boolean[] drop, boolean foster) {
58         return foster
59             ? new UnwrapLeft(e, head, drop)
60             : new RewritingSequence(head, e, drop);
61     }
62
63     /** return a new sequence identical to this one, but with a positive conjunct <tt>s</tt> */
64     public Sequence and(Sequence s) {
65         if (s.in_a_union)
66             throw new RuntimeException("you may not use a sequence as a conjunct if it belongs to a Union");
67         Sequence ret = dup();
68         ret.needs.add(s);
69         s.needed_or_hated=true;
70         return ret;
71     }
72
73     /** return a new sequence identical to this one, but with a negative conjunct <tt>s</tt> */
74     public Sequence andnot(Sequence s) {
75         if (s.in_a_union)
76             throw new RuntimeException("you may not use a sequence as a conjunct if it belongs to a Union");
77         Sequence ret = dup();
78         ret.hates.add(s);
79         s.needed_or_hated=true;
80         return ret;
81     }
82
83     /** return a new sequence identical to this one, but with a follow-set restricted to <tt>a</tt> */
84     public Sequence followedBy(Atom a) { Sequence ret = dup(); ret.follow = a; return ret; }
85
86     ////////////////////////////////////////////////////////////////////////////////
87
88     abstract Sequence _clone();
89     private Sequence dup() {
90         Sequence ret = _clone();
91         for(Sequence s : needs) { ret.needs.add(s); }
92         for(Sequence s : hates) { ret.hates.add(s); }
93         ret.follow = follow;
94         return ret;
95     }
96
97     Iterable<Sequence> needs() { return needs; }
98     Iterable<Sequence> hates() { return hates; }
99
100     Position firstp() { return firstp; }
101     Position lastp() { return firstp().last(); }
102
103     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
104     protected Sequence(Element[] elements) {
105         this.elements = elements;
106         for(int i=0; i<elements.length; i++)
107             if (elements[i]==null)
108                 throw new RuntimeException("cannot have nulls in a sequence: " + this);
109         this.firstp = new Position(0, null);
110     }
111
112     abstract Forest epsilonForm(Input.Region loc, Grammar cache);
113
114     protected abstract <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p);
115
116
117     // Position //////////////////////////////////////////////////////////////////////////////
118
119     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
120     class Position implements IntegerMappable {
121
122         public int ord = -1;
123
124         private Forest zero = null;
125         /*
126         public Forest zero(Input.Region reg) {
127             if (zero != null) return zero;
128             if (pos > 0) throw new RuntimeException("Position.zero(): pos>0");
129             return zero = rewrite(reg);
130         }
131         */
132                 final int      pos;
133         private final Position next;
134         private final Position prev;
135                 final Forest[] holder;
136         
137         private Position(int pos, Position prev) {
138             this.pos      = pos;
139             this.next     = pos==elements.length ? null : new Position(pos+1, this);
140             this.holder   = new Forest[elements.length];
141             this.prev     = prev;
142         }
143
144         boolean isFirst() { return pos==0; }
145
146         /** the element immediately after this Position, or null if this is the last Position */
147         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
148
149         /** the element which produces the sequence to which this Position belongs */
150         public Sequence owner() { return Sequence.this; }
151
152         /** the next Position (the Position after <tt>this.element()</tt>) */
153         public Position next() { return next; }
154
155         /** true iff this Position is the last one in the sequence */
156         public boolean isLast() { return next()==null; }
157         public Position last() { return isLast() ? this : next().last(); }
158         public Position prev() { return prev; }
159
160         // Position /////////////////////////////////////////////////////////////////////////////////
161
162         final <T> Forest<T> rewrite(Input.Region loc, Grammar cache) {
163             if (this==firstp()) epsilonForm(loc, cache);
164             for(int i=0; i<pos; i++) if (holder[i]==null) throw new Error("realbad " + i);
165             for(int i=pos; i<elements.length; i++) {
166                 if (holder[i]==null) holder[i] = ((Union)elements[i]).epsilonForm(loc, cache);
167                 if (holder[i]==null) throw new Error("bad");
168             }
169             return Sequence.this.postReduce(loc, holder, this);
170         }
171
172         public String   toString() {
173             StringBuffer ret = new StringBuffer();
174             ret.append("<{");
175             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
176                 ret.append(' ');
177                 if (p==this) ret.append(" | ");
178                 if (p.element()!=null) ret.append(p.element());
179                 else                   ret.append(' ');
180             }
181             ret.append("}>");
182             return ret.toString();
183         }
184         private final int idx = master_position_idx++;
185         public int toInt() { return idx; }
186     }
187     private static int master_position_idx = 0;
188
189     // toString //////////////////////////////////////////////////////////////////////////////
190
191     public String toString() { return toString(new StringBuffer(), false).toString(); }
192     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
193     StringBuffer toString(StringBuffer sb, boolean spacing) {
194         for(int i=0; i<elements.length; i++) {
195             sb.append(elements[i]+"");
196             sb.append(' ');
197         }
198         if (follow != null) {
199             sb.append("-> ");
200             sb.append(follow);
201         }
202         for(Sequence s : needs) {
203             sb.append("& ");
204             sb.append(s);
205         }
206         for(Sequence s : hates) {
207             sb.append("&~ ");
208             sb.append(s);
209         }
210         return sb;
211     }
212
213
214     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
215
216     static class Constant extends Sequence {
217         private final Object result;
218         public Constant(Element[] e, Object result) {
219             super(e);
220             if (result==null) throw new Error("constant sequences may not have result==null");
221             this.result = result;
222         }
223         Sequence _clone() { return new Constant(elements, result); }
224         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
225             return (Forest<T>)Forest.create(loc, result, null, false);
226         }
227         Forest epsilonForm(Input.Region loc, Grammar cache) {
228             return Forest.create(loc, result, null, false);
229         }
230     }
231
232     static class Singleton extends Sequence {
233         private final int idx;
234         public Singleton(Element e) { this(new Element[] { e }, 0); }
235         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
236         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) { return args[idx]; }
237         Sequence _clone() { return new Singleton(elements,idx); }
238         Forest epsilonForm(Input.Region loc, Grammar cache) {
239             return ((Union)elements[idx]).epsilonForm(loc, cache);
240         }
241     }
242
243     static class Unwrap extends Sequence {
244         private boolean[] drops;
245         private final Object tag;
246         public Unwrap(Element[] e, Object tag)                  { this(e, tag, null); }
247         public Unwrap(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
248         Sequence _clone() { return new Unwrap(elements, tag, drops); }
249         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
250             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
251             if (drops==null) return Forest.create(loc, (T)tag, args, true);
252             int count = 0;
253             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
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             return Forest.create(loc, (T)tag, args2, true);
258         }
259         Forest epsilonForm(Input.Region loc, Grammar cache) {
260             return Forest.create(loc, tag, new Forest[0], false);
261         }
262     }
263
264     static class UnwrapLeft extends Sequence {
265         private boolean[] drops;
266         private final Object tag;
267         public UnwrapLeft(Element[] e, Object tag)                  { this(e, tag, null); }
268         public UnwrapLeft(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
269         Sequence _clone() { return new UnwrapLeft(elements, tag, drops); }
270         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
271             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
272             if (drops==null) return Forest.create(loc, (T)tag, args, false, true);
273             int count = 0;
274             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
275             Forest<T>[] args2 = new Forest[count];
276             int j = 0;
277             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
278             return Forest.create(loc, (T)tag, args2, false, true);
279         }
280         Forest epsilonForm(Input.Region loc, Grammar cache) {
281             return Forest.create(loc, tag, new Forest[0], false);
282         }
283     }
284
285     static class RewritingSequence extends Sequence {
286         private Object tag;
287         private final boolean[] drops;
288         private int count = 0;
289         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
290         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
291         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
292             super(e);
293             if (tag==null) throw new Error();
294             this.tag = tag;
295             this.drops = drops == null ? new boolean[e.length] : drops;
296             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
297         }
298         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
299             Forest<T>[] args2 = new Forest[count];
300             int j = 0;
301             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
302             return Forest.create(loc, (T)tag, args2, false);
303         }
304         public StringBuffer toString(StringBuffer sb, boolean spacing) {
305             int len = sb.length();
306             if (tag != null)
307                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
308             super.toString(sb, spacing);
309             len = sb.length()-len;
310             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
311             return sb;
312         }
313         Forest epsilonForm(Input.Region loc, Grammar cache) {
314             return Forest.create(loc, tag, new Forest[0], false);
315         }
316     }
317
318 }