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     /** the empty sequence (matches the empty string) */
16     public static final Sequence empty = new Sequence.Constant.Empty();
17
18     /** after matching the sequence, do not add anything to the output tree */
19     public static Sequence drop(Element[] e, HashSet<Sequence> and, HashSet<Sequence> not, boolean lame) { return new Constant.Drop(e, and, not, lame); }
20
21     /** after matching the sequence, insert a constant into the output tree */
22     public static Sequence constant(Element[] e, Object o, HashSet<Sequence> and, HashSet<Sequence> not) { return new Constant(e, o, and, not); }
23
24     /** after matching the sequence, place the result of the <tt>idx</tt>th match in the output tree */
25     public static Sequence singleton(Element[] e, int idx, HashSet<Sequence> and, HashSet<Sequence> not) { return new Singleton(e, idx, and, not); }
26
27     /**
28      *  after matching the sequence, create the specified output tree
29      *  @param tag   the tag for the output tree
30      *  @param e     the elements to match
31      *  @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
32      **/
33     public static Sequence rewritingSequence(Object tag, Element[] e, boolean[] drops, HashSet<Sequence> and, HashSet<Sequence> not) {
34         return new RewritingSequence(tag, e, drops, and, not); }
35
36     ////////////////////////////////////////////////////////////////////////////////
37
38     public Element noFollow = null;
39     public String name = null;
40     public void setName(String name) { this.name = name; }
41     public final Topology noFollow() { return noFollow==null ? null : noFollow.toAtom(); }
42
43     Topology toAtom() {
44         if (elements.length!=1) throw new RuntimeException("cannot invoke toAtom() on a Sequence with " + elements.length + " elements: " + this);
45         return elements[0].toAtom();
46     }
47
48     protected final Element[] elements;
49
50           HashSet<Sequence> needed;
51           HashSet<Sequence> hated;
52     final HashSet<Sequence> needs;
53     final HashSet<Sequence> hates;
54     public boolean           lame  = false;
55
56     final Position          firstp;
57     Position firstp() { return firstp; }
58
59     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
60     protected Sequence(Element[] elements, HashSet<Sequence> and, HashSet<Sequence> not) {
61         this.needs = and==null ? new HashSet<Sequence>() : and;
62         this.hates = not==null ? new HashSet<Sequence>() : not;
63         if (this.needs != null)
64             for(Sequence s : this.needs)
65                 (s.needed==null?(s.needed=new HashSet<Sequence>()):s.needed).add(this);
66         if (this.hates != null)
67             for(Sequence s : this.hates)
68                 (s.hated==null?(s.hated=new HashSet<Sequence>()):s.hated).add(this);
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, HashSet<Sequence> and, HashSet<Sequence> not) { super(e, and, not); this.result = result; }
177         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
178             return (Forest<T>)Forest.leaf(loc, result);
179         }
180         static class Drop extends Constant {
181             public Drop(Element[] e, HashSet<Sequence> and, HashSet<Sequence> not, boolean lame) {
182                 super(e, null, and, not);
183                 this.lame = lame;
184             }
185         }
186         static class Empty extends Sequence.Constant.Drop { public Empty() { super(new Element[] { }, null, null, false); } }
187     }
188
189     static class Singleton extends Sequence {
190         private final int idx;
191         public Singleton(Element e, HashSet<Sequence> and, HashSet<Sequence> not) { this(new Element[] { e }, 0, and, not); }
192         public Singleton(Element[] e, int idx, HashSet<Sequence> and, HashSet<Sequence> not) { super(e, and, not); this.idx = idx; }
193         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) { return (Forest<T>)Forest.singleton(loc, args[idx]); }
194     }
195
196     public static class Unwrap extends Sequence {
197         private boolean[] drops;
198         public Unwrap(Element[] e, HashSet<Sequence> and, HashSet<Sequence> not)                  { super(e, and, not); this.drops = null; }
199         public Unwrap(Element[] e, boolean[] drops, HashSet<Sequence> and, HashSet<Sequence> not) { super(e, and, not); this.drops = drops; }
200         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
201             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
202             if (drops==null) return Forest.create(loc, null, args, true, false);
203             int count = 0;
204             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
205             Forest<T>[] args2 = new Forest[count];
206             int j = 0;
207             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
208             return Forest.create(loc, null, args2, true, false);            
209         }
210     }
211
212     static class RewritingSequence extends Sequence {
213         /*private*/public final Object tag;
214         private final boolean[] drops;
215         private int count = 0;
216         public RewritingSequence(Object tag, Element[] e, HashSet<Sequence> and, HashSet<Sequence> not) { this(tag, e, null, and, not); }
217         public RewritingSequence(Object tag, Element[] e, boolean[] drops, HashSet<Sequence> and, HashSet<Sequence> not) {
218             super(e, and, not);
219             this.tag = tag;
220             this.drops = drops == null ? new boolean[e.length] : drops;
221             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
222         }
223         public <T> Forest<T> postReduce(Input.Location loc, Forest<T>[] args) {
224             Forest<T>[] args2 = new Forest[count];
225             int j = 0;
226             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
227             //System.out.println("reduce \""+tag+"\"");
228             return Forest.create(loc, (T)tag, args2, false, false);
229         }
230         public StringBuffer toString(StringBuffer sb, boolean spacing) {
231             int len = sb.length();
232             super.toString(sb, spacing);
233             len = sb.length()-len;
234             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
235             sb.append(" => ");
236             sb.append(tag);
237             return sb;
238         }
239     }
240 }