Skip to content
Snippets Groups Projects
Commit ccfa95a7 authored by Martin Kočička's avatar Martin Kočička Committed by Jan Trávníček
Browse files

added universal LR parsing algorithm

parent c69d56e5
No related branches found
No related tags found
1 merge request!18Bp kocicma3
...@@ -85,6 +85,49 @@ LR0Items LRParser::getNextStateItems ( LR0Items items, alphabet::Symbol symbol, ...@@ -85,6 +85,49 @@ LR0Items LRParser::getNextStateItems ( LR0Items items, alphabet::Symbol symbol,
return getClosure ( transitionItems, originalGrammar ); return getClosure ( transitionItems, originalGrammar );
} }
   
bool LRParser::parse ( LRActionTable actionTable, LRGotoTable gotoTable, automaton::State initialState, std::vector < alphabet::Symbol > input ) {
std::stack < automaton::State > states;
states.push ( initialState );
unsigned currentPosition = 0;
while ( true ) {
LRActionTable::iterator actionIterator = actionTable.find ( { states.top ( ), input[currentPosition] } );
if ( actionIterator == actionTable.end ( ) ) {
return false;
}
switch ( actionIterator->second.first ) {
case LRAction::Shift:
states.push ( actionIterator->second.second.get < automaton::State > ( ) );
++currentPosition;
break;
case LRAction::Reduce: {
std::pair < alphabet::Symbol, std::vector < alphabet::Symbol > > reduceBy = actionIterator->second.second.get < std::pair < alphabet::Symbol, std::vector < alphabet::Symbol > > > ( );
for ( unsigned i = 0; i < reduceBy.second.size ( ); ++i ) {
states.pop ( );
}
LRGotoTable::iterator nextStateIterator = gotoTable.find ( { states.top ( ), reduceBy.first } );
if (nextStateIterator == gotoTable.end()) {
return false;
}
states.push ( nextStateIterator->second );
break;
}
case LRAction::Accept:
return true;
break;
}
}
return false;
}
} /* namespace parsing */ } /* namespace parsing */
   
} /* namespace grammar */ } /* namespace grammar */
...@@ -12,6 +12,8 @@ ...@@ -12,6 +12,8 @@
#include <grammar/ContextFree/CFG.h> #include <grammar/ContextFree/CFG.h>
#include <grammar/parsing/LRParserTypes.h> #include <grammar/parsing/LRParserTypes.h>
   
#include <vector>
namespace grammar { namespace grammar {
   
namespace parsing { namespace parsing {
...@@ -25,6 +27,8 @@ public: ...@@ -25,6 +27,8 @@ public:
static LR0Items getClosure ( LR0Items items, grammar::CFG originalGrammar ); static LR0Items getClosure ( LR0Items items, grammar::CFG originalGrammar );
   
static LR0Items getNextStateItems ( LR0Items items, alphabet::Symbol symbol, grammar::CFG originalGrammar ); static LR0Items getNextStateItems ( LR0Items items, alphabet::Symbol symbol, grammar::CFG originalGrammar );
static bool parse ( LRActionTable actionTable, LRGotoTable gotoTable, automaton::State initialState, std::vector < alphabet::Symbol > input );
}; };
   
} /* namespace parsing */ } /* namespace parsing */
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment