From c0ece722bd7775af14c7f2ec18dcd1fd138607cb Mon Sep 17 00:00:00 2001 From: Patrick Simianer Date: Fri, 10 Oct 2014 14:20:59 +0100 Subject: algorithms: shift reduce dependency parsing --- algorithms/shift_reduce_parser.cc | 127 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 algorithms/shift_reduce_parser.cc (limited to 'algorithms/shift_reduce_parser.cc') diff --git a/algorithms/shift_reduce_parser.cc b/algorithms/shift_reduce_parser.cc new file mode 100644 index 0000000..563c8e4 --- /dev/null +++ b/algorithms/shift_reduce_parser.cc @@ -0,0 +1,127 @@ +#include +#include +#include +#include +#include + + +using namespace std; + +typedef std::pair Key; + +struct E +{ + vector h; + + Key get() { + char second = h.back(); + h.pop_back(); + char first = h.back(); + h.pop_back(); + return make_pair(first, second); + } + bool good() { return h.size() > 1; } + char add(char c) { h.push_back(c); } +}; + +struct P +{ + std::map actionTable_; + + P() + { + createActionTable(); + } + + void r(E& e) + { + cout << "before: "; + for (auto it: e.h) + cout << it; + cout << endl; + bool stop = false; + while (e.good() && !stop) { + pair k = e.get(); + char action = actionTable_[k]; + switch (action) { + case 'L': + e.add('f'); + break; + case 'R': + e.add('f'); + stop = true; + break; + case 'S': + e.add(k.first); + e.add(k.second); + stop = true; + break; + case 'I': + default: + e.add('u'); + stop = true; + break; + } + } + cout << " after: "; + for (auto it: e.h) + cout << it; + cout << endl; + cout << "--" << endl; + } + + void createActionTable() + { + // u -> + actionTable_[Key('u','u')] = 'S'; // Shift + actionTable_[Key('u','f')] = 'S'; + actionTable_[Key('u','l')] = 'S'; + actionTable_[Key('u','r')] = 'I'; // Illegal + + // f -> + actionTable_[Key('f','f')] = 'S'; // ambiguous + actionTable_[Key('f','l')] = 'S'; + actionTable_[Key('f','r')] = 'R'; // Right-reduce + + // l -> + actionTable_[Key('l','f')] = 'L'; // Left-reduce + actionTable_[Key('l','l')] = 'S'; + actionTable_[Key('l','r')] = 'I'; + + // r -> + actionTable_[Key('r','f')] = 'I'; + actionTable_[Key('r','l')] = 'I'; + actionTable_[Key('r','r')] = 'I'; + } +}; + + +int main(void) +{ + E e; + P p; + + /*e.add('u'); + p.r(e); + + e.add('l'); + p.r(e); + + e.add('l'); + p.r(e); + + e.add('f'); + p.r(e); + + e.add('r'); + p.r(e);*/ + + string s("frllllfrlllllllf"); + for (auto it: s) { + e.add(it); + p.r(e); + } + + return 0; +} + -- cgit v1.2.3