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