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