#ifndef CHILON_PARSER_UNTIL_HPP
#define CHILON_PARSER_UNTIL_HPP
#include <chilon/parser/parse.hpp>
#include <chilon/parser/choice.hpp>
#include <chilon/parser/stored.hpp>
#include <chilon/parser/skipped.hpp>
#include <chilon/meta/flatten.hpp>
#include <chilon/meta/switch_template.hpp>
#include <chilon/meta/list.hpp>
#include <vector>
namespace chilon { namespace parser {
template <class Limit, class Match, bool Skip_whitespace>
struct until_base {
template <class Stream>
inline static bool skip(Stream& stream) {
while (! Limit::skip(stream) && ! stream.empty()) {
if (! Match::skip(stream)) return false;
if (Skip_whitespace) stream.skip_whitespace();
}
return true;
}
template <class Stream>
inline static bool match(Stream& stream) {
auto beginBackup = stream.begin();
while (! Limit::skip(stream) && ! stream.empty()) {
if (! Match::skip(stream)) {
stream.begin() = beginBackup;
return false;
}
if (Skip_whitespace) stream.skip_whitespace();
}
stream.begin() = beginBackup;
return true;
}
};
/**
* Ordered choice (Match .^*? Limit) storing range.
*/
template <class Limit, class Match>
struct until_range : until_base<Limit, Match, false> {};
template <class Limit, class Match>
struct until_list : until_base<Limit, Match, true> {};
template <class Limit, class Match>
struct parse< until_range<Limit, Match> > {
typedef range store_type;
template <class Stream, class Output>
inline static bool skip(Stream& stream, Output& output) {
output.begin() = stream.begin();
while (! Limit::skip(stream) && ! stream.empty()) {
if (! Match::skip(stream)) {
// TODO: don't always reset this
stream.begin() = output.begin();
return false;
}
else {
// is this optimal?
output.end() = stream.begin();
}
}
return true;
}
};
template <class Limit, class Match>
struct parse< until_list<Limit, Match> > {
typedef typename stored<Match>::type vector_element_type;
typedef std::vector<vector_element_type> store_type;
typedef typename meta::flatten_type<
meta::list, choice, Limit>::type limit_list;
template <class Stream, class Output>
inline static bool skip(Stream& stream, Output& output) {
while (! Limit::skip(stream) && ! stream.empty()) {
// TODO: reset instead of recreating in loop?
vector_element_type current_element;
if (! parse<Match>::skip(stream, current_element)) {
return false;
}
else {
output.push_back(current_element);
stream.template skip_whitespace_without<limit_list>();
}
}
return true;
}
};
namespace detail {
template <class Limit, class Match, class W>
struct make_until : parse_forward<until_list<Limit, Match>> {};
template <class Limit, class Match>
struct make_until<Limit, Match, char>
: parse_forward<until_range<Limit, Match>> {};
}
/**
* Forward to either until_range or until_list depending on types.
*/
template <class Limit, class Match>
struct until :
detail::make_until<Limit, Match, typename skipped_store<Match>::type> {};
} }
#endif