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