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