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