tree-sitter/src/compiler/rules/pattern.cpp

128 lines
3.9 KiB
C++
Raw Normal View History

2013-12-18 20:58:05 -08:00
#include "rules.h"
#include "transition_map.h"
using namespace std;
namespace tree_sitter {
namespace rules {
class PatternParser {
public:
PatternParser(const string &input) :
input(input),
position(0),
length(input.length()) {}
rule_ptr rule() {
auto result = term();
while (has_more_input() && peek() == '|') {
next();
result = choice({ result, term() });
}
return result;
}
private:
rule_ptr term() {
rule_ptr result = factor();
while (has_more_input() && (peek() != '|') && (peek() != ')'))
result = seq({ result, factor() });
return result;
}
rule_ptr factor() {
2013-11-15 13:35:35 -08:00
rule_ptr result = atom();
if (has_more_input() && (peek() == '+')) {
next();
result = repeat(result);
}
return result;
}
rule_ptr atom() {
rule_ptr result;
switch (peek()) {
case '(':
next();
result = rule();
2013-11-15 08:46:45 -08:00
if (peek() != ')')
error("mismatched parens");
else
next();
2013-11-15 08:46:45 -08:00
break;
case ')':
error("mismatched parens");
break;
case '\\':
next();
2013-11-20 19:00:20 -08:00
result = escaped_char(peek());
2013-11-15 08:46:45 -08:00
next();
break;
default:
result = character(peek());
next();
break;
}
2013-11-15 08:46:45 -08:00
return result;
}
2013-11-20 19:00:20 -08:00
rule_ptr escaped_char(char value) {
switch (value) {
case '(':
case ')':
return character(value);
case 'w':
return char_class(CharClassTypeWord);
case 'd':
return char_class(CharClassTypeDigit);
default:
error("unrecognized escape sequence");
return rule_ptr();
}
}
void next() {
position++;
}
char peek() {
return input[position];
}
bool has_more_input() {
return position < length;
}
2013-11-15 08:46:45 -08:00
void error(const char *message) {
throw std::string("Invalid regex pattern '") + input + "': " + message;
}
const std::string input;
const size_t length;
int position;
};
Pattern::Pattern(const std::string &string) : value(string) {};
pattern_ptr pattern(const std::string &value) {
return std::make_shared<Pattern>(value);
}
2013-12-18 20:58:05 -08:00
bool Pattern::operator==(tree_sitter::rules::Rule const &other) const {
2013-11-20 19:00:20 -08:00
auto pattern = dynamic_cast<const Pattern *>(&other);
return pattern && (pattern->value == value);
}
std::string Pattern::to_string() const {
return value;
}
2013-12-18 20:58:05 -08:00
void Pattern::accept(RuleVisitor &visitor) const {
visitor.visit(this);
}
rule_ptr Pattern::to_rule_tree() const {
return PatternParser(value).rule();
}
}
}