2eddfc4f01b1dcd163a6c11ea07ffa9ccef06846
[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 String name = null;
50     public void setName(String name) { this.name = name; }
51     public final Topology noFollow() { return noFollow==null ? null : noFollow.toAtom(); }
52
53     Topology toAtom() {
54         if (elements.length!=1) throw new RuntimeException("cannot invoke toAtom() on a Sequence with " + elements.length + " elements: " + this);
55         return elements[0].toAtom();
56     }
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     private boolean eps = false;
78     Forest epsilonForm() {
79         if (epsilonForm==null) {
80             epsilonForm = new Forest.Ref();
81             epsilonForm.merge(firstp().rewrite2(null));
82         }
83         return epsilonForm;
84     }
85
86     protected abstract <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args);
87
88
89     // Position //////////////////////////////////////////////////////////////////////////////
90
91     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
92     public class Position implements IntegerMappable {
93
94         private Forest zero = null;
95         public Forest zero() {
96             if (zero != null) return zero;
97             if (pos > 0) throw new Error();
98             return zero = rewrite(null);
99         }
100
101
102                 final int      pos;
103         private final Position next;
104                 final Forest[] holder;
105         
106         private Position(int pos) {
107             this.pos      = pos;
108             this.next     = pos==elements.length ? null : new Position(pos+1);
109             this.holder   = new Forest[elements.length];
110         }
111
112         boolean isFirst() { return pos==0; }
113
114         /** the element immediately after this Position, or null if this is the last Position */
115         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
116
117         /** the element which produces the sequence to which this Position belongs */
118         public Sequence owner() { return Sequence.this; }
119
120         /** the next Position (the Position after <tt>this.element()</tt>) */
121         public Position next() { return next; }
122
123         /** true iff this Position is the last one in the sequence */
124         public boolean isLast() { return next()==null; }
125
126         // Position /////////////////////////////////////////////////////////////////////////////////
127
128         final <T> Forest<T> rewrite(Input.Location loc) {
129             if (this==firstp()) return epsilonForm();
130             return rewrite2(loc);
131         }
132
133         final <T> Forest<T> rewrite2(Input.Location loc) {
134             for(int i=0; i<pos; i++) if (holder[i]==null) throw new Error("realbad " + i);
135             for(int i=pos; i<elements.length; i++) {
136                 if (holder[i]==null) holder[i] = elements[i].epsilonForm();
137                 if (holder[i]==null) throw new Error("bad " + i);
138             }
139             Forest<T> ret = Sequence.this.postReduce(loc, holder);
140             for(int k=0; k<pos; k++) holder[k] = null; // to help GC
141             return ret;
142         }
143
144         public String   toString() {
145             StringBuffer ret = new StringBuffer();
146             ret.append("<{");
147             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
148                 ret.append(' ');
149                 if (p==this) ret.append(" | ");
150                 if (p.element()!=null) ret.append(p.element());
151                 else                   ret.append(' ');
152             }
153             ret.append("}>");
154             return ret.toString();
155         }
156         private final int idx = master_position_idx++;
157         public int toInt() { return idx; }
158     }
159     private static int master_position_idx = 0;
160
161     // toString //////////////////////////////////////////////////////////////////////////////
162
163     public String toString() { return toString(new StringBuffer(), false).toString(); }
164     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
165     StringBuffer toString(StringBuffer sb, boolean spacing) {
166         for(int i=0; i<elements.length; i++) {
167             sb.append(elements[i].toString());
168             sb.append(' ');
169         }
170         return sb;
171     }
172
173
174     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
175
176     static class Constant extends Sequence {
177         private final Object result;
178         public Constant(Element[] e, Object result) { super(e); this.result = result; }
179         Sequence _clone() { return new Constant(elements, result); }
180         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
181             return (Forest<T>)Forest.leaf(loc, result);
182         }
183         static class Drop extends Constant {
184             Sequence _clone() { return new Drop(elements, lame); }
185             public Drop(Element[] e, boolean lame) {
186                 super(e, null);
187                 this.lame = lame;
188             }
189         }
190         static class Empty extends Sequence.Constant.Drop {
191             Sequence _clone() { return new Empty(); }
192             public Empty() { super(new Element[] { }, false); } }
193     }
194
195     static class Singleton extends Sequence {
196         private final int idx;
197         public Singleton(Element e) { this(new Element[] { e }, 0); }
198         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
199         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) { return (Forest<T>)Forest.singleton(loc, args[idx]); }
200         Sequence _clone() { return new Singleton(elements,idx); }
201     }
202
203     public static class Unwrap extends Sequence {
204         private boolean[] drops;
205         public Unwrap(Element[] e)                  { super(e); this.drops = null; }
206         public Unwrap(Element[] e, boolean[] drops) { super(e); this.drops = drops; }
207         Sequence _clone() { return new Unwrap(elements, drops); }
208         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
209             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
210             if (drops==null) return Forest.create(loc, null, args, true, false);
211             int count = 0;
212             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
213             Forest<T>[] args2 = new Forest[count];
214             int j = 0;
215             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
216             return Forest.create(loc, null, args2, true, false);            
217         }
218     }
219
220     static class RewritingSequence extends Sequence {
221         /*private*/public final Object tag;
222         private final boolean[] drops;
223         private int count = 0;
224         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
225         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
226         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
227             super(e);
228             this.tag = tag;
229             this.drops = drops == null ? new boolean[e.length] : drops;
230             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
231         }
232         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
233             Forest<T>[] args2 = new Forest[count];
234             int j = 0;
235             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
236             //System.out.println("reduce \""+tag+"\"");
237             return Forest.create(loc, (T)tag, args2, false, false);
238         }
239         public StringBuffer toString(StringBuffer sb, boolean spacing) {
240             int len = sb.length();
241             super.toString(sb, spacing);
242             len = sb.length()-len;
243             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
244             sb.append(" => ");
245             sb.append(tag);
246             return sb;
247         }
248     }
249 }