mstch/src/template_type.cpp

63 lines
1.9 KiB
C++
Raw Normal View History

#include "template_type.hpp"
using namespace mstch;
template_type::template_type(const std::string& str) {
2015-04-23 18:54:08 +08:00
tokenize(str);
strip_whitespace();
}
void template_type::process_text(citer begin, citer end) {
if (begin == end)
return;
auto start = begin;
for (auto it = begin; it != end; ++it)
if (*it == '\n' || it == end - 1) {
tokens.push_back({{start, it + 1}});
start = it + 1;
}
}
void template_type::tokenize(const std::string& tmplt) {
2015-04-27 19:59:36 +08:00
std::string o{"{{"}, c{"}}"};
citer beg = tmplt.begin();
for (unsigned long pos = 0; pos < tmplt.size();) {
2015-04-27 19:59:36 +08:00
auto to = tmplt.find(o, pos);
auto tc = tmplt.find(c, (to == std::string::npos)?to:(to + 1));
if (tc != std::string::npos && to != std::string::npos) {
2015-04-27 19:59:36 +08:00
if (*(beg + to + o.size()) == '{' && *(beg + tc + c.size()) == '}')
++tc;
process_text(beg + pos, beg + to);
2015-04-27 19:59:36 +08:00
pos = tc + c.size();
tokens.push_back({{beg + to, beg + tc + c.size()}, o.size(), c.size()});
if (*(beg + to + o.size()) == '=' && *(beg + tc - 1) == '=') {
o = {beg + to + o.size() + 1, beg + tmplt.find(' ', to)};
c = {beg + tmplt.find(' ', to) + 1, beg + tc - 1};
2015-04-23 18:54:08 +08:00
}
} else {
process_text(beg + pos, tmplt.end());
pos = tc;
}
2015-04-23 18:54:08 +08:00
}
}
void template_type::strip_whitespace() {
2015-04-27 19:59:36 +08:00
auto lbegin = tokens.begin();
2015-04-23 18:54:08 +08:00
bool has_tag = false, non_space = false;
for (auto it = tokens.begin(); it != tokens.end(); ++it) {
auto type = (*it).token_type();
if (type != token::type::text && type != token::type::variable &&
type != token::type::unescaped_variable)
has_tag = true;
else if (!(*it).ws_only())
non_space = true;
if ((*it).eol()) {
2015-04-27 19:59:36 +08:00
if (has_tag && !non_space)
for (auto c = lbegin; it != c-1; c = (*c).ws_only()?tokens.erase(c):++c)
it = (*c).eol()?c-1:it;
2015-04-23 18:54:08 +08:00
non_space = has_tag = false;
2015-04-27 19:59:36 +08:00
lbegin = it + 1;
}
2015-04-23 18:54:08 +08:00
}
}