tree-sitter/src/compiler/grammar.cpp

63 lines
2 KiB
C++
Raw Normal View History

#include "grammar.h"
2014-01-04 15:30:05 -08:00
using std::unordered_map;
using std::vector;
using std::string;
using std::pair;
using std::initializer_list;
using std::ostream;
2013-12-15 14:41:51 -08:00
namespace tree_sitter {
2014-01-04 15:30:05 -08:00
Grammar::Grammar(const initializer_list<pair<const string, const rules::rule_ptr>> &rules) :
rules(rules),
2013-11-13 20:22:06 -08:00
start_rule_name(rules.begin()->first) {}
2014-01-03 01:02:24 -08:00
2014-01-04 15:30:05 -08:00
Grammar::Grammar(std::string start_rule_name, const unordered_map<string, const rules::rule_ptr> &rules) :
2014-01-03 01:02:24 -08:00
rules(rules),
start_rule_name(start_rule_name) {}
2014-01-04 15:30:05 -08:00
const rules::rule_ptr Grammar::rule(const string &name) const {
2013-11-13 20:22:06 -08:00
auto iter = rules.find(name);
return (iter == rules.end()) ?
rules::rule_ptr(nullptr) :
iter->second;
}
2013-12-15 14:41:51 -08:00
vector<string> Grammar::rule_names() const {
vector<string> result;
for (auto pair : rules) {
result.push_back(pair.first);
}
return result;
}
2014-01-03 01:02:24 -08:00
bool Grammar::operator==(const Grammar &other) const {
if (other.start_rule_name != start_rule_name) return false;
if (other.rules.size() != rules.size()) return false;
for (auto pair : rules) {
auto other_pair = other.rules.find(pair.first);
if (other_pair == other.rules.end()) return false;
auto orr = other_pair->second->to_string();;
2014-01-03 01:02:24 -08:00
if (!other_pair->second->operator==(*pair.second)) return false;
}
return true;
}
bool Grammar::has_definition(const rules::Symbol &symbol) const {
return rules.find(symbol.name) != rules.end();
}
2014-01-04 15:30:05 -08:00
ostream& operator<<(ostream &stream, const Grammar &grammar) {
2014-01-03 01:02:24 -08:00
stream << string("#<grammar: ");
bool started = false;
for (auto pair : grammar.rules) {
if (started) stream << string(", ");
stream << pair.first;
stream << string(" => ");
stream << pair.second;
started = true;
}
return stream << string(">");
}
2013-12-28 23:26:20 -08:00
}