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