tree-sitter/src/compiler/grammar.cpp

91 lines
2.9 KiB
C++
Raw Normal View History

#include "grammar.h"
namespace tree_sitter {
2014-02-12 23:06:26 -08:00
using std::vector;
using std::string;
using std::pair;
using std::initializer_list;
using std::ostream;
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-02-12 08:30:50 -08:00
Grammar::Grammar(std::string start_rule_name, const rule_map &rules) :
2014-01-03 01:02:24 -08:00
rules(rules),
start_rule_name(start_rule_name) {}
2014-02-12 08:30:50 -08:00
Grammar::Grammar(std::string start_rule_name, const rule_map &rules, const rule_map &aux_rules) :
rules(rules),
aux_rules(aux_rules),
start_rule_name(start_rule_name) {}
const rules::rule_ptr Grammar::rule(const rules::Symbol &symbol) const {
auto map = symbol.is_auxiliary ? aux_rules : rules;
auto iter = map.find(symbol.name);
if (iter != map.end())
return iter->second;
else
return rules::rule_ptr();
}
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;
if (other.aux_rules.size() != aux_rules.size()) return false;
2014-01-03 01:02:24 -08:00
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;
}
for (auto pair : aux_rules) {
auto other_pair = other.aux_rules.find(pair.first);
if (other_pair == other.aux_rules.end()) return false;
if (!other_pair->second->operator==(*pair.second)) return false;
}
2014-01-03 01:02:24 -08:00
return true;
}
bool Grammar::has_definition(const rules::Symbol &symbol) const {
return rule(symbol).get() != nullptr;
}
2014-01-04 15:30:05 -08:00
ostream& operator<<(ostream &stream, const Grammar &grammar) {
stream << string("#<grammar");
stream << string(" rules: {");
2014-01-03 01:02:24 -08:00
bool started = false;
for (auto pair : grammar.rules) {
if (started) stream << string(", ");
stream << pair.first;
stream << string(" => ");
stream << pair.second;
started = true;
}
stream << string("}");
stream << string(" aux_rules: {");
started = false;
for (auto pair : grammar.aux_rules) {
if (started) stream << string(", ");
stream << pair.first;
stream << string(" => ");
stream << pair.second;
started = true;
}
stream << string("}");
2014-01-03 01:02:24 -08:00
return stream << string(">");
}
2013-12-28 23:26:20 -08:00
}