checkpoint harmony
[sbp.git] / src / edu / berkeley / sbp / Parser.java
1 package edu.berkeley.sbp;
2 import edu.berkeley.sbp.*;
3 import edu.berkeley.sbp.util.*;
4 import edu.berkeley.sbp.Sequence.Position;
5 import java.io.*;
6 import java.util.*;
7
8 /** a parser which translates streams of Tokens of type T into a Forest<R> */
9 public abstract class Parser<T extends Token, R> {
10
11     private final Table pt;
12
13     /** create a parser to parse the grammar with start symbol <tt>u</tt> */
14     protected Parser(Union u)  { this.pt = new Table(u, top()); }
15     protected Parser(Table pt) { this.pt = pt; }
16
17     /** implement this method to create the output forest corresponding to a lone shifted input token */
18     public abstract Forest<R> shiftedToken(T t, Token.Location loc);
19
20     /** this method must return an empty topology of the input token type */
21     public abstract Topology<T> top();
22
23     /** parse <tt>input</tt>, using the table <tt>pt</tt> to drive the parser */
24     public Forest<R> parse(Token.Stream<T> input) throws IOException, ParseFailed {
25         GSS gss = new GSS();
26         Token.Location loc = input.getLocation();
27         GSS.Phase current = gss.new Phase(null, this, null, input.next(1, 0, 0), loc, null);
28         current.newNode(null, Forest.leaf(null, null), pt.start, true);
29         int count = 1;
30         for(;;) {
31             loc = input.getLocation();
32             current.reduce();
33             Forest forest = current.token==null ? null : shiftedToken((T)current.token, loc);
34             GSS.Phase next = gss.new Phase(current, this, current, input.next(count, gss.resets, gss.waits), loc, forest);
35             count = next.size();
36             if (current.isDone()) return (Forest<R>)gss.finalResult;
37             current = next;
38         }
39     }
40
41     // Table //////////////////////////////////////////////////////////////////////////////
42
43     /** an SLR(1) parse table which may contain conflicts */
44     static class Table extends Walk.Cache {
45
46         public final Walk.Cache cache = this;
47
48         private void walk(Element e, HashSet<Element> hs) {
49             if (e==null) return;
50             if (hs.contains(e)) return;
51             hs.add(e);
52             if (e instanceof Atom) return;
53             for(Sequence s : (Union)e) {
54                 hs.add(s);
55                 for(Position p = s.firstp(); p != null; p = p.next())
56                     walk(p.element(), hs);
57             }
58         }
59
60         /** the start state */
61         public final State   start;
62
63         /** used to generate unique values for State.idx */
64         private int master_state_idx = 0;
65
66         /** construct a parse table for the given grammar */
67         public Table(Topology top) { this("s", top); }
68         public Table(String startSymbol, Topology top) { this(new Union(startSymbol), top); }
69         public Table(Union ux, Topology top) {
70             Union start0 = new Union("0");
71             start0.add(new Sequence.Singleton(ux, null, null));
72
73             for(Sequence s : start0) cache.eof.put(s, true);
74             cache.eof.put(start0, true);
75
76             // construct the set of states
77             HashMap<HashSet<Position>,State>   all_states    = new HashMap<HashSet<Position>,State>();
78             HashSet<Element>                   all_elements  = new HashSet<Element>();
79             walk(start0, all_elements);
80             for(Element e : all_elements)
81                 cache.ys.addAll(e, new Walk.YieldSet(e, cache).walk());
82             HashSet<Position> hp = new HashSet<Position>();
83             reachable(start0, hp);
84             this.start = new State(hp, all_states, all_elements);
85
86             // for each state, fill in the corresponding "row" of the parse table
87             for(State state : all_states.values())
88                 for(Position p : state.hs) {
89
90                     // the Grammar's designated "last position" is the only accepting state
91                     if (start0.contains(p.owner()) && p.next()==null)
92                         state.accept = true;
93
94                     if (isRightNullable(p)) {
95                         Walk.Follow wf = new Walk.Follow(top.empty(), p.owner(), all_elements, cache);
96                         Reduction red = new Reduction(p);
97
98                         Topology follow = wf.walk(p.owner());
99                         for(Position p2 = p; p2 != null && p2.element() != null; p2 = p2.next())
100                             follow = follow.intersect(new Walk.Follow(top.empty(), p2.element(), all_elements, cache).walk(p2.element()));
101                         state.reductions.put(follow, red);
102                         if (wf.includesEof()) state.eofReductions.add(red);
103                     }
104
105                     // if the element following this position is an atom, copy the corresponding
106                     // set of rows out of the "master" goto table and into this state's shift table
107                     if (p.element() != null && p.element() instanceof Atom)
108                         state.shifts.addAll(state.gotoSetTerminals.subset(((Atom)p.element())));
109                 }
110             for(State state : all_states.values()) {
111                 state.oreductions = state.reductions.optimize();
112                 state.oshifts = state.shifts.optimize();
113             }
114         }
115
116         private boolean isRightNullable(Position p) {
117             if (p.isLast()) return true;
118             if (!p.element().possiblyEpsilon(this)) return false;
119             return isRightNullable(p.next());
120         }
121
122         /** a single state in the LR table and the transitions possible from it */
123
124         public class State implements Comparable<Table.State>, IntegerMappable, Iterable<Position> {
125         
126             public  final     int               idx    = master_state_idx++;
127             private final     HashSet<Position> hs;
128
129             public transient HashMap<Element,State>          gotoSetNonTerminals = new HashMap<Element,State>();
130             private transient TopologicalBag<Token,State>     gotoSetTerminals    = new TopologicalBag<Token,State>();
131
132             private           TopologicalBag<Token,Reduction> reductions          = new TopologicalBag<Token,Reduction>();
133             private           HashSet<Reduction>              eofReductions       = new HashSet<Reduction>();
134             private           TopologicalBag<Token,State>     shifts              = new TopologicalBag<Token,State>();
135             private           boolean                         accept              = false;
136
137             private VisitableMap<Token,State> oshifts = null;
138             private VisitableMap<Token,Reduction> oreductions = null;
139
140             // Interface Methods //////////////////////////////////////////////////////////////////////////////
141
142             boolean             isAccepting()               { return accept; }
143             public Iterator<Position>  iterator()                  { return hs.iterator(); }
144
145             boolean             canShift(Token t)           { return oshifts.contains(t); }
146             <B,C> void          invokeShifts(Token t, Invokable<State,B,C> irbc, B b, C c) {
147                 oshifts.invoke(t, irbc, b, c);
148             }
149
150             boolean             canReduce(Token t)          { return t==null ? eofReductions.size()>0 : oreductions.contains(t); }
151             <B,C> void          invokeReductions(Token t, Invokable<Reduction,B,C> irbc, B b, C c) {
152                 if (t==null) for(Reduction r : eofReductions) irbc.invoke(r, b, c);
153                 else         oreductions.invoke(t, irbc, b, c);
154             }
155
156             // Constructor //////////////////////////////////////////////////////////////////////////////
157
158             /**
159              *  create a new state consisting of all the <tt>Position</tt>s in <tt>hs</tt>
160              *  @param hs           the set of <tt>Position</tt>s comprising this <tt>State</tt>
161              *  @param all_states   the set of states already constructed (to avoid recreating states)
162              *  @param all_elements the set of all elements (Atom instances need not be included)
163              *  
164              *   In principle these two steps could be merged, but they
165              *   are written separately to highlight these two facts:
166              * <ul>
167              * <li> Non-atom elements either match all-or-nothing, and do not overlap
168              *      with each other (at least not in the sense of which element corresponds
169              *      to the last reduction performed).  Therefore, in order to make sure we
170              *      wind up with the smallest number of states and shifts, we wait until
171              *      we've figured out all the token-to-position multimappings before creating
172              *      any new states
173              *  
174              * <li> In order to be able to run the state-construction algorithm in a single
175              *      shot (rather than repeating until no new items appear in any state set),
176              *      we need to use the "yields" semantics rather than the "produces" semantics
177              *      for non-Atom Elements.
178              *  </ul>
179              */
180             public State(HashSet<Position> hs,
181                          HashMap<HashSet<Position>,State> all_states,
182                          HashSet<Element> all_elements) {
183                 this.hs = hs;
184
185                 // register ourselves in the all_states hash so that no
186                 // two states are ever created with an identical position set
187                 all_states.put(hs, this);
188
189                 // Step 1a: examine all Position's in this state and compute the mappings from
190                 //          sets of follow tokens (tokens which could follow this position) to sets
191                 //          of _new_ positions (positions after shifting).  These mappings are
192                 //          collectively known as the _closure_
193
194                 TopologicalBag<Token,Position> bag0 = new TopologicalBag<Token,Position>();
195                 for(Position position : hs) {
196                     if (position.isLast() || !(position.element() instanceof Atom)) continue;
197                     Atom a = (Atom)position.element();
198                     HashSet<Position> hp = new HashSet<Position>();
199                     reachable(position.next(), hp);
200                     bag0.addAll(a, hp);
201                 }
202
203                 // Step 1b: for each _minimal, contiguous_ set of characters having an identical next-position
204                 //          set, add that character set to the goto table (with the State corresponding to the
205                 //          computed next-position set).
206
207                 for(Topology<Token> r : bag0) {
208                     HashSet<Position> h = new HashSet<Position>();
209                     for(Position p : bag0.getAll(r)) h.add(p);
210                     gotoSetTerminals.put(r, all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h));
211                 }
212
213                 // Step 2: for every non-Atom element (ie every Element which has a corresponding reduction),
214                 //         compute the closure over every position in this set which is followed by a symbol
215                 //         which could yield the Element in question.
216                 //
217                 //         "yields" [in one or more step] is used instead of "produces" [in exactly one step]
218                 //         to avoid having to iteratively construct our set of States as shown in most
219                 //         expositions of the algorithm (ie "keep doing XYZ until things stop changing").
220                 HashMapBag<Element,Position> move = new HashMapBag<Element,Position>();
221                 for(Position p : hs) {
222                     Element e = p.element();
223                     if (e==null) continue;
224                     for(Element y : cache.ys.getAll(e)) {
225                         HashSet<Position> hp = new HashSet<Position>();
226                         reachable(p.next(), hp);
227                         move.addAll(y, hp);
228                     }
229                 }
230                 for(Element y : move) {
231                     HashSet<Position> h = move.getAll(y);
232                     State s = all_states.get(h) == null ? new State(h, all_states, all_elements) : all_states.get(h);
233                     gotoSetNonTerminals.put(y, s);
234                 }
235             }
236
237             public String toString() {
238                 StringBuffer ret = new StringBuffer();
239                 ret.append("state["+idx+"]: ");
240                 for(Position p : this) ret.append("{"+p+"}  ");
241                 return ret.toString();
242             }
243
244             public int compareTo(Table.State s) { return idx==s.idx ? 0 : idx < s.idx ? -1 : 1; }
245             public int toInt() { return idx; }
246         }
247
248         /**
249          *  the information needed to perform a reduction; copied here to
250          *  avoid keeping references to <tt>Element</tt> objects in a Table
251          */
252         public class Reduction {
253             // FIXME: cleanup; almost everything in here could go in either Sequence.Position.getRewrite() or else in GSS.Reduct
254             /*private*/ final Position position;
255             public int hashCode() { return position.hashCode(); }
256             public boolean equals(Object o) {
257                 if (o==null) return false;
258                 if (o==this) return true;
259                 if (!(o instanceof Reduction)) return false;
260                 Reduction r = (Reduction)o;
261                 return r.position == position;
262             }
263             public Reduction(Position p) {
264                 this.position = p;
265             }
266             public String toString() { return "[reduce " + position + "]"; }
267
268             private Forest zero = null;
269             public Forest zero() {
270                 if (zero != null) return zero;
271                 if (position.pos > 0) throw new Error();
272                 return zero = position.rewrite(null);
273             }
274
275         }
276     }
277
278     private static final Forest[] emptyForestArray = new Forest[0];
279
280
281     // Helpers //////////////////////////////////////////////////////////////////////////////
282
283     private static void reachable(Element e, HashSet<Position> h) {
284         if (e instanceof Atom) return;
285         for(Sequence s : ((Union)e))
286             reachable(s.firstp(), h);
287     }
288     private static void reachable(Position p, HashSet<Position> h) {
289         if (h.contains(p)) return;
290         h.add(p);
291         if (p.element() != null) reachable(p.element(), h);
292     }
293
294 }