a029274a0a01f7cbe48db426e645c1def564e64a
[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     public boolean needed_or_hated = false;
18
19     public HashMap<Sequence,Boolean> canNeed = new HashMap<Sequence,Boolean>();
20     public HashMap<Sequence,Boolean> canKill = new HashMap<Sequence,Boolean>();
21
22     final HashSet<Sequence> hated   = new HashSet<Sequence>();
23
24     final HashSet<Sequence> needs  = new HashSet<Sequence>();
25     final HashSet<Sequence> hates  = new HashSet<Sequence>();
26
27     final Position          firstp;
28
29     Atom follow = null;
30
31     // Static Constructors //////////////////////////////////////////////////////////////////////////////
32
33     abstract Sequence _clone();
34     Sequence dup() {
35         Sequence ret = _clone();
36         for(Sequence s : needs) { ret.needs.add(s); }
37         for(Sequence s : hates) { ret.hates.add(s); s.hated.add(ret); }
38         ret.follow = follow;
39         return ret;
40     }
41
42     /** create an empty sequence (matches the empty string) */
43     public static Sequence create() { return new Sequence.Constant.Empty(); }
44
45     /** create a sequence of one element */
46     public static Sequence create(Element e) { return create(new Element[] { e }, 0); }
47
48     /** create a sequence which drops the result of all but one of its element */
49     public static Sequence create(Element[] e, int which) { return new Singleton(e, which); }
50
51     /** create a sequence which always evaluates to a constant result  */
52     public static Sequence create(Element[] e, Object result) { return new Constant(e, result); }
53
54     /**
55      *  create a sequence (general form)
56      *  @param head   the head of the output tree
57      *  @param e      the elements to match
58      *  @param drop   only elements of <tt>e</tt> whose corresponding <tt>boolean</tt> in <tt>drops</tt>
59      *                is <i>false</i> will be included in the output tree
60      *  @param foster if true, all children of the last child (ie
61      *                grandchildren) are promoted to children of this
62      *                node; this is very useful for matching repetitions
63      **/
64     public static Sequence create(Object head, Element[] e, boolean[] drop, boolean foster) {
65         return foster
66             ? new Unwrap(e, head, drop)
67             : new RewritingSequence(head, e, drop);
68     }
69
70     ////////////////////////////////////////////////////////////////////////////////
71
72     /** return a new sequence identical to this one, but with a positive conjunct <tt>s</tt> */
73     public Sequence and(Sequence s) { Sequence ret = dup(); ret.needs.add(s); s.needed_or_hated=true; return ret; }
74
75     /** return a new sequence identical to this one, but with a negative conjunct <tt>s</tt> */
76     public Sequence andnot(Sequence s) { Sequence ret = dup(); ret.hates.add(s); s.hated.add(ret); s.needed_or_hated=true; return ret; }
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     boolean hatesAny(Iterable<Sequence> it) {
82         if (hates.isEmpty()) return false;
83         for(Sequence s : it) if (hates.contains(s)) return true;
84         return false;
85     }
86
87     Iterable<Sequence> needs() { return needs; }
88     Iterable<Sequence> hates() { return hates; }
89
90     Position firstp() { return firstp; }
91
92     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
93     protected Sequence(Element[] elements) {
94         this.elements = elements;
95         this.firstp = new Position(0);
96     }
97
98     // DO NOT MESS WITH THE FOLLOWING LINE!!!
99     private Forest.Many epsilonForm = null;
100     Forest epsilonForm(Input.Region loc) {
101         if (epsilonForm!=null) return epsilonForm;
102         epsilonForm = new Forest.Many();
103         epsilonForm.merge(firstp().rewrite(loc, false));
104         return epsilonForm;
105     }
106
107     protected abstract <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p);
108
109
110     // Position //////////////////////////////////////////////////////////////////////////////
111
112     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
113     class Position implements IntegerMappable {
114
115         public int ord = -1;
116         public int compareTo(Position p, Walk.Cache cache) {
117             Position position = this;
118             Position rposition = p;
119             int ret = 0;
120             if (Reduction.canKill(cache, position, rposition) &&
121                 Reduction.canKill(cache, rposition, position)) throw new Error();
122             if      (Reduction.canKill(cache, position,   rposition)) ret =  1;
123             else if (Reduction.canKill(cache, rposition, position)) ret = -1;
124             if      (Reduction.canNeed(cache, position,   rposition)) ret =  1;
125             else if (Reduction.canNeed(cache, rposition, position)) ret = -1;
126             return ret;
127         }
128
129         private Forest zero = null;
130         public Forest zero(Input.Region reg) {
131             if (zero != null) return zero;
132             if (pos > 0) throw new Error();
133             return zero = rewrite(reg);
134         }
135
136
137                 final int      pos;
138         private final Position next;
139                 final Forest[] holder;
140         
141         private Position(int pos) {
142             this.pos      = pos;
143             this.next     = pos==elements.length ? null : new Position(pos+1);
144             this.holder   = new Forest[elements.length];
145         }
146
147         boolean isFirst() { return pos==0; }
148
149         /** the element immediately after this Position, or null if this is the last Position */
150         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
151
152         /** the element which produces the sequence to which this Position belongs */
153         public Sequence owner() { return Sequence.this; }
154
155         /** the next Position (the Position after <tt>this.element()</tt>) */
156         public Position next() { return next; }
157
158         /** true iff this Position is the last one in the sequence */
159         public boolean isLast() { return next()==null; }
160
161         // Position /////////////////////////////////////////////////////////////////////////////////
162
163         final <T> Forest<T> rewrite(Input.Region loc) { return rewrite(loc, true); }
164         private final <T> Forest<T> rewrite(Input.Region loc, boolean epsilonCheck) {
165             if (epsilonCheck && this==firstp()) return epsilonForm(loc);
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] = elements[i].epsilonForm(loc);
169                 if (holder[i]==null) throw new Error("bad " + i);
170             }
171             Forest<T> ret = Sequence.this.postReduce(loc, holder, this);
172             //for(int k=0; k<pos; k++) holder[k] = null; // to help GC
173             return ret;
174         }
175
176         public String   toString() {
177             StringBuffer ret = new StringBuffer();
178             ret.append("<{");
179             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
180                 ret.append(' ');
181                 if (p==this) ret.append(" | ");
182                 if (p.element()!=null) ret.append(p.element());
183                 else                   ret.append(' ');
184             }
185             ret.append("}>");
186             return ret.toString();
187         }
188         private final int idx = master_position_idx++;
189         public int toInt() { return idx; }
190     }
191     private static int master_position_idx = 0;
192
193     // toString //////////////////////////////////////////////////////////////////////////////
194
195     public String toString() { return toString(new StringBuffer(), false).toString(); }
196     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
197     StringBuffer toString(StringBuffer sb, boolean spacing) {
198         for(int i=0; i<elements.length; i++) {
199             sb.append(elements[i].toString());
200             sb.append(' ');
201         }
202         if (follow != null) {
203             sb.append("-> ");
204             sb.append(follow);
205         }
206         for(Sequence s : needs) {
207             sb.append("& ");
208             sb.append(s);
209         }
210         for(Sequence s : hates) {
211             sb.append("&~ ");
212             sb.append(s);
213         }
214         return sb;
215     }
216
217
218     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
219
220     static class Constant extends Sequence {
221         private final Object result;
222         public Constant(Element[] e, Object result) { super(e); this.result = result; }
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         static class Drop extends Constant {
228             Sequence _clone() { return new Drop(elements); }
229             public Drop(Element[] e) { super(e, null); }
230         }
231         static class Empty extends Sequence.Constant.Drop {
232             Sequence _clone() { return new Empty(); }
233             public Empty() { super(new Element[] { }); } }
234     }
235
236     static class Singleton extends Sequence {
237         private final int idx;
238         public Singleton(Element e) { this(new Element[] { e }, 0); }
239         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
240         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) { return args[idx]; }
241         Sequence _clone() { return new Singleton(elements,idx); }
242     }
243
244     static class Unwrap extends Sequence {
245         private boolean[] drops;
246         private final Object tag;
247         public Unwrap(Element[] e, Object tag)                  { super(e); this.drops = null; this.tag = tag; }
248         public Unwrap(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
249         Sequence _clone() { return new Unwrap(elements, tag, drops); }
250         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
251             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
252             if (drops==null) return Forest.create(loc, (T)tag, args, true);
253             int count = 0;
254             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
255             Forest<T>[] args2 = new Forest[count];
256             int j = 0;
257             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
258             return Forest.create(loc, (T)tag, args2, true);
259         }
260     }
261
262
263
264     static class RegionRewritingSequence extends RewritingSequence {
265         private Functor<Input.Region, Object> tagf;
266         public RegionRewritingSequence(Functor<Input.Region,Object> tagfunctor, Element[] e, boolean[] drops) {
267             super(null, e, drops);
268             this.tagf = tagfunctor;
269         }
270         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
271             this.tag = tagf.invoke(loc);
272             Forest<T> ret = super.postReduce(loc, args, p);
273             this.tag = null;
274             return ret;
275         }
276     }
277
278     static class RewritingSequence extends Sequence {
279         /*private*/public /*final*/ Object tag;
280         private final boolean[] drops;
281         private int count = 0;
282         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
283         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
284         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
285             super(e);
286             this.tag = tag;
287             this.drops = drops == null ? new boolean[e.length] : drops;
288             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
289         }
290         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
291             Forest<T>[] args2 = new Forest[count];
292             int j = 0;
293             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
294             //System.out.println("reduce \""+tag+"\"");
295             return Forest.create(loc, (T)tag, args2, false);
296         }
297         public StringBuffer toString(StringBuffer sb, boolean spacing) {
298             int len = sb.length();
299             if (tag != null)
300                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
301             super.toString(sb, spacing);
302             len = sb.length()-len;
303             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
304             return sb;
305         }
306     }
307
308 }