f4315182d654770e32ee45c8cc9017a3d17dda1e
[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 extends Element implements Iterable<Element> {
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 not(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() {
88         if (epsilonForm!=null) return epsilonForm;
89         epsilonForm = new Forest.Many();
90         epsilonForm.merge(firstp().rewrite(null, 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() {
104             if (zero != null) return zero;
105             if (pos > 0) throw new Error();
106             return zero = rewrite(null);
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();
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();
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         return sb;
180     }
181
182
183     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
184
185     static class Constant extends Sequence {
186         private final Object result;
187         public Constant(Element[] e, Object result) { super(e); this.result = result; }
188         Sequence _clone() { return new Constant(elements, result); }
189         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
190             return (Forest<T>)Forest.create(loc, result, null, false);
191         }
192         static class Drop extends Constant {
193             Sequence _clone() { return new Drop(elements); }
194             public Drop(Element[] e) { super(e, null); }
195         }
196         static class Empty extends Sequence.Constant.Drop {
197             Sequence _clone() { return new Empty(); }
198             public Empty() { super(new Element[] { }); } }
199     }
200
201     static class Singleton extends Sequence {
202         private final int idx;
203         public Singleton(Element e) { this(new Element[] { e }, 0); }
204         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
205         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) { return args[idx]; }
206         Sequence _clone() { return new Singleton(elements,idx); }
207     }
208
209     static class Unwrap extends Sequence {
210         private boolean[] drops;
211         private final Object tag;
212         public Unwrap(Element[] e, Object tag)                  { super(e); this.drops = null; this.tag = tag; }
213         public Unwrap(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
214         Sequence _clone() { return new Unwrap(elements, tag, drops); }
215         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
216             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
217             if (drops==null) return Forest.create(loc, (T)tag, args, true);
218             int count = 0;
219             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
220             Forest<T>[] args2 = new Forest[count];
221             int j = 0;
222             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
223             return Forest.create(loc, (T)tag, args2, true);
224         }
225     }
226
227
228
229     static class RegionRewritingSequence extends RewritingSequence {
230         private Functor<Input.Region, Object> tagf;
231         public RegionRewritingSequence(Functor<Input.Region,Object> tagfunctor, Element[] e, boolean[] drops) {
232             super(null, e, drops);
233             this.tagf = tagfunctor;
234         }
235         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
236             this.tag = tagf.invoke(loc);
237             Forest<T> ret = super.postReduce(loc, args, p);
238             this.tag = null;
239             return ret;
240         }
241     }
242
243     static class RewritingSequence extends Sequence {
244         /*private*/public /*final*/ Object tag;
245         private final boolean[] drops;
246         private int count = 0;
247         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
248         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
249         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
250             super(e);
251             this.tag = tag;
252             this.drops = drops == null ? new boolean[e.length] : drops;
253             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
254         }
255         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
256             Forest<T>[] args2 = new Forest[count];
257             int j = 0;
258             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
259             //System.out.println("reduce \""+tag+"\"");
260             return Forest.create(loc, (T)tag, args2, false);
261         }
262         public StringBuffer toString(StringBuffer sb, boolean spacing) {
263             int len = sb.length();
264             if (tag != null)
265                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
266             super.toString(sb, spacing);
267             len = sb.length()-len;
268             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
269             return sb;
270         }
271     }
272
273 }