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