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