checkpoint
[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 /** juxtaposition; zero or more adjacent Elements; can specify a rewriting */
11 public abstract class Sequence extends Element implements Iterable<Element> {
12
13     // Static Constructors //////////////////////////////////////////////////////////////////////////////
14
15     public abstract Sequence and(Sequence s);
16     public abstract Sequence not(Sequence s);
17
18     private void needs(Sequence s) { s.needed.add(this); needs.add(s); }
19     private void hates(Sequence s) { s.hated.add(this); hates.add(s); }
20
21     void clone(Sequence seq) {
22         for(Sequence s : seq.hates) hates(s);
23         for(Sequence s : seq.needs) needs(s);
24         noFollow = seq.noFollow;
25     }
26
27     /** the empty sequence (matches the empty string) */
28     public static final Sequence empty = new Sequence.Constant.Empty();
29
30     /** after matching the sequence, do not add anything to the output tree */
31     public static Sequence drop(Element[] e, boolean lame) { return new Constant.Drop(e, lame); }
32
33     /** after matching the sequence, insert a constant into the output tree */
34     public static Sequence constant(Element[] e, Object o) { return new Constant(e, o); }
35
36     /** after matching the sequence, place the result of the <tt>idx</tt>th match in the output tree */
37     public static Sequence singleton(Element[] e, int idx) { return new Singleton(e, idx); }
38
39     /**
40      *  after matching the sequence, create the specified output tree
41      *  @param tag   the tag for the output tree
42      *  @param e     the elements to match
43      *  @param drops only elements of <tt>e</tt> whose corresponding <tt>boolean</tt> in <tt>drops</tt> is <i>false</i> will be included in the output tree
44      **/
45     public static Sequence rewritingSequence(Object tag, Element[] e, boolean[] drops) { return new RewritingSequence(tag, e, drops); }
46
47     ////////////////////////////////////////////////////////////////////////////////
48
49     public Element noFollow = null;
50     public String name = null;
51     public void setName(String name) { this.name = name; }
52     public final Topology noFollow() { return noFollow==null ? null : noFollow.toAtom(); }
53
54     Topology toAtom() {
55         if (elements.length!=1) throw new RuntimeException("cannot invoke toAtom() on a Sequence with " + elements.length + " elements: " + this);
56         return elements[0].toAtom();
57     }
58
59     protected final Element[] elements;
60
61     final HashSet<Sequence> needed = new HashSet<Sequence>();
62     final HashSet<Sequence> hated = new HashSet<Sequence>();
63     final HashSet<Sequence> needs = new HashSet<Sequence>();
64     final HashSet<Sequence> hates = new HashSet<Sequence>();
65     public boolean           lame  = false;
66
67     final Position          firstp;
68     Position firstp() { return firstp; }
69
70     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
71     protected Sequence(Element[] elements) {
72         this.elements = elements;
73         this.firstp = new Position(0);
74     }
75
76     // DO NOT MESS WITH THE FOLLOWING LINE!!!
77     private Forest.Ref epsilonForm = null;
78     private boolean eps = false;
79     Forest epsilonForm() {
80         if (epsilonForm==null) {
81             epsilonForm = new Forest.Ref();
82             epsilonForm.merge(firstp().rewrite2(null));
83         }
84         return epsilonForm;
85     }
86
87     protected abstract <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args);
88
89
90     // Position //////////////////////////////////////////////////////////////////////////////
91
92     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
93     public class Position implements IntegerMappable {
94
95         private Forest zero = null;
96         public Forest zero() {
97             if (zero != null) return zero;
98             if (pos > 0) throw new Error();
99             return zero = rewrite(null);
100         }
101
102
103                 final int      pos;
104         private final Position next;
105                 final Forest[] holder;
106         
107         private Position(int pos) {
108             this.pos      = pos;
109             this.next     = pos==elements.length ? null : new Position(pos+1);
110             this.holder   = new Forest[elements.length];
111         }
112
113         boolean isFirst() { return pos==0; }
114
115         /** the element immediately after this Position, or null if this is the last Position */
116         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
117
118         /** the element which produces the sequence to which this Position belongs */
119         public Sequence owner() { return Sequence.this; }
120
121         /** the next Position (the Position after <tt>this.element()</tt>) */
122         public Position next() { return next; }
123
124         /** true iff this Position is the last one in the sequence */
125         public boolean isLast() { return next()==null; }
126
127         // Position /////////////////////////////////////////////////////////////////////////////////
128
129         final <T> Forest<T> rewrite(Input.Location loc) {
130             if (this==firstp()) return epsilonForm();
131             return rewrite2(loc);
132         }
133
134         final <T> Forest<T> rewrite2(Input.Location loc) {
135             for(int i=0; i<pos; i++) if (holder[i]==null) throw new Error("realbad " + i);
136             for(int i=pos; i<elements.length; i++) {
137                 if (holder[i]==null) holder[i] = elements[i].epsilonForm();
138                 if (holder[i]==null) throw new Error("bad " + i);
139             }
140             Forest<T> ret = Sequence.this.postReduce(loc, holder);
141             for(int k=0; k<pos; k++) holder[k] = null; // to help GC
142             return ret;
143         }
144
145         public String   toString() {
146             StringBuffer ret = new StringBuffer();
147             ret.append("<{");
148             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
149                 ret.append(' ');
150                 if (p==this) ret.append(" | ");
151                 if (p.element()!=null) ret.append(p.element());
152                 else                   ret.append(' ');
153             }
154             ret.append("}>");
155             return ret.toString();
156         }
157         private final int idx = master_position_idx++;
158         public int toInt() { return idx; }
159     }
160     private static int master_position_idx = 0;
161
162     // toString //////////////////////////////////////////////////////////////////////////////
163
164     public String toString() { return toString(new StringBuffer(), false).toString(); }
165     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
166     StringBuffer toString(StringBuffer sb, boolean spacing) {
167         for(int i=0; i<elements.length; i++) {
168             sb.append(elements[i].toString());
169             sb.append(' ');
170         }
171         return sb;
172     }
173
174
175     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
176
177     static class Constant extends Sequence {
178         private final Object result;
179         public Constant(Element[] e, Object result) { super(e); this.result = result; }
180         public Sequence and(Sequence s) { Sequence ret = new Constant(elements, result); ret.needs(s); ret.clone(this); return ret; }
181         public Sequence not(Sequence s) { Sequence ret = new Constant(elements, result); ret.hates(s); ret.clone(this); return ret; }
182         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
183             return (Forest<T>)Forest.leaf(loc, result);
184         }
185         static class Drop extends Constant {
186             public Drop(Element[] e, boolean lame) {
187                 super(e, null);
188                 this.lame = lame;
189             }
190             public Sequence and(Sequence s) { Sequence ret = new Drop(elements, lame); ret.needs(s); ret.clone(this); return ret; }
191             public Sequence not(Sequence s) { Sequence ret = new Drop(elements, lame); ret.hates(s); ret.clone(this); return ret; }
192         }
193         static class Empty extends Sequence.Constant.Drop { public Empty() { super(new Element[] { }, false); } }
194     }
195
196     static class Singleton extends Sequence {
197         private final int idx;
198         public Singleton(Element e) { this(new Element[] { e }, 0); }
199         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
200         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) { return (Forest<T>)Forest.singleton(loc, args[idx]); }
201         public Sequence and(Sequence s) { Sequence ret = new Singleton(elements, idx); ret.needs(s); ret.clone(this); return ret; }
202         public Sequence not(Sequence s) { Sequence ret = new Singleton(elements, idx); ret.hates(s); ret.clone(this); return ret; }
203     }
204
205     public static class Unwrap extends Sequence {
206         private boolean[] drops;
207         public Unwrap(Element[] e)                  { super(e); this.drops = null; }
208         public Unwrap(Element[] e, boolean[] drops) { super(e); this.drops = drops; }
209         public Sequence and(Sequence s) { Sequence ret = new Unwrap(elements, drops); ret.needs(s); ret.clone(this); return ret; }
210         public Sequence not(Sequence s) { Sequence ret = new Unwrap(elements, drops); ret.hates(s); ret.clone(this); return ret; }
211         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
212             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
213             if (drops==null) return Forest.create(loc, null, args, true, false);
214             int count = 0;
215             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
216             Forest<T>[] args2 = new Forest[count];
217             int j = 0;
218             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
219             return Forest.create(loc, null, args2, true, false);            
220         }
221     }
222
223     static class RewritingSequence extends Sequence {
224         /*private*/public final Object tag;
225         private final boolean[] drops;
226         private int count = 0;
227         public Sequence and(Sequence s) { Sequence ret = new RewritingSequence(tag, elements, drops); ret.needs(s); ret.clone(this); return ret; }
228         public Sequence not(Sequence s) { Sequence ret = new RewritingSequence(tag, elements, drops); ret.hates(s); ret.clone(this); return ret; }
229         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
230         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
231             super(e);
232             this.tag = tag;
233             this.drops = drops == null ? new boolean[e.length] : drops;
234             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
235         }
236         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
237             Forest<T>[] args2 = new Forest[count];
238             int j = 0;
239             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
240             //System.out.println("reduce \""+tag+"\"");
241             return Forest.create(loc, (T)tag, args2, false, false);
242         }
243         public StringBuffer toString(StringBuffer sb, boolean spacing) {
244             int len = sb.length();
245             super.toString(sb, spacing);
246             len = sb.length()-len;
247             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
248             sb.append(" => ");
249             sb.append(tag);
250             return sb;
251         }
252     }
253 }