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