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