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