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