adf93fa64d35b8c645d7e3c72928f8585fdf2e03
[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(Token.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 {
91
92                 final int      pos;
93         private final Position next;
94                 final Forest[] holder;
95         
96         private Position(int pos) {
97             this.pos      = pos;
98             this.next     = pos==elements.length ? null : new Position(pos+1);
99             this.holder   = new Forest[elements.length];
100         }
101
102         boolean isFirst() { return pos==0; }
103         boolean isRightNullable(Walk.Cache cache) {
104             if (isLast()) return true;
105             if (!element().possiblyEpsilon(cache)) return false;
106             return next().isRightNullable(cache);
107         }
108
109         /** the element immediately after this Position, or null if this is the last Position */
110         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
111
112         /** the element which produces the sequence to which this Position belongs */
113         public Sequence owner() { return Sequence.this; }
114
115         /** the next Position (the Position after <tt>this.element()</tt>) */
116         public Position next() { return next; }
117
118         /** true iff this Position is the last one in the sequence */
119         public boolean isLast() { return next()==null; }
120
121         // Reduction /////////////////////////////////////////////////////////////////////////////////
122
123         final <T> Forest<T> rewrite(Token.Location loc) {
124             if (this==firstp()) return epsilonForm();
125             return rewrite2(loc);
126         }
127
128         final <T> Forest<T> rewrite2(Token.Location loc) {
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);
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().possiblyEpsilon(null) ? "["+p.element()+"]" : p.element());
146                 else                   ret.append(' ');
147             }
148             ret.append("}>");
149             return ret.toString();
150         }
151     }
152
153
154     // toString //////////////////////////////////////////////////////////////////////////////
155
156     public String toString() { return toString(new StringBuffer(), false).toString(); }
157     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
158     StringBuffer toString(StringBuffer sb, boolean spacing) {
159         for(int i=0; i<elements.length; i++) {
160             sb.append(elements[i].toString());
161             sb.append(' ');
162         }
163         return sb;
164     }
165
166
167     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
168
169     static class Constant extends Sequence {
170         private final Object result;
171         public Constant(Element[] e, Object result, HashSet<Sequence> and, HashSet<Sequence> not) { super(e, and, not); this.result = result; }
172         public <T> Forest<T> postReduce(Token.Location loc, Forest<T>[] args) {
173             return (Forest<T>)Forest.leaf(loc, result);
174         }
175         static class Drop extends Constant {
176             public Drop(Element[] e, HashSet<Sequence> and, HashSet<Sequence> not, boolean lame) {
177                 super(e, null, and, not);
178                 this.lame = lame;
179             }
180         }
181         static class Empty extends Sequence.Constant.Drop { public Empty() { super(new Element[] { }, null, null, false); } }
182     }
183
184     static class Singleton extends Sequence {
185         private final int idx;
186         public Singleton(Element e, HashSet<Sequence> and, HashSet<Sequence> not) { this(new Element[] { e }, 0, and, not); }
187         public Singleton(Element[] e, int idx, HashSet<Sequence> and, HashSet<Sequence> not) { super(e, and, not); this.idx = idx; }
188         public <T> Forest<T> postReduce(Token.Location loc, Forest<T>[] args) { return (Forest<T>)Forest.singleton(loc, args[idx]); }
189     }
190
191     public static class Unwrap extends Sequence {
192         private boolean[] drops;
193         public Unwrap(Element[] e, HashSet<Sequence> and, HashSet<Sequence> not)                  { super(e, and, not); this.drops = null; }
194         public Unwrap(Element[] e, boolean[] drops, HashSet<Sequence> and, HashSet<Sequence> not) { super(e, and, not); this.drops = drops; }
195         public <T> Forest<T> postReduce(Token.Location loc, Forest<T>[] args) {
196             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
197             if (drops==null) return Forest.create(loc, null, args, true, false);
198             int count = 0;
199             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
200             Forest<T>[] args2 = new Forest[count];
201             int j = 0;
202             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
203             return Forest.create(loc, null, args2, true, false);            
204         }
205     }
206
207     static class RewritingSequence extends Sequence {
208         /*private*/public final Object tag;
209         private final boolean[] drops;
210         private int count = 0;
211         public RewritingSequence(Object tag, Element[] e, HashSet<Sequence> and, HashSet<Sequence> not) { this(tag, e, null, and, not); }
212         public RewritingSequence(Object tag, Element[] e, boolean[] drops, HashSet<Sequence> and, HashSet<Sequence> not) {
213             super(e, and, not);
214             this.tag = tag;
215             this.drops = drops == null ? new boolean[e.length] : drops;
216             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
217         }
218         public <T> Forest<T> postReduce(Token.Location loc, Forest<T>[] args) {
219             Forest<T>[] args2 = new Forest[count];
220             int j = 0;
221             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
222             //System.out.println("reduce \""+tag+"\"");
223             return Forest.create(loc, (T)tag, args2, false, false);
224         }
225         public StringBuffer toString(StringBuffer sb, boolean spacing) {
226             int len = sb.length();
227             super.toString(sb, spacing);
228             len = sb.length()-len;
229             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
230             sb.append(" => ");
231             sb.append(tag);
232             return sb;
233         }
234     }
235 }