tree-sitter/src/compiler/grammar/grammar.cpp

58 lines
1.9 KiB
C++
Raw Normal View History

#include "grammar.h"
2013-12-15 14:41:51 -08:00
using namespace std;
namespace tree_sitter {
2014-01-03 01:02:24 -08:00
Grammar::Grammar(const std::initializer_list<std::pair<const std::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
Grammar::Grammar(std::string start_rule_name, const std::unordered_map<std::string, const rules::rule_ptr> &rules) :
rules(rules),
start_rule_name(start_rule_name) {}
2013-11-20 19:00:20 -08:00
const rules::rule_ptr Grammar::rule(const std::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;
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-03 01:02:24 -08:00
std::ostream& operator<<(std::ostream &stream, const Grammar &grammar) {
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
}