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