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