rename edu.berkeley.sbp.Cache to Grammar
[sbp.git] / src / edu / berkeley / sbp / Sequence.java
1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.util.*;
5 import edu.berkeley.sbp.*;
6 import edu.berkeley.sbp.*;
7 import java.io.*;
8 import java.util.*;
9 import java.lang.reflect.*;
10 import java.lang.ref.*;
11
12 /** <font color=green>juxtaposition; zero or more adjacent Elements; can specify a rewriting</font> */
13 public abstract class Sequence implements Iterable<Element>, SequenceOrElement {
14
15     protected final Element[] elements;
16
17     boolean needed_or_hated = false;
18     boolean in_a_union = false;
19
20     final HashSet<Sequence> needs  = new HashSet<Sequence>();
21     final HashSet<Sequence> hates  = new HashSet<Sequence>();
22
23     // FIXME: these are ugly -- migrate into Grammar
24     HashMap<Sequence,Boolean> canNeed = new HashMap<Sequence,Boolean>();
25     HashMap<Sequence,Boolean> canKill = new HashMap<Sequence,Boolean>();
26
27     final Position          firstp;
28
29     Atom follow = null;
30
31     // Static Constructors //////////////////////////////////////////////////////////////////////////////
32
33     /** create a sequence of one element */
34     public static Sequence create(Element e) { return create(new Element[] { e }, 0); }
35
36     /** create a sequence which drops the result of all but one of its element */
37     public static Sequence create(Element[] e, int which) { return new Singleton(e, which); }
38
39     /** create a sequence which always evaluates to a constant result  */
40     public static Sequence create(Element[] e, Object result) { return new Constant(e, result); }
41
42     /**
43      *  create a sequence (general form)
44      *  @param head   the head of the output tree
45      *  @param e      the elements to match
46      *  @param drop   only elements of <tt>e</tt> whose corresponding <tt>boolean</tt> in <tt>drops</tt>
47      *                is <i>false</i> will be included in the output tree
48      *  @param foster if true, all children of the last child (ie
49      *                grandchildren) are promoted to children of this
50      *                node; this is very useful for matching repetitions
51      **/
52     public static Sequence create(Object head, Element[] e, boolean[] drop, boolean foster) {
53         return foster
54             ? new Unwrap(e, head, drop)
55             : new RewritingSequence(head, e, drop);
56     }
57
58     /** return a new sequence identical to this one, but with a positive conjunct <tt>s</tt> */
59     public Sequence and(Sequence s) {
60         if (s.in_a_union)
61             throw new RuntimeException("you may not use a sequence as a conjunct if it belongs to a Union");
62         Sequence ret = dup();
63         ret.needs.add(s);
64         s.needed_or_hated=true;
65         return ret;
66     }
67
68     /** return a new sequence identical to this one, but with a negative conjunct <tt>s</tt> */
69     public Sequence andnot(Sequence s) {
70         if (s.in_a_union)
71             throw new RuntimeException("you may not use a sequence as a conjunct if it belongs to a Union");
72         Sequence ret = dup();
73         ret.hates.add(s);
74         s.needed_or_hated=true;
75         return ret;
76     }
77
78     /** return a new sequence identical to this one, but with a follow-set restricted to <tt>a</tt> */
79     public Sequence followedBy(Atom a) { Sequence ret = dup(); ret.follow = a; return ret; }
80
81     ////////////////////////////////////////////////////////////////////////////////
82
83     abstract Sequence _clone();
84     private Sequence dup() {
85         Sequence ret = _clone();
86         for(Sequence s : needs) { ret.needs.add(s); }
87         for(Sequence s : hates) { ret.hates.add(s); }
88         ret.follow = follow;
89         return ret;
90     }
91
92     Iterable<Sequence> needs() { return needs; }
93     Iterable<Sequence> hates() { return hates; }
94
95     Position firstp() { return firstp; }
96     Position lastp() { return firstp().last(); }
97
98     public Iterator<Element> iterator()    { return new ArrayIterator<Element>(elements); }
99     protected Sequence(Element[] elements) {
100         this.elements = elements;
101         for(int i=0; i<elements.length; i++)
102             if (elements[i]==null)
103                 throw new RuntimeException("cannot have nulls in a sequence: " + this);
104         this.firstp = new Position(0, null);
105     }
106
107     abstract Forest epsilonForm(Input.Region loc, Grammar cache);
108
109     protected abstract <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p);
110
111
112     // Position //////////////////////////////////////////////////////////////////////////////
113
114     /** the imaginary position before or after an element of a sequence; corresponds to an "LR item" */
115     class Position implements IntegerMappable {
116
117         public int ord = -1;
118
119         private Forest zero = null;
120         /*
121         public Forest zero(Input.Region reg) {
122             if (zero != null) return zero;
123             if (pos > 0) throw new RuntimeException("Position.zero(): pos>0");
124             return zero = rewrite(reg);
125         }
126         */
127                 final int      pos;
128         private final Position next;
129         private final Position prev;
130                 final Forest[] holder;
131         
132         private Position(int pos, Position prev) {
133             this.pos      = pos;
134             this.next     = pos==elements.length ? null : new Position(pos+1, this);
135             this.holder   = new Forest[elements.length];
136             this.prev     = prev;
137         }
138
139         boolean isFirst() { return pos==0; }
140
141         /** the element immediately after this Position, or null if this is the last Position */
142         public Element  element() { return pos>=elements.length ? null : elements[pos]; }
143
144         /** the element which produces the sequence to which this Position belongs */
145         public Sequence owner() { return Sequence.this; }
146
147         /** the next Position (the Position after <tt>this.element()</tt>) */
148         public Position next() { return next; }
149
150         /** true iff this Position is the last one in the sequence */
151         public boolean isLast() { return next()==null; }
152         public Position last() { return isLast() ? this : next().last(); }
153         public Position prev() { return prev; }
154
155         // Position /////////////////////////////////////////////////////////////////////////////////
156
157         final <T> Forest<T> rewrite(Input.Region loc, Grammar cache) {
158             if (this==firstp()) epsilonForm(loc, cache);
159             for(int i=0; i<pos; i++) if (holder[i]==null) throw new Error("realbad " + i);
160             for(int i=pos; i<elements.length; i++) {
161                 if (holder[i]==null) holder[i] = ((Union)elements[i]).epsilonForm(loc, cache);
162                 if (holder[i]==null) throw new Error("bad");
163             }
164             return Sequence.this.postReduce(loc, holder, this);
165         }
166
167         public String   toString() {
168             StringBuffer ret = new StringBuffer();
169             ret.append("<{");
170             for(Position p = Sequence.this.firstp(); p != null; p = p.next()) {
171                 ret.append(' ');
172                 if (p==this) ret.append(" | ");
173                 if (p.element()!=null) ret.append(p.element());
174                 else                   ret.append(' ');
175             }
176             ret.append("}>");
177             return ret.toString();
178         }
179         private final int idx = master_position_idx++;
180         public int toInt() { return idx; }
181     }
182     private static int master_position_idx = 0;
183
184     // toString //////////////////////////////////////////////////////////////////////////////
185
186     public String toString() { return toString(new StringBuffer(), false).toString(); }
187     StringBuffer toString(StringBuffer sb) { return toString(sb, true); }
188     StringBuffer toString(StringBuffer sb, boolean spacing) {
189         for(int i=0; i<elements.length; i++) {
190             sb.append(elements[i]+"");
191             sb.append(' ');
192         }
193         if (follow != null) {
194             sb.append("-> ");
195             sb.append(follow);
196         }
197         for(Sequence s : needs) {
198             sb.append("& ");
199             sb.append(s);
200         }
201         for(Sequence s : hates) {
202             sb.append("&~ ");
203             sb.append(s);
204         }
205         return sb;
206     }
207
208
209     // Specialized Subclasses //////////////////////////////////////////////////////////////////////////////
210
211     static class Constant extends Sequence {
212         private final Object result;
213         public Constant(Element[] e, Object result) {
214             super(e);
215             if (result==null) throw new Error("constant sequences may not have result==null");
216             this.result = result;
217         }
218         Sequence _clone() { return new Constant(elements, result); }
219         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
220             return (Forest<T>)Forest.create(loc, result, null, false);
221         }
222         Forest epsilonForm(Input.Region loc, Grammar cache) {
223             return Forest.create(loc, result, null, false);
224         }
225     }
226
227     static class Singleton extends Sequence {
228         private final int idx;
229         public Singleton(Element e) { this(new Element[] { e }, 0); }
230         public Singleton(Element[] e, int idx) { super(e); this.idx = idx; }
231         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) { return args[idx]; }
232         Sequence _clone() { return new Singleton(elements,idx); }
233         Forest epsilonForm(Input.Region loc, Grammar cache) {
234             return ((Union)elements[idx]).epsilonForm(loc, cache);
235         }
236     }
237
238     static class Unwrap extends Sequence {
239         private boolean[] drops;
240         private final Object tag;
241         public Unwrap(Element[] e, Object tag)                  { this(e, tag, null); }
242         public Unwrap(Element[] e, Object tag, boolean[] drops) { super(e); this.drops = drops; this.tag = tag; }
243         Sequence _clone() { return new Unwrap(elements, tag, drops); }
244         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
245             for(int i=0; i<args.length; i++) if (args[i]==null) throw new Error();
246             if (drops==null) return Forest.create(loc, (T)tag, args, true);
247             int count = 0;
248             for(int i=0; i<drops.length; i++) if (!drops[i]) count++;
249             Forest<T>[] args2 = new Forest[count];
250             int j = 0;
251             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
252             return Forest.create(loc, (T)tag, args2, true);
253         }
254         Forest epsilonForm(Input.Region loc, Grammar cache) {
255             return Forest.create(loc, tag, new Forest[0], false);
256         }
257     }
258
259     static class RewritingSequence extends Sequence {
260         private Object tag;
261         private final boolean[] drops;
262         private int count = 0;
263         Sequence _clone() { return new RewritingSequence(tag, elements, drops); }
264         public RewritingSequence(Object tag, Element[] e) { this(tag, e, null); }
265         public RewritingSequence(Object tag, Element[] e, boolean[] drops) {
266             super(e);
267             if (tag==null) throw new Error();
268             this.tag = tag;
269             this.drops = drops == null ? new boolean[e.length] : drops;
270             for(int i=0; i<this.drops.length; i++) if (!this.drops[i]) count++;
271         }
272         public <T> Forest<T> postReduce(Input.Region loc, Forest<T>[] args, Position p) {
273             Forest<T>[] args2 = new Forest[count];
274             int j = 0;
275             for(int i=0; i<args.length; i++) if (!drops[i]) args2[j++] = args[i];
276             return Forest.create(loc, (T)tag, args2, false);
277         }
278         public StringBuffer toString(StringBuffer sb, boolean spacing) {
279             int len = sb.length();
280             if (tag != null)
281                 sb.append("\""+StringUtil.escapify(tag.toString(),"\"\r\n")+"\":: ");
282             super.toString(sb, spacing);
283             len = sb.length()-len;
284             if (spacing) for(int i=0; i<50-len; i++) sb.append(' ');
285             return sb;
286         }
287         Forest epsilonForm(Input.Region loc, Grammar cache) {
288             return Forest.create(loc, tag, new Forest[0], false);
289         }
290     }
291
292 }