Teuchos - Trilinos Tools Package Version of the Day
Loading...
Searching...
No Matches
Teuchos_make_lalr1_parser.cpp
1// @HEADER
2// *****************************************************************************
3// Teuchos: Common Tools Package
4//
5// Copyright 2004 NTESS and the Teuchos contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8// @HEADER
9
10#include "Teuchos_make_lalr1_parser.hpp"
11
12#include <map>
13#include <iostream>
14#include <cstdlib>
15#include <queue>
16#include <algorithm>
17#include <fstream>
18
19#include "Teuchos_vector.hpp"
20#include "Teuchos_Graph.hpp"
21#include "Teuchos_stack.hpp"
22#include "Teuchos_set.hpp"
23
24namespace Teuchos {
25
26/* The LALR(1) parser construction implemented here is based on
27 David Pager's work:
28
29 Pager, David.
30 "The lane-tracing algorithm for constructing LR (k) parsers
31 and ways of enhancing its efficiency."
32 Information Sciences 12.1 (1977): 19-42.
33
34 The identifiers used in this code are consistent with the terminology
35 in that paper, except where we bring in FIRST set terminology, which
36 Pager doesn't go into detail about. */
37
38Config::Config(int p, int d):
39 production(p),
40 dot(d)
41{
42}
43
44StateConfig::StateConfig(int s, int cis):
45 state(s),
46 config_in_state(cis)
47{
48}
49
50void swap(StateInProgress& a, StateInProgress& b) {
51 using std::swap;
52 swap(a.configs, b.configs);
53 swap(a.actions, b.actions);
54}
55
56// expand the grammar productions into marked productions
57static Configs make_configs(Grammar const& g) {
58 Configs configs;
59 for (int i = 0; i < Teuchos::size(g.productions); ++i) {
60 const Grammar::Production& production = at(g.productions, i);
61 for (int j = 0; j <= Teuchos::size(production.rhs); ++j) {
62 configs.push_back(Config(i,j));
63 }
64 }
65 return configs;
66}
67
68static Graph get_left_hand_sides_to_start_configs(
69 Configs const& cs, Grammar const& grammar) {
70 Graph lhs2sc = make_graph_with_nnodes(grammar.nsymbols);
71 for (int c_i = 0; c_i < Teuchos::size(cs); ++c_i) {
72 const Config& c = at(cs, c_i);
73 if (c.dot > 0) continue;
74 int p_i = c.production;
75 const Grammar::Production& p = at(grammar.productions, p_i);
76 add_edge(lhs2sc, p.lhs, c_i);
77 }
78 return lhs2sc;
79}
80
81struct StateCompare {
82 typedef StateInProgress const* Value;
83 bool operator()(Value const& a, Value const& b) const {
84 return a->configs < b->configs;
85 }
86};
87
88typedef std::map<StateInProgress const*, int, StateCompare> StatePtr2StateIndex;
89
90static void close(StateInProgress& state,
91 Configs const& cs, Grammar const& grammar,
92 Graph const& lhs2sc) {
93 std::queue<int> config_q;
94 std::set<int> config_set;
95 for (std::vector<int>::const_iterator it = state.configs.begin();
96 it != state.configs.end(); ++it) {
97 int config_i = *it;
98 config_q.push(config_i);
99 TEUCHOS_ASSERT(!config_set.count(config_i));
100 config_set.insert(config_i);
101 }
102 while (!config_q.empty()) {
103 int config_i = config_q.front(); config_q.pop();
104 const Config& config = at(cs, config_i);
105 int prod_i = config.production;
106 const Grammar::Production& prod = at(grammar.productions, prod_i);
107 if (config.dot == Teuchos::size(prod.rhs)) continue;
108 int symbol_after_dot = at(prod.rhs, config.dot);
109 if (is_terminal(grammar, symbol_after_dot)) continue;
110 const NodeEdges& edges = get_edges(lhs2sc, symbol_after_dot);
111 for (NodeEdges::const_iterator it = edges.begin();
112 it != edges.end(); ++it) {
113 int sc = *it;
114 if (!config_set.count(sc)) {
115 config_set.insert(sc);
116 config_q.push(sc);
117 }
118 }
119 }
120 state.configs.assign(config_set.begin(), config_set.end());
121}
122
123static void add_back(StatesInProgress& sips, StateInProgress& sip) {
124 using std::swap;
125 StateInProgressPtr ptr(new StateInProgress());
126 swap(*ptr, sip);
127 sips.push_back(ptr);
128}
129
130static void add_reduction_actions(StatesInProgress& states,
131 Configs const& cs, Grammar const& grammar) {
132 for (StatesInProgress::iterator it = states.begin();
133 it != states.end(); ++it) {
134 StateInProgressPtr& state_uptr = *it;
135 StateInProgress& state = *state_uptr;
136 for (std::vector<int>::const_iterator it2 = state.configs.begin();
137 it2 != state.configs.end(); ++it2) {
138 int config_i = *it2;
139 const Config& config = at(cs, config_i);
140 int prod_i = config.production;
141 const Grammar::Production& prod = at(grammar.productions, prod_i);
142 if (config.dot != Teuchos::size(prod.rhs)) continue;
143 ActionInProgress reduction;
144 reduction.action.kind = ACTION_REDUCE;
145 reduction.action.production = config.production;
146 state.actions.push_back(reduction);
147 }
148 }
149}
150
151static void set_lr0_contexts(
152 StatesInProgress& states,
153 Grammar const& grammar) {
154 for (StatesInProgress::iterator it = states.begin();
155 it != states.end(); ++it) {
156 StateInProgressPtr& state_uptr = *it;
157 StateInProgress& state = *state_uptr;
158 for (StateInProgress::Actions::iterator it2 = state.actions.begin();
159 it2 != state.actions.end(); ++it2) {
160 ActionInProgress& action = *it2;
161 if (action.action.kind != ACTION_REDUCE) continue;
162 if (action.action.production == get_accept_production(grammar)) {
163 action.context.insert(get_end_terminal(grammar));
164 } else {
165 for (int terminal = 0; terminal < grammar.nterminals; ++terminal) {
166 action.context.insert(terminal);
167 }
168 }
169 }
170 }
171}
172
173static StatesInProgress make_lr0_parser(Configs const& cs, Grammar const& grammar,
174 Graph const& lhs2sc) {
175 StatesInProgress states;
176 StatePtr2StateIndex state_ptrs2idxs;
177 std::queue<int> state_q;
178 { /* start state */
179 StateInProgress start_state;
180 int accept_nt = get_accept_nonterminal(grammar);
181 /* there should only be one start configuration for the accept symbol */
182 int start_accept_config = get_edges(lhs2sc, accept_nt).front();
183 start_state.configs.push_back(start_accept_config);
184 close(start_state, cs, grammar, lhs2sc);
185 int start_state_i = Teuchos::size(states);
186 state_q.push(start_state_i);
187 add_back(states, start_state);
188 state_ptrs2idxs[states.back().get()] = start_state_i;
189 }
190 while (!state_q.empty()) {
191 int state_i = state_q.front(); state_q.pop();
192 StateInProgress& state = *at(states, state_i);
193 std::set<int> transition_symbols;
194 for (std::vector<int>::const_iterator it = state.configs.begin();
195 it != state.configs.end(); ++it) {
196 int config_i = *it;
197 const Config& config = at(cs, config_i);
198 int prod_i = config.production;
199 const Grammar::Production& prod = at(grammar.productions, prod_i);
200 if (config.dot == Teuchos::size(prod.rhs)) continue;
201 int symbol_after_dot = at(prod.rhs, config.dot);
202 transition_symbols.insert(symbol_after_dot);
203 }
204 for (std::set<int>::const_iterator it = transition_symbols.begin();
205 it != transition_symbols.end(); ++it) {
206 int transition_symbol = *it;
207 StateInProgress next_state;
208 for (std::vector<int>::const_iterator it2 = state.configs.begin();
209 it2 != state.configs.end(); ++it2) {
210 int config_i = *it2;
211 const Config& config = at(cs, config_i);
212 int prod_i = config.production;
213 const Grammar::Production& prod = at(grammar.productions, prod_i);
214 if (config.dot == Teuchos::size(prod.rhs)) continue;
215 int symbol_after_dot = at(prod.rhs, config.dot);
216 if (symbol_after_dot != transition_symbol) continue;
217 /* transition successor should just be the next index */
218 int next_config_i = config_i + 1;
219 next_state.configs.push_back(next_config_i);
220 }
221 close(next_state, cs, grammar, lhs2sc);
222 StatePtr2StateIndex::iterator it2 = state_ptrs2idxs.find(&next_state);
223 int next_state_i;
224 if (it2 == state_ptrs2idxs.end()) {
225 next_state_i = Teuchos::size(states);
226 state_q.push(next_state_i);
227 add_back(states, next_state);
228 state_ptrs2idxs[states.back().get()] = next_state_i;
229 } else {
230 next_state_i = it2->second;
231 }
232 ActionInProgress transition;
233 transition.action.kind = ACTION_SHIFT;
234 transition.action.next_state = next_state_i;
235 transition.context.insert(transition_symbol);
236 state.actions.push_back(transition);
237 }
238 }
239 add_reduction_actions(states, cs, grammar);
240 set_lr0_contexts(states, grammar);
241 return states;
242}
243
244static Graph get_productions_by_lhs(Grammar const& grammar) {
245 int nsymbols = grammar.nsymbols;
246 Graph lhs2prods = make_graph_with_nnodes(nsymbols);
247 for (int prod_i = 0; prod_i < Teuchos::size(grammar.productions); ++prod_i) {
248 const Grammar::Production& prod = at(grammar.productions, prod_i);
249 add_edge(lhs2prods, prod.lhs, prod_i);
250 }
251 return lhs2prods;
252}
253
254/* compute a graph where symbols are graph nodes, and
255 there exists an edge (A, B) if B appears in the RHS of
256 any production in which A is the LHS */
257static Graph get_symbol_graph(Grammar const& grammar, Graph const& lhs2prods) {
258 int nsymbols = grammar.nsymbols;
259 Graph out = make_graph_with_nnodes(nsymbols);
260 for (int lhs = 0; lhs < nsymbols; ++lhs) {
261 std::set<int> dependees;
262 for (int i = 0; i < count_edges(lhs2prods, lhs); ++i) {
263 int prod_i = at(lhs2prods, lhs, i);
264 const Grammar::Production& prod = at(grammar.productions, prod_i);
265 for (int j = 0; j < Teuchos::size(prod.rhs); ++j) {
266 int rhs_symb = at(prod.rhs, j);
267 dependees.insert(rhs_symb);
268 }
269 }
270 at(out, lhs).assign(dependees.begin(), dependees.end());
271 }
272 return out;
273}
274
275/* the "FIRST" set, i.e. the set of 1-heads of non-null terminal descendants of
276 some string.
277 As suggested by Westley Weimer here:
278 https://www.cs.virginia.edu/~weimer/2008-415/reading/FirstFollowLL.pdf
279 we will also use the FIRST set for determining whether the string has
280 a null terminal descendant, indicated by the prescence of a special
281 FIRST_NULL symbol in the FIRST set */
282enum { FIRST_NULL = -425 };
283typedef std::set<int> FirstSet;
284
285static void print_set(std::set<int> const& set, Grammar const& grammar) {
286 std::cerr << "{";
287 for (std::set<int>::const_iterator it = set.begin(); it != set.end(); ++it) {
288 if (it != set.begin()) std::cerr << ", ";
289 int symb = *it;
290 if (symb == FIRST_NULL) std::cerr << "null";
291 else {
292 const std::string& symb_name = at(grammar.symbol_names, symb);
293 if (symb_name == ",") std::cerr << "','";
294 else std::cerr << symb_name;
295 }
296 }
297 std::cerr << "}";
298}
299
300static FirstSet get_first_set_of_string(std::vector<int> const& string,
301 std::vector<FirstSet> const& first_sets) {
302 FirstSet out;
303 /* walk the string, stop when any symbol is found that doesn't
304 have a null terminal descendant */
305 int i;
306 for (i = 0; i < Teuchos::size(string); ++i) {
307 int symbol = at(string, i);
308 bool has_null = false;
309 const FirstSet& first_set = at(first_sets, symbol);
310 for (FirstSet::const_iterator it = first_set.begin();
311 it != first_set.end(); ++it) {
312 int first_symbol = *it;
313 if (first_symbol == FIRST_NULL) has_null = true;
314 else out.insert(first_symbol);
315 }
316 if (!has_null) break;
317 }
318 if (i == Teuchos::size(string)) out.insert(FIRST_NULL);
319 return out;
320}
321
322struct Event {
323 int added_symbol;
324 int dependee;
325 Event(int as, int d):
326 added_symbol(as),
327 dependee(d)
328 {}
329};
330
331/* figure out the FIRST sets for each non-terminal in the grammar.
332 I couldn't find a super-efficient way to do this, so here is a
333 free-for-all event-driven implementation. */
334static std::vector<FirstSet> compute_first_sets(Grammar const& grammar,
335 bool verbose) {
336 if (verbose) std::cerr << "computing FIRST sets...\n";
337 std::queue<Event> event_q;
338 int nsymbols = grammar.nsymbols;
339 std::vector<FirstSet> first_sets = make_vector<FirstSet>(nsymbols);
340 Graph lhs2prods = get_productions_by_lhs(grammar);
341 for (int symbol = 0; symbol < nsymbols; ++symbol) {
342 if (is_terminal(grammar, symbol)) {
343 event_q.push(Event(symbol, symbol));
344 } else {
345 for (int i = 0; i < count_edges(lhs2prods, symbol); ++i) {
346 int prod_i = at(lhs2prods, symbol, i);
347 const Grammar::Production& prod = at(grammar.productions, prod_i);
348 if (prod.rhs.empty()) {
349 event_q.push(Event(FIRST_NULL, symbol));
350 break;
351 }
352 }
353 }
354 }
355 Graph dependers2dependees = get_symbol_graph(grammar, lhs2prods);
356 Graph dependees2dependers = make_transpose(dependers2dependees);
357 while (!event_q.empty()) {
358 Event event = event_q.front(); event_q.pop();
359 int added_symb = event.added_symbol;
360 int dependee = event.dependee;
361 FirstSet& dependee_firsts = at(first_sets, dependee);
362 /* hopefully we don't get too many duplicate events piled up... */
363 if (dependee_firsts.count(added_symb)) continue;
364 dependee_firsts.insert(added_symb);
365 for (int i = 0; i < count_edges(dependees2dependers, dependee); ++i) {
366 int depender = at(dependees2dependers, dependee, i);
367 TEUCHOS_ASSERT(is_nonterminal(grammar, depender));
368 const FirstSet& depender_firsts = at(first_sets, depender);
369 for (int j = 0; j < count_edges(lhs2prods, depender); ++j) {
370 int prod_i = at(lhs2prods, depender, j);
371 const Grammar::Production& prod = at(grammar.productions, prod_i);
372 FirstSet rhs_first_set = get_first_set_of_string(prod.rhs, first_sets);
373 for (FirstSet::iterator it = rhs_first_set.begin();
374 it != rhs_first_set.end(); ++it) {
375 int rhs_first_symb = *it;
376 if (!depender_firsts.count(rhs_first_symb)) {
377 event_q.push(Event(rhs_first_symb, depender));
378 }
379 }
380 }
381 }
382 }
383 if (verbose) {
384 for (int symb = 0; symb < nsymbols; ++symb) {
385 const std::string& symb_name = at(grammar.symbol_names, symb);
386 std::cerr << "FIRST(" << symb_name << ") = {";
387 const FirstSet& c = at(first_sets, symb);
388 for (FirstSet::const_iterator it = c.begin(); it != c.end(); ++it) {
389 if (it != c.begin()) std::cerr << ", ";
390 int first_symb = *it;
391 if (first_symb == FIRST_NULL) {
392 std::cerr << "null";
393 } else {
394 const std::string& first_name = at(grammar.symbol_names, first_symb);
395 std::cerr << first_name;
396 }
397 }
398 std::cerr << "}\n";
399 }
400 std::cerr << '\n';
401 }
402 return first_sets;
403}
404
405StateConfigs form_state_configs(StatesInProgress const& states) {
406 StateConfigs out;
407 for (int i = 0; i < Teuchos::size(states); ++i) {
408 StateInProgress& state = *at(states, i);
409 for (int j = 0; j < Teuchos::size(state.configs); ++j) {
410 out.push_back(StateConfig(i, j));
411 }
412 }
413 return out;
414}
415
416Graph form_states_to_state_configs(StateConfigs const& scs,
417 StatesInProgress const& states) {
418 Graph out = make_graph_with_nnodes(Teuchos::size(states));
419 for (int i = 0; i < Teuchos::size(scs); ++i) {
420 const StateConfig& sc = at(scs, i);
421 at(out, sc.state).push_back(i);
422 }
423 return out;
424}
425
426static std::string escape_dot(std::string const& s) {
427 std::string out;
428 for (std::size_t i = 0; i < s.size(); ++i) {
429 char c = s[i];
430 if (c == '\\' || c == '|' || c == '\"' || c == '<' || c == '>' || c == '{' || c == '}') {
431 out.push_back('\\');
432 out.push_back(c);
433 } else if (c == '.') {
434 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105329
435#if defined(__GNUC__) && __GNUC__ == 12
436#pragma GCC diagnostic push
437#pragma GCC diagnostic ignored "-Wrestrict"
438#endif
439 out = "'";
440#if defined(__GNUC__) && __GNUC__ == 12
441#pragma GCC diagnostic pop
442#endif
443 out += s;
444 out += "'";
445 return out;
446 } else {
447 out.push_back(c);
448 }
449 }
450 return out;
451}
452
453void print_graphviz(
454 std::string const& filepath,
455 ParserInProgress const& pip,
456 bool /* verbose */,
457 std::ostream& os
458 ) {
459 const StatesInProgress& sips = pip.states;
460 const Configs& cs = pip.configs;
461 GrammarPtr grammar = pip.grammar;
462 const Graph& states2scs = pip.states2state_configs;
463 os << "writing GraphViz file \"" << filepath << "\"\n";
464 os << "process with:\n";
465 os << " dot -Tpdf -o \"" << filepath << ".pdf\" \"" << filepath << "\"\n";
466 std::ofstream file(filepath.c_str());
467 TEUCHOS_ASSERT(file.is_open());
468 file << "digraph {\n";
469 file << "graph [\n";
470 file << "rankdir = \"LR\"\n";
471 file << "]\n";
472 for (int s_i = 0; s_i < Teuchos::size(sips); ++s_i) {
473 const StateInProgress& state = *at(sips, s_i);
474 file << s_i << " [\n";
475 file << "label = \"";
476 file << "State " << s_i << "\\l";
477 for (int cis_i = 0; cis_i < Teuchos::size(state.configs); ++cis_i) {
478 int c_i = at(state.configs, cis_i);
479 const Config& config = at(cs, c_i);
480 const Grammar::Production& prod = at(grammar->productions, config.production);
481 int sc_i = at(states2scs, s_i, cis_i);
482 file << sc_i << ": ";
483 const std::string& lhs_name = at(grammar->symbol_names, prod.lhs);
484 file << escape_dot(lhs_name) << " ::= ";
485 for (int rhs_i = 0; rhs_i <= Teuchos::size(prod.rhs); ++rhs_i) {
486 if (rhs_i == config.dot) file << " .";
487 if (rhs_i < Teuchos::size(prod.rhs)) {
488 int rhs_symb = at(prod.rhs, rhs_i);
489 const std::string& rhs_symb_name = at(grammar->symbol_names, rhs_symb);
490 file << " " << escape_dot(rhs_symb_name);
491 }
492 }
493 if (config.dot == Teuchos::size(prod.rhs)) {
494 file << ", \\{";
495 bool found = false;
496 for (int a_i = 0; a_i < Teuchos::size(state.actions); ++a_i) {
497 const ActionInProgress& action = at(state.actions, a_i);
498 if (action.action.kind == ACTION_REDUCE &&
499 action.action.production == config.production) {
500 found = true;
501 const Context& ac = action.context;
502 for (Context::const_iterator it = ac.begin(); it != ac.end(); ++it) {
503 if (it != ac.begin()) file << ", ";
504 int symb = *it;
505 const std::string& symb_name = at(grammar->symbol_names, symb);
506 file << escape_dot(symb_name);
507 }
508 }
509 }
510 TEUCHOS_TEST_FOR_EXCEPTION(!found, std::logic_error,
511 "BUG: missing reduce action in state " << s_i << " !!!\n");
512 file << "\\}";
513 }
514 file << "\\l";
515 }
516 file << "\"\n";
517 file << "shape = \"record\"\n";
518 file << "]\n";
519 for (int a_i = 0; a_i < Teuchos::size(state.actions); ++a_i) {
520 const ActionInProgress& action = at(state.actions, a_i);
521 if (action.action.kind == ACTION_SHIFT) {
522 int symb = *(action.context.begin());
523 const std::string& symb_name = at(grammar->symbol_names, symb);
524 int next = action.action.next_state;
525 file << s_i << " -> " << next << " [\n";
526 file << "label = \"" << escape_dot(symb_name) << "\"\n";
527 file << "]\n";
528 }
529 }
530 }
531 file << "}\n";
532}
533
534static Graph make_immediate_predecessor_graph(
535 StateConfigs const& scs,
536 StatesInProgress const& states,
537 Graph const& states2scs,
538 Configs const& cs,
539 GrammarPtr grammar) {
540 Graph out = make_graph_with_nnodes(Teuchos::size(scs));
541 for (int s_i = 0; s_i < Teuchos::size(states); ++s_i) {
542 const StateInProgress& state = *at(states, s_i);
543 for (int cis_i = 0; cis_i < Teuchos::size(state.configs); ++cis_i) {
544 int config_i = at(state.configs, cis_i);
545 const Config& config = at(cs, config_i);
546 const Grammar::Production& prod = at(grammar->productions, config.production);
547 int dot = config.dot;
548 if (dot == Teuchos::size(prod.rhs)) continue;
549 int s = at(prod.rhs, dot);
550 if (is_terminal(*grammar, s)) continue;
551 for (int cis_j = 0; cis_j < Teuchos::size(state.configs); ++cis_j) {
552 int config_j = at(state.configs, cis_j);
553 const Config& config2 = at(cs, config_j);
554 const Grammar::Production& prod2 = at(grammar->productions, config2.production);
555 if (prod2.lhs == s) {
556 int sc_i = at(states2scs, s_i, cis_i);
557 int sc_j = at(states2scs, s_i, cis_j);
558 add_edge(out, sc_j, sc_i);
559 }
560 }
561 }
562 }
563 return out;
564}
565
566static Graph find_transition_predecessors(
567 StateConfigs const& scs,
568 StatesInProgress const& states,
569 Graph const& states2scs,
570 Configs const& cs,
571 GrammarPtr grammar) {
572 Graph out = make_graph_with_nnodes(Teuchos::size(scs));
573 for (int state_i = 0; state_i < Teuchos::size(states); ++state_i) {
574 const StateInProgress& state = *at(states, state_i);
575 for (int a_i = 0; a_i < Teuchos::size(state.actions); ++a_i) {
576 const ActionInProgress& action = at(state.actions, a_i);
577 if (action.action.kind != ACTION_SHIFT) continue;
578 TEUCHOS_ASSERT(action.context.size() == 1);
579 int symbol = *(action.context.begin());
580 int state_j = action.action.next_state;
581 const StateInProgress& state2 = *at(states, state_j);
582 for (int cis_i = 0; cis_i < Teuchos::size(state.configs); ++cis_i) {
583 int config_i = at(state.configs, cis_i);
584 const Config& config = at(cs, config_i);
585 for (int cis_j = 0; cis_j < Teuchos::size(state2.configs); ++cis_j) {
586 int config_j = at(state2.configs, cis_j);
587 const Config& config2 = at(cs, config_j);
588 if (config.production == config2.production &&
589 config.dot + 1 == config2.dot) {
590 const Grammar::Production& prod = at(grammar->productions, config.production);
591 int rhs_symbol = at(prod.rhs, config.dot);
592 if (rhs_symbol == symbol) {
593 int sc_i = at(states2scs, state_i, cis_i);
594 int sc_j = at(states2scs, state_j, cis_j);
595 add_edge(out, sc_j, sc_i);
596 }
597 }
598 }
599 }
600 }
601 }
602 return out;
603}
604
605static Graph make_originator_graph(
606 StateConfigs const& scs,
607 StatesInProgress const& states,
608 Graph const& states2scs,
609 Configs const& cs,
610 GrammarPtr grammar) {
611 Graph out = make_graph_with_nnodes(Teuchos::size(scs));
612 Graph ipg = make_immediate_predecessor_graph(
613 scs, states, states2scs, cs, grammar);
614 Graph tpg = find_transition_predecessors(
615 scs, states, states2scs, cs, grammar);
616 for (int sc_i = 0; sc_i < Teuchos::size(scs); ++sc_i) {
617 std::set<int> originators;
618 /* breadth-first search through the Transition
619 Precessor Graph (tpg), followed by a single hop
620 along the Immediate Predecessor Graph (ipg) */
621 std::queue<int> tpq;
622 std::set<int> tps;
623 tpq.push(sc_i);
624 tps.insert(sc_i);
625 while (!tpq.empty()) {
626 int tpp = tpq.front(); tpq.pop();
627 for (int i = 0; i < count_edges(tpg, tpp); ++i) {
628 int tpc = at(tpg, tpp, i);
629 if (tps.count(tpc)) continue;
630 tpq.push(tpc);
631 tps.insert(tpc);
632 }
633 for (int i = 0; i < count_edges(ipg, tpp); ++i) {
634 int ip_i = at(ipg, tpp, i);
635 originators.insert(ip_i);
636 }
637 }
638 at(out, sc_i).assign(originators.begin(), originators.end());
639 }
640 return out;
641}
642
643static std::vector<int> get_follow_string(
644 int sc_addr,
645 StateConfigs const& scs,
646 StatesInProgress const& states,
647 Configs const& cs,
648 GrammarPtr grammar) {
649 const StateConfig& sc = at(scs, sc_addr);
650 const StateInProgress& state = *at(states, sc.state);
651 int config_i = at(state.configs, sc.config_in_state);
652 const Config& config = at(cs, config_i);
653 const Grammar::Production& prod = at(grammar->productions, config.production);
654 int out_size = Teuchos::size(prod.rhs) - (config.dot + 1);
655 std::vector<int> out;
656 /* out_size can be negative */
657 if (out_size < 1) return out;
658 reserve(out, out_size);
659 for (int i = config.dot + 1; i < Teuchos::size(prod.rhs); ++i) {
660 out.push_back(at(prod.rhs, i));
661 }
662 return out;
663}
664
665static void print_string(std::vector<int> const& str, GrammarPtr grammar) {
666 std::cerr << "\"";
667 for (int i = 0; i < Teuchos::size(str); ++i) {
668 int symb = at(str, i);
669 const std::string& symb_name = at(grammar->symbol_names, symb);
670 std::cerr << symb_name;
671 }
672 std::cerr << "\"";
673}
674
675static bool has_non_null_terminal_descendant(FirstSet const& first_set) {
676 if (first_set.empty()) return false;
677 if (first_set.size() > 1) return true;
678 return *(first_set.begin()) != FIRST_NULL;
679}
680
681static Context get_contexts(FirstSet first_set) {
682 FirstSet::iterator it = first_set.find(FIRST_NULL);
683 if (it != first_set.end()) first_set.erase(it);
684 return first_set;
685}
686
687enum { MARKER = -433 };
688enum { ZERO = -100 }; // actual zero is a valid index for us
689
690static void print_stack(std::vector<int> const& stack) {
691 for (int i = 0; i < Teuchos::size(stack); ++i) {
692 int symb = at(stack, i);
693 if (symb == MARKER) std::cerr << " M";
694 else if (symb == ZERO) std::cerr << " Z";
695 else std::cerr << " " << symb;
696 }
697 std::cerr << '\n';
698}
699
700static void move_markers(
701 std::vector<int>& lane,
702 std::vector<int>& in_lane,
703 int zeta_prime_addr,
704 int zeta_pointer,
705 bool tests_failed
706 ) {
707 int loc_of_zeta_prime = at(in_lane, zeta_prime_addr);
708 TEUCHOS_ASSERT(loc_of_zeta_prime != -1);
709 int r = 0;
710 for (int i = loc_of_zeta_prime + 1; i < zeta_pointer; ++i) {
711 if (at(lane, i) == MARKER) {
712 ++r;
713 at(lane, i) = ZERO;
714 }
715 }
716 int top_addr = -1;
717 if (tests_failed) {
718 top_addr = lane.back();
719 lane.resize(lane.size() - 1); // pop
720 }
721 for (int i = 0; i < r; ++i) lane.push_back(MARKER);
722 if (tests_failed) {
723 lane.push_back(top_addr);
724 at(in_lane, top_addr) = Teuchos::size(lane) - 1;
725 }
726}
727
728typedef std::vector<Context> Contexts;
729
730static void context_adding_routine(
731 std::vector<int> const& lane,
732 int zeta_pointer,
733 Context& contexts_generated,
734 Contexts& contexts,
735 bool verbose,
736 GrammarPtr grammar
737 ) {
738 if (verbose) {
739 std::cerr << " CONTEXT ADDING ROUTINE\n";
740 std::cerr << " LANE:";
741 print_stack(lane);
742 std::cerr << " $\\zeta$-POINTER = " << zeta_pointer << '\n';
743 }
744 for (int r = zeta_pointer; r >= 0 && (!contexts_generated.empty()); --r) {
745 int v_r = at(lane, r);
746 if (verbose) std::cerr << " r = " << r << ", $v_r$ = ";
747 if (v_r < 0) {
748 if (verbose) {
749 if (v_r == MARKER) std::cerr << "marker\n";
750 else if (v_r == ZERO) std::cerr << "zero\n";
751 }
752 continue;
753 }
754 int tau_r_addr = v_r;
755 if (verbose) {
756 std::cerr << "$\\tau_r$ = " << tau_r_addr << '\n';
757 std::cerr << " CONTEXTS_GENERATED = ";
758 print_set(contexts_generated, *grammar);
759 std::cerr << "\n CONTEXTS_$\\tau_r$ = ";
760 print_set(at(contexts, tau_r_addr), *grammar);
761 std::cerr << "\n CONTEXTS_GENERATED <- CONTEXTS_GENERATED - CONTEXTS_$\\tau_r$";
762 }
763 subtract_from(contexts_generated, at(contexts, tau_r_addr));
764 if (verbose) {
765 std::cerr << "\n CONTEXTS_GENERATED = ";
766 print_set(contexts_generated, *grammar);
767 std::cerr << "\n CONTEXTS_$\\tau_r$ <- CONTEXTS_$\\tau_r$ U CONTEXTS_GENERATED";
768 }
769 unite_with(at(contexts, tau_r_addr), contexts_generated);
770 if (verbose) {
771 std::cerr << "\n CONTEXTS_$\\tau_r$ = ";
772 print_set(at(contexts, tau_r_addr), *grammar);
773 std::cerr << "\n";
774 }
775 }
776}
777
778static void deal_with_tests_failed(
779 int& num_originators_failed,
780 int& first_originator_failed,
781 int zeta_prime_addr,
782 bool& tests_failed,
783 std::vector<int>& lane,
784 std::vector<int>& in_lane,
785 int zeta_addr,
786 std::vector<int>& stack,
787 bool verbose
788 ) {
789 if (verbose) std::cerr << " Dealing with test failures\n";
790 if (num_originators_failed == 0) {
791 if (verbose) std::cerr << " " << zeta_prime_addr << " is the first originator of " << zeta_addr << " to fail the tests\n";
792 first_originator_failed = zeta_prime_addr;
793 if (verbose) std::cerr << " pushing " << zeta_prime_addr << " onto LANE:\n ";
794 lane.push_back(zeta_prime_addr);
795 if (verbose) print_stack(lane);
796 at(in_lane, zeta_prime_addr) = Teuchos::size(lane) - 1;
797 if (verbose) std::cerr << " IN_LANE(" << zeta_prime_addr << ") <- ON\n";
798 tests_failed = true;
799 if (verbose) std::cerr << " TESTS_FAILED <- ON\n";
800 } else if (num_originators_failed == 1) {
801 if (verbose) std::cerr << " " << zeta_prime_addr << " is the second originator of " << zeta_addr << " to fail the tests\n";
802 int zeta_double_prime_addr = first_originator_failed;
803 if (verbose) std::cerr << " the first was " << zeta_double_prime_addr << '\n';
804 TEUCHOS_ASSERT(at(lane, Teuchos::size(lane) - 1) == zeta_double_prime_addr);
805 TEUCHOS_ASSERT(at(lane, Teuchos::size(lane) - 2) == zeta_addr);
806 if (verbose) std::cerr << " pop LANE, push {marker, " << zeta_double_prime_addr << "} onto it:\n ";
807 lane.resize(lane.size() - 1);
808 lane.push_back(MARKER);
809 lane.push_back(zeta_double_prime_addr);
810 if (verbose) print_stack(lane);
811 if (verbose) std::cerr << " push {marker, " << zeta_prime_addr << "} onto STACK:\n ";
812 stack.push_back(MARKER);
813 stack.push_back(zeta_prime_addr);
814 if (verbose) print_stack(stack);
815 } else {
816 if (verbose) std::cerr << " " << zeta_prime_addr << " is the third or later originator of " << zeta_addr << " to fail the tests\n";
817 if (verbose) std::cerr << " pushing " << zeta_prime_addr << " onto STACK:\n ";
818 stack.push_back(zeta_prime_addr);
819 if (verbose) print_stack(stack);
820 }
821 ++num_originators_failed;
822}
823
824static void heuristic_propagation_of_context_sets(
825 int tau_addr,
826 Contexts& contexts,
827 std::vector<bool>& complete,
828 StateConfigs const& scs,
829 StatesInProgress const& states,
830 Graph const& states2scs,
831 Configs const& cs,
832 GrammarPtr grammar
833 ) {
834 const StateConfig& tau = at(scs, tau_addr);
835 const StateInProgress& state = *at(states, tau.state);
836 int config_i = at(state.configs, tau.config_in_state);
837 const Config& config = at(cs, config_i);
838 if (config.dot != 0) return;
839 const Grammar::Production& prod = at(grammar->productions, config.production);
840 for (int cis_j = 0; cis_j < Teuchos::size(state.configs); ++cis_j) {
841 int config_j = at(state.configs, cis_j);
842 if (config_j == config_i) continue;
843 const Config& config2 = at(cs, config_j);
844 if (config2.dot != 0) continue;
845 const Grammar::Production& prod2 = at(grammar->productions, config2.production);
846 if (prod.lhs != prod2.lhs) continue;
847 int tau_prime_addr = at(states2scs, tau.state, cis_j);
848 at(contexts, tau_prime_addr) = at(contexts, tau_addr);
849 at(complete, tau_prime_addr) = true;
850 }
851}
852
853/* Here it is! The magical algorithm described by a flowchart in
854 Figure 7 of David Pager's paper. */
855static void compute_context_set(
856 int zeta_j_addr,
857 Contexts& contexts,
858 std::vector<bool>& complete,
859 StateConfigs const& scs,
860 Graph const& originator_graph,
861 StatesInProgress const& states,
862 Graph const& states2scs,
863 Configs const& cs,
864 std::vector<FirstSet> const& first_sets,
865 GrammarPtr grammar,
866 bool verbose,
867 ParserInProgress const& pip
868 ) {
869 if (verbose) std::cerr << "Computing context set for $\\zeta_j$ = " << zeta_j_addr << "...\n";
870 if (verbose) std::cerr << "BEGIN PROGRAM\n";
871 if (at(complete, zeta_j_addr)) {
872 if (verbose) std::cerr << zeta_j_addr << " was already complete!\nEND PROGRAM\n\n";
873 return;
874 }
875 std::vector<int> stack;
876 // need random access, inner insert, which std::stack doesn't provide
877 std::vector<int> lane;
878 std::vector<int> in_lane = make_vector<int>(Teuchos::size(scs), -1);
879 lane.push_back(zeta_j_addr);
880 at(in_lane, zeta_j_addr) = Teuchos::size(lane) - 1;
881 bool tests_failed = false;
882 Context contexts_generated;
883 if (verbose) {
884 std::cerr << "Initial LANE:";
885 print_stack(lane);
886 }
887 while (true) {
888 TEUCHOS_ASSERT(!lane.empty());
889 int zeta_addr = lane.back();
890 if (verbose) {
891 std::cerr << "Top of LANE is $\\zeta$ = " << zeta_addr << '\n';
892 }
893 int zeta_pointer = Teuchos::size(lane) - 1;
894 if (verbose) std::cerr << "$\\zeta$-POINTER <- " << zeta_pointer << '\n';
895 int num_originators_failed = 0;
896 int first_originator_failed = -1;
897 if (verbose) std::cerr << "DO_LOOP:\n";
898 /* DO_LOOP */
899 for (int i = 0; i < count_edges(originator_graph, zeta_addr); ++i) {
900 int zeta_prime_addr = at(originator_graph, zeta_addr, i);
901 if (verbose) {
902 std::cerr << "Next originator of $\\zeta$ = " << zeta_addr << " is $\\zeta'$ = " << zeta_prime_addr << '\n';
903 }
904 std::vector<int> gamma = get_follow_string(zeta_prime_addr, scs, states, cs, grammar);
905 if (verbose) {
906 std::cerr << " FOLLOW string of $\\zeta'$ = " << zeta_prime_addr << " is ";
907 print_string(gamma, grammar);
908 std::cerr << '\n';
909 }
910 FirstSet gamma_first = get_first_set_of_string(gamma, first_sets);
911 if (verbose) {
912 std::cerr << " FIRST set of ";
913 print_string(gamma, grammar);
914 std::cerr << " is ";
915 print_set(gamma_first, *grammar);
916 std::cerr << "\n";
917 }
918 if (has_non_null_terminal_descendant(gamma_first)) { // test A
919 if (verbose) {
920 std::cerr << " ";
921 print_string(gamma, grammar);
922 std::cerr << " has a non-null terminal descendant\n";
923 }
924 contexts_generated = get_contexts(gamma_first);
925 if (verbose) {
926 std::cerr << " CONTEXTS_GENERATED = ";
927 print_set(contexts_generated, *grammar);
928 std::cerr << " = 1-heads of non-null descendants of ";
929 print_string(gamma, grammar);
930 std::cerr << '\n';
931 }
932 if (gamma_first.count(FIRST_NULL)) {
933 if (verbose) {
934 std::cerr << " ";
935 print_string(gamma, grammar);
936 std::cerr << " has a null terminal descendant\n";
937 }
938 if (at(complete, zeta_prime_addr)) {
939 unite_with(contexts_generated, at(contexts, zeta_prime_addr));
940 context_adding_routine(lane, zeta_pointer, contexts_generated, contexts,
941 verbose, grammar);
942 } else if (-1 == at(in_lane, zeta_prime_addr)) {
943 context_adding_routine(lane, zeta_pointer, contexts_generated, contexts,
944 verbose, grammar);
945 /* TRACE_FURTHER */
946 deal_with_tests_failed(num_originators_failed, first_originator_failed,
947 zeta_prime_addr, tests_failed, lane, in_lane, zeta_addr, stack,
948 verbose);
949 } else {
950 print_graphviz("ambiguous.dot", pip, true, std::cerr);
951 std::stringstream ss;
952 ss << "error: grammar is ambiguous.\n";
953 ss << "zeta_j is " << zeta_j_addr << ", zeta is " << zeta_addr << ", and zeta prime is " << zeta_prime_addr << '\n';
954 throw ParserBuildFail(ss.str());
955 }
956 } else {
957 context_adding_routine(lane, zeta_pointer, contexts_generated, contexts,
958 verbose, grammar);
959 }
960 } else {
961 if (verbose) {
962 std::cerr << " ";
963 print_string(gamma, grammar);
964 std::cerr << " does not have a non-null terminal descendant\n";
965 }
966 if (at(complete, zeta_prime_addr)) { // test B
967 if (verbose) std::cerr << " COMPLETE(" << zeta_prime_addr << ") is ON\n";
968 contexts_generated = at(contexts, zeta_prime_addr);
969 context_adding_routine(lane, zeta_pointer, contexts_generated, contexts,
970 verbose, grammar);
971 } else {
972 if (verbose) std::cerr << " COMPLETE(" << zeta_prime_addr << ") is OFF\n";
973 if (-1 != at(in_lane, zeta_prime_addr)) { // test C
974 if (verbose) std::cerr << " IN_LANE(" << zeta_prime_addr << ") is ON\n";
975 move_markers(lane, in_lane, zeta_prime_addr, zeta_pointer, tests_failed);
976 contexts_generated = at(contexts, zeta_prime_addr);
977 context_adding_routine(lane, zeta_pointer, contexts_generated, contexts,
978 verbose, grammar);
979 } else {
980 if (verbose) std::cerr << " IN_LANE(" << zeta_prime_addr << ") is OFF\n";
981 deal_with_tests_failed(num_originators_failed, first_originator_failed,
982 zeta_prime_addr, tests_failed, lane, in_lane, zeta_addr, stack,
983 verbose);
984 }
985 }
986 }
987 } /* END DO_LOOP */
988 if (verbose) std::cerr << "END DO_LOOP\n";
989 if (tests_failed) {
990 if (verbose) {
991 std::cerr << " TESTS_FAILED was on, turning it off and going to next configuration\n";
992 }
993 tests_failed = false;
994 continue;
995 }
996 bool keep_lane_popping = true;
997 if (verbose) std::cerr << " Start LANE popping\n";
998 while (keep_lane_popping) { // LANE popping loop
999 TEUCHOS_ASSERT(!lane.empty());
1000 if (verbose) {
1001 std::cerr << " LANE:";
1002 print_stack(lane);
1003 }
1004 if (at(lane, Teuchos::size(lane) - 1) == MARKER) {
1005 if (verbose) std::cerr << " Top of LANE is a marker\n";
1006 if (verbose) std::cerr << " Start STACK popping\n";
1007 while (true) { // STACK popping loop
1008 TEUCHOS_ASSERT(!stack.empty());
1009 if (verbose) {
1010 std::cerr << " STACK:";
1011 print_stack(stack);
1012 std::cerr << " LANE:";
1013 print_stack(lane);
1014 }
1015 if (stack.back() == MARKER) {
1016 if (verbose) std::cerr << " Top of STACK is a marker, pop STACK and LANE\n";
1017 resize(stack, Teuchos::size(stack) - 1);
1018 resize(lane, Teuchos::size(lane) - 1);
1019 break; // out of STACK popping, back into LANE popping
1020 } else if (at(complete, stack.back())) {
1021 if (verbose) std::cerr << " Top of STACK is has COMPLETE flag, pop STACK\n";
1022 resize(stack, Teuchos::size(stack) - 1);
1023 // back into STACK popping
1024 } else {
1025 int addr = stack.back();
1026 if (verbose) std::cerr << " Top of STACK is " << addr << ", pop STACK\n";
1027 resize(stack, Teuchos::size(stack) - 1);
1028 if (verbose) std::cerr << " Push " << addr << " onto LANE\n";
1029 lane.push_back(addr);
1030 if (verbose) std::cerr << " IN_LANE(" << addr << ") <- ON\n";
1031 at(in_lane, addr) = Teuchos::size(lane) - 1;
1032 keep_lane_popping = false;
1033 break; // out of STACK and LANE popping, into top-level loop
1034 } // end STACK top checks
1035 } // end STACK popping loop
1036 } else if (at(lane, Teuchos::size(lane) - 1) == ZERO) {
1037 if (verbose) std::cerr << " Top of LANE is a zero\n";
1038 if (verbose) std::cerr << " Pop LANE\n";
1039 resize(lane, Teuchos::size(lane) - 1); // pop LANE
1040 // back to top of LANE popping loop
1041 } else { // top of LANE neither marker nor zero
1042 int tau_addr = lane.back();
1043 if (verbose) std::cerr << " Top of LANE is $\\tau$ = " << tau_addr << "\n";
1044 at(in_lane, tau_addr) = -1;
1045 if (verbose) std::cerr << " IN_LANE(" << tau_addr << ") <- OFF\n";
1046 at(complete, tau_addr) = true;
1047 if (verbose) std::cerr << " COMPLETE(" << tau_addr << ") <- ON\n";
1048 if (verbose) std::cerr << " HEURISTIC PROPAGATION OF CONTEXT SETS\n";
1049 heuristic_propagation_of_context_sets(
1050 tau_addr, contexts, complete,
1051 scs, states, states2scs, cs, grammar);
1052 if (Teuchos::size(lane) == 1 && at(lane, 0) == zeta_j_addr) {
1053 if (verbose) std::cerr << "END PROGRAM\n\n";
1054 return;
1055 }
1056 if (verbose) std::cerr << " Pop LANE\n";
1057 resize(lane, Teuchos::size(lane) - 1); // pop LANE
1058 // back to top of LANE popping loop
1059 } // end top of LANE checks
1060 } // end LANE popping loop
1061 } // end top-level while(1) loop
1062}
1063
1064static std::vector<bool> determine_adequate_states(
1065 StatesInProgress const& states,
1066 GrammarPtr grammar,
1067 bool verbose,
1068 std::ostream& os) {
1069 std::vector<bool> out = make_vector<bool>(Teuchos::size(states));
1070 for (int s_i = 0; s_i < Teuchos::size(states); ++s_i) {
1071 const StateInProgress& state = *at(states, s_i);
1072 bool state_is_adequate = true;
1073 for (int a_i = 0; a_i < Teuchos::size(state.actions); ++a_i) {
1074 const ActionInProgress& action = at(state.actions, a_i);
1075 if (action.action.kind == ACTION_SHIFT &&
1076 is_nonterminal(*grammar, *(action.context.begin()))) {
1077 continue;
1078 }
1079 for (int a_j = a_i + 1; a_j < Teuchos::size(state.actions); ++a_j) {
1080 const ActionInProgress& action2 = at(state.actions, a_j);
1081 if (action2.action.kind == ACTION_SHIFT &&
1082 is_nonterminal(*grammar, *(action2.context.begin()))) {
1083 continue;
1084 }
1085 if (intersects(action2.context, action.context)) {
1086 if (verbose) {
1087 const ActionInProgress* ap1 = &action;
1088 const ActionInProgress* ap2 = &action2;
1089 if (ap1->action.kind == ACTION_SHIFT) {
1090 std::swap(ap1, ap2);
1091 }
1092 TEUCHOS_ASSERT(ap1->action.kind == ACTION_REDUCE);
1093 os << "shift-reduce conflict in state " << s_i << ":\n";
1094 os << "reduce ";
1095 const Grammar::Production& prod = at(grammar->productions, ap1->action.production);
1096 const std::string& lhs_name = at(grammar->symbol_names, prod.lhs);
1097 os << lhs_name << " ::=";
1098 for (int rhs_i = 0; rhs_i < Teuchos::size(prod.rhs); ++rhs_i) {
1099 int rhs_symb = at(prod.rhs, rhs_i);
1100 const std::string& rhs_symb_name = at(grammar->symbol_names, rhs_symb);
1101 os << " " << rhs_symb_name;
1102 }
1103 int shift_symb = *(ap2->context.begin());
1104 const std::string& shift_name = at(grammar->symbol_names, shift_symb);
1105 os << "\nshift " << shift_name << '\n';
1106 }
1107 state_is_adequate = false;
1108 break;
1109 }
1110 }
1111 if (!state_is_adequate) break;
1112 }
1113 at(out, s_i) = state_is_adequate;
1114 }
1115 if (verbose) os << '\n';
1116 return out;
1117}
1118
1119ParserInProgress draft_lalr1_parser(GrammarPtr grammar, bool verbose) {
1120 ParserInProgress out;
1121 Configs& cs = out.configs;
1122 StatesInProgress& states = out.states;
1123 StateConfigs& scs = out.state_configs;
1124 Graph& states2scs = out.states2state_configs;
1125 out.grammar = grammar;
1126 cs = make_configs(*grammar);
1127 Graph lhs2cs = get_left_hand_sides_to_start_configs(cs, *grammar);
1128 if (verbose) std::cerr << "Building LR(0) parser\n";
1129 states = make_lr0_parser(cs, *grammar, lhs2cs);
1130 scs = form_state_configs(states);
1131 states2scs = form_states_to_state_configs(scs, states);
1132 if (verbose) print_graphviz("lr0.dot", out, true, std::cerr);
1133 if (verbose) std::cerr << "Checking adequacy of LR(0) machine\n";
1134 std::vector<bool> adequate = determine_adequate_states(states, grammar, verbose,
1135 std::cerr);
1136 if (*(std::min_element(adequate.begin(), adequate.end()))) {
1137 if (verbose) std::cerr << "The grammar is LR(0)!\n";
1138 return out;
1139 }
1140 std::vector<bool> complete = make_vector<bool>(Teuchos::size(scs), false);
1141 std::vector<Context> contexts = make_vector<Context>(Teuchos::size(scs));
1142 int accept_prod_i = get_accept_production(*grammar);
1143 /* initialize the accepting state-configs as described in
1144 footnote 8 at the bottom of page 37 */
1145 for (int sc_i = 0; sc_i < Teuchos::size(scs); ++sc_i) {
1146 StateConfig& sc = at(scs, sc_i);
1147 StateInProgress& state = *at(states, sc.state);
1148 int config_i = at(state.configs, sc.config_in_state);
1149 Config& config = at(cs, config_i);
1150 if (config.production == accept_prod_i) {
1151 at(complete, sc_i) = true;
1152 at(contexts, sc_i).insert(get_end_terminal(*grammar));
1153 }
1154 }
1155 Graph og = make_originator_graph(scs, states, states2scs, cs, grammar);
1156 if (verbose) std::cerr << "Originator Graph:\n";
1157 if (verbose) std::cerr << og << '\n';
1158 std::vector<FirstSet> first_sets = compute_first_sets(*grammar, verbose);
1159 /* compute context sets for all state-configs associated with reduction
1160 actions that are part of an inadequate state */
1161 for (int s_i = 0; s_i < Teuchos::size(states); ++s_i) {
1162 if (at(adequate, s_i)) continue;
1163 StateInProgress& state = *at(states, s_i);
1164 for (int cis_i = 0; cis_i < Teuchos::size(state.configs); ++cis_i) {
1165 int config_i = at(state.configs, cis_i);
1166 const Config& config = at(cs, config_i);
1167 const Grammar::Production& prod = at(grammar->productions, config.production);
1168 if (config.dot != Teuchos::size(prod.rhs)) continue;
1169 int zeta_j_addr = at(states2scs, s_i, cis_i);
1170 compute_context_set(zeta_j_addr, contexts, complete, scs,
1171 og, states, states2scs, cs, first_sets, grammar, verbose, out);
1172 }
1173 }
1174 /* update the context sets for all reduction state-configs
1175 which are marked complete, even if they aren't in inadequate states */
1176 for (int s_i = 0; s_i < Teuchos::size(states); ++s_i) {
1177 StateInProgress& state = *at(states, s_i);
1178 for (int cis_i = 0; cis_i < Teuchos::size(state.configs); ++cis_i) {
1179 int sc_i = at(states2scs, s_i, cis_i);
1180 if (!at(complete, sc_i)) continue;
1181 int config_i = at(state.configs, cis_i);
1182 Config& config = at(cs, config_i);
1183 const Grammar::Production& prod = at(grammar->productions, config.production);
1184 if (config.dot != Teuchos::size(prod.rhs)) continue;
1185 for (int a_i = 0; a_i < Teuchos::size(state.actions); ++a_i) {
1186 ActionInProgress& action = at(state.actions, a_i);
1187 if (action.action.kind == ACTION_REDUCE &&
1188 action.action.production == config.production) {
1189 action.context = at(contexts, sc_i);
1190 }
1191 }
1192 }
1193 }
1194 if (verbose) std::cerr << "Checking adequacy of LALR(1) machine\n";
1195 adequate = determine_adequate_states(states, grammar, verbose, std::cerr);
1196 if (!(*(std::min_element(adequate.begin(), adequate.end())))) {
1197 std::stringstream ss;
1198 ss << "error: The grammar is not LALR(1).\n";
1199 determine_adequate_states(states, grammar, true, ss);
1200 print_graphviz("error.dot", out, true, ss);
1201 std::string s = ss.str();
1202 throw ParserBuildFail(s);
1203 }
1204 if (verbose) std::cerr << "The grammar is LALR(1)!\n";
1205 if (verbose) print_graphviz("lalr1.dot", out, true, std::cerr);
1206 return out;
1207}
1208
1209Parser accept_parser(ParserInProgress const& pip) {
1210 const StatesInProgress& sips = pip.states;
1211 GrammarPtr grammar = pip.grammar;
1212 Parser out(grammar, Teuchos::size(sips));
1213 for (int s_i = 0; s_i < Teuchos::size(sips); ++s_i) {
1214 add_state(out);
1215 }
1216 for (int s_i = 0; s_i < Teuchos::size(sips); ++s_i) {
1217 const StateInProgress& sip = *at(sips, s_i);
1218 for (int a_i = 0; a_i < Teuchos::size(sip.actions); ++a_i) {
1219 const ActionInProgress& action = at(sip.actions, a_i);
1220 if (action.action.kind == ACTION_SHIFT &&
1221 is_nonterminal(*grammar, *(action.context.begin()))) {
1222 int nt = as_nonterminal(*grammar, *(action.context.begin()));
1223 add_nonterminal_action(out, s_i, nt, action.action.next_state);
1224 } else {
1225 for (Context::const_iterator it = action.context.begin();
1226 it != action.context.end(); ++it) {
1227 int terminal = *it;
1228 TEUCHOS_ASSERT(is_terminal(*grammar, terminal));
1229 add_terminal_action(out, s_i, terminal, action.action);
1230 }
1231 }
1232 }
1233 }
1234 return out;
1235}
1236
1237ParserBuildFail::ParserBuildFail(const std::string& msg):
1238 std::invalid_argument(msg) {
1239}
1240
1241Parser make_lalr1_parser(GrammarPtr grammar, bool verbose) {
1242 ParserInProgress pip = draft_lalr1_parser(grammar, verbose);
1243 return accept_parser(pip);
1244}
1245
1246}
Ptr< T > ptr(T *p)
Create a pointer to an object from a raw pointer.
#define TEUCHOS_ASSERT(assertion_test)
This macro is throws when an assert fails.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
TypeTo as(const TypeFrom &t)
Convert from one value type to another.
The Teuchos namespace contains all of the classes, structs and enums used by Teuchos,...
Parser make_lalr1_parser(GrammarPtr grammar, bool verbose)
Tries to create LALR(1) parser tables for a given grammar.