C++#pragma once
#include <bits/stdc++.h>
#include <filesystem>
using namespace std;
namespace vld {
namespace fs = std::filesystem;
struct Error {
string file;
int line = 1;
int col = 1;
string msg;
};
struct StopParse {};
struct RawOptions {
bool forbidCR = true;
bool forbidTab = true;
bool forbidTrailingSpace = true;
bool requireExactlyOneFinalLF = true;
};
struct RealOptions {
bool allowPlus = false;
bool allowMinus = true;
bool allowPoint = true;
bool requirePoint = false;
bool requireDigitBeforePoint = true;
bool requireDigitAfterPoint = true;
bool allowExp = false;
bool noLeadingZero = true;
int maxFracDigits = -1;
};
struct BatchOptions {
string dir = ".";
string logFile = "validator.log";
bool recursive = false;
bool autoEof = true;
bool makeBackup = false;
string backupSuffix = ".bak";
RawOptions raw;
};
enum class PatternMode {
Glob,
Regex
};
inline string normalizeText(string s) {
string t;
t.reserve(s.size() + 1);
for (size_t i = 0; i < s.size(); ++i) {
char c = s[i];
if (c == '\r') {
if (i + 1 < s.size() && s[i + 1] == '\n') continue;
c = '\n';
}
if (c == '\n') {
while (!t.empty() && (t.back() == ' ' || t.back() == '\t')) t.pop_back();
t.push_back('\n');
} else {
t.push_back(c);
}
}
while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\n')) {
t.pop_back();
}
t.push_back('\n');
return t;
}
class Input {
private:
string file;
string buf;
string out;
size_t p = 0;
int ln = 1, cl = 1;
vector<Error>* errors = nullptr;
RawOptions rawOpt;
bool formatMode = false;
void addError(int line, int col, const string& msg) {
if (errors) errors->push_back({file, line, col, msg});
else {
cerr << file << ":" << line << ":" << col << ": " << msg << '\n';
exit(1);
}
}
[[noreturn]] void fail(const string& msg) {
addError(ln, cl, msg);
throw StopParse();
}
string show(char c) const {
if (c == 0) return "EOF";
if (c == '\n') return "LF";
if (c == '\r') return "CR";
if (c == '\t') return "TAB";
if (c == ' ') return "space";
return string("'") + c + "'";
}
char peek() {
if (p >= buf.size()) return 0;
if (buf[p] == '\r') fail("CR byte found, CRLF is forbidden");
return buf[p];
}
char getRaw() {
char c = peek();
if (!c) fail("unexpected EOF");
++p;
if (c == '\n') {
++ln;
cl = 1;
} else {
++cl;
}
return c;
}
void emit(char c) {
if (formatMode) out.push_back(c);
}
void emit(const string& s) {
if (formatMode) out += s;
}
void expectStrict(char c, const string& name) {
char x = peek();
if (x != c) fail("expected " + name + ", got " + show(x));
getRaw();
}
string readRawToken() {
char c = peek();
if (c == 0 || c == ' ' || c == '\n' || c == '\t') {
fail("expected token, got " + show(c));
}
string s;
while (true) {
c = peek();
if (c == 0 || c == ' ' || c == '\n' || c == '\t') break;
s += getRaw();
}
return s;
}
string readIntTokenNoEmit() {
char c = peek();
if (c != '-' && !isdigit((unsigned char)c)) {
fail("expected integer, got " + show(c));
}
string s;
if (c == '-') {
s += getRaw();
if (!isdigit((unsigned char)peek())) fail("expected digit after '-'");
}
while (isdigit((unsigned char)peek())) {
s += getRaw();
}
string digits = s[0] == '-' ? s.substr(1) : s;
if (digits.size() > 1 && digits[0] == '0') fail("leading zero in integer");
if (s == "-0") fail("-0 is forbidden");
return s;
}
string readRealTokenNoEmit(RealOptions opt) {
string s;
char c = peek();
if (c == '+' || c == '-') {
if (c == '+' && !opt.allowPlus) fail("'+' sign is forbidden");
if (c == '-' && !opt.allowMinus) fail("'-' sign is forbidden");
s += getRaw();
}
int intDigits = 0;
while (isdigit((unsigned char)peek())) {
s += getRaw();
++intDigits;
}
bool hasPoint = false;
int fracDigits = 0;
if (peek() == '.') {
if (!opt.allowPoint) fail("decimal point is forbidden");
hasPoint = true;
s += getRaw();
while (isdigit((unsigned char)peek())) {
s += getRaw();
++fracDigits;
}
}
if (opt.requirePoint && !hasPoint) fail("decimal point is required");
if (opt.requireDigitBeforePoint && intDigits == 0) fail("digit before decimal point is required");
if (hasPoint && opt.requireDigitAfterPoint && fracDigits == 0) fail("digit after decimal point is required");
if (!hasPoint && intDigits == 0) fail("expected real number");
if (opt.maxFracDigits >= 0 && fracDigits > opt.maxFracDigits) fail("too many digits after decimal point");
if (opt.noLeadingZero && intDigits >= 2) {
size_t off = (!s.empty() && (s[0] == '-' || s[0] == '+')) ? 1 : 0;
if (s[off] == '0') fail("leading zero in real number");
}
if (peek() == 'e' || peek() == 'E') {
if (!opt.allowExp) fail("exponent is forbidden");
s += getRaw();
if (peek() == '+' || peek() == '-') s += getRaw();
int expDigits = 0;
while (isdigit((unsigned char)peek())) {
s += getRaw();
++expDigits;
}
if (expDigits == 0) fail("expected exponent digits");
}
return s;
}
public:
Input() = default;
Input(string filename, string content, vector<Error>* sink, RawOptions ro = {}, bool fmt = false)
: file(std::move(filename)), buf(std::move(content)), errors(sink), rawOpt(ro), formatMode(fmt) {
if (formatMode) buf = normalizeText(buf);
else rawCheck();
}
void rawCheck() {
if (buf.empty()) {
addError(1, 1, "empty file");
throw StopParse();
}
int line = 1, col = 1;
bool fatal = false;
if (rawOpt.requireExactlyOneFinalLF) {
if (buf.back() != '\n') {
addError(1, 1, "file must end with exactly one LF");
fatal = true;
} else if (buf.size() >= 2 && buf[buf.size() - 2] == '\n') {
int lastLine = 1;
for (char c : buf) {
if (c == '\n') ++lastLine;
}
addError(lastLine - 1, 1, "extra final LF: file must end with exactly one LF, not blank lines");
fatal = true;
}
}
for (size_t i = 0; i < buf.size(); ++i) {
char c = buf[i];
if (rawOpt.forbidCR && c == '\r') {
addError(line, col, "CR byte found, CRLF is forbidden");
fatal = true;
}
if (rawOpt.forbidTab && c == '\t') {
addError(line, col, "TAB byte found, use ordinary spaces only");
fatal = true;
}
if (c == '\n') {
if (rawOpt.forbidTrailingSpace && i > 0 && buf[i - 1] == ' ') {
addError(line, col - 1, "trailing space before LF is forbidden");
fatal = true;
}
++line;
col = 1;
} else {
++col;
}
}
if (fatal) throw StopParse();
}
int line() const { return ln; }
int col() const { return cl; }
string filename() const { return file; }
const string& formatted() const { return out; }
void ensure(bool ok, const string& msg) {
if (!ok) fail(msg);
}
void rdSpace(char c = ' ') {
if (formatMode && c == ' ') {
char x = peek();
if (x != ' ' && x != '\t') {
fail("expected space, got " + show(x));
}
while (peek() == ' ' || peek() == '\t') {
getRaw();
}
emit(' ');
} else {
string name = (c == ' ' ? "space" : string("'") + c + "'");
expectStrict(c, name);
emit(c);
}
}
void rdEoln() {
if (formatMode) {
while (peek() == ' ' || peek() == '\t') {
getRaw();
}
expectStrict('\n', "LF");
emit('\n');
} else {
expectStrict('\n', "LF");
}
}
void rdEof() {
if (p != buf.size()) fail("expected EOF, got " + show(peek()));
}
string rdToken() {
string s = readRawToken();
emit(s);
return s;
}
string rdTokenRegex(const string& pat, const string& name = "token") {
string s = readRawToken();
if (!regex_match(s, regex(pat))) {
fail(name + " does not match regex: " + s);
}
emit(s);
return s;
}
char rdChar() {
char c = peek();
if (c == 0 || c == '\n') fail("expected character, got " + show(c));
c = getRaw();
emit(c);
return c;
}
char rdChar(char expected) {
char c = peek();
if (c != expected) {
fail("expected character '" + string(1, expected) + "', got " + show(c));
}
getRaw();
emit(expected);
return expected;
}
char rdChar(char L, char R) {
char c = peek();
if (c == 0 || c == '\n') fail("expected character, got " + show(c));
if (c < L || c > R) {
fail("character " + show(c) + " out of range ['" + string(1, L) + "', '" + string(1, R) + "']");
}
c = getRaw();
emit(c);
return c;
}
char rdLnChar() {
char c = rdChar();
rdEoln();
return c;
}
char rdLnChar(char expected) {
char c = rdChar(expected);
rdEoln();
return c;
}
char rdLnChar(char L, char R) {
char c = rdChar(L, R);
rdEoln();
return c;
}
string rdString(int minLen, int maxLen) {
ensure(0 <= minLen && minLen <= maxLen, "internal error: bad string length range");
string s;
while (true) {
char c = peek();
if (c == 0 || c == ' ' || c == '\n' || c == '\t') break;
s += getRaw();
}
if ((int)s.size() < minLen || (int)s.size() > maxLen) {
fail("string length " + to_string(s.size()) + " out of range [" +
to_string(minLen) + ", " + to_string(maxLen) + "]");
}
emit(s);
return s;
}
string rdString(int minLen, int maxLen, const string& alphabet) {
string s = rdString(minLen, maxLen);
vector<unsigned char> ok(256, 0);
for (unsigned char c : alphabet) ok[c] = 1;
for (char c : s) {
if (!ok[(unsigned char)c]) {
fail("character " + show(c) + " is not in allowed alphabet");
}
}
return s;
}
template<class Pred>
string rdString(int minLen, int maxLen, Pred pred, const string& desc = "custom predicate") {
string s = rdString(minLen, maxLen);
for (char c : s) {
if (!pred(c)) {
fail("character " + show(c) + " does not satisfy " + desc);
}
}
return s;
}
string rdStringRegex(int minLen, int maxLen, const string& pat, const string& name = "string") {
string s = rdString(minLen, maxLen);
if (!regex_match(s, regex(pat))) {
fail(name + " does not match regex: " + s);
}
return s;
}
string rdLnString(int minLen, int maxLen) {
string s = rdString(minLen, maxLen);
rdEoln();
return s;
}
string rdLnString(int minLen, int maxLen, const string& alphabet) {
string s = rdString(minLen, maxLen, alphabet);
rdEoln();
return s;
}
template<class Pred>
string rdLnString(int minLen, int maxLen, Pred pred, const string& desc = "custom predicate") {
string s = rdString(minLen, maxLen, pred, desc);
rdEoln();
return s;
}
string rdLnStringRegex(int minLen, int maxLen, const string& pat, const string& name = "string") {
string s = rdStringRegex(minLen, maxLen, pat, name);
rdEoln();
return s;
}
string rdLine(int minLen, int maxLen) {
ensure(0 <= minLen && minLen <= maxLen, "internal error: bad line length range");
string s;
while (true) {
char c = peek();
if (c == 0 || c == '\n') break;
s += getRaw();
}
if ((int)s.size() < minLen || (int)s.size() > maxLen) {
fail("line length " + to_string(s.size()) + " out of range [" +
to_string(minLen) + ", " + to_string(maxLen) + "]");
}
rdEoln();
emit(s);
emit('\n');
return s;
}
template<class Pred>
string rdLine(int minLen, int maxLen, Pred pred, const string& desc = "custom predicate") {
string s = rdLine(minLen, maxLen);
for (char c : s) {
if (!pred(c)) {
fail("character " + show(c) + " does not satisfy " + desc);
}
}
return s;
}
static string normInt(string s) {
if (s.empty()) throw runtime_error("empty integer bound");
bool neg = false;
if (s[0] == '-') {
neg = true;
s.erase(s.begin());
if (s.empty()) throw runtime_error("bad integer bound");
}
for (char c : s) {
if (!isdigit((unsigned char)c)) throw runtime_error("bad integer bound: " + s);
}
int i = 0;
while (i + 1 < (int)s.size() && s[i] == '0') ++i;
s = s.substr(i);
if (s == "0") return "0";
return neg ? "-" + s : s;
}
static int cmpInt(string a, string b) {
a = normInt(a);
b = normInt(b);
bool na = a[0] == '-';
bool nb = b[0] == '-';
if (na != nb) return na ? -1 : 1;
string aa = na ? a.substr(1) : a;
string bb = nb ? b.substr(1) : b;
int c;
if (aa.size() != bb.size()) c = aa.size() < bb.size() ? -1 : 1;
else if (aa == bb) c = 0;
else c = aa < bb ? -1 : 1;
return na ? -c : c;
}
string rdIntToken() {
string x = readIntTokenNoEmit();
emit(x);
return x;
}
string rdInt(const string& L, const string& R) {
string l = normInt(L);
string r = normInt(R);
ensure(cmpInt(l, r) <= 0, "internal error: empty integer range");
string x = readIntTokenNoEmit();
if (cmpInt(x, l) < 0 || cmpInt(x, r) > 0) {
fail("integer " + x + " out of range [" + l + ", " + r + "]");
}
emit(x);
return x;
}
string rdInt(const char* L, const char* R) {
return rdInt(string(L), string(R));
}
long long rdInt(long long L, long long R) {
string x = rdInt(to_string(L), to_string(R));
return stoll(x);
}
string rdLnInt(const string& L, const string& R) {
string x = rdInt(L, R);
rdEoln();
return x;
}
string rdLnInt(const char* L, const char* R) {
string x = rdInt(string(L), string(R));
rdEoln();
return x;
}
long long rdLnInt(long long L, long long R) {
long long x = rdInt(L, R);
rdEoln();
return x;
}
vector<string> rdLnMultiInt(int cnt, const string& L, const string& R, char sep = ' ') {
ensure(cnt >= 0, "internal error: negative count");
vector<string> a;
a.reserve(cnt);
for (int i = 0; i < cnt; ++i) {
if (i) rdSpace(sep);
a.push_back(rdInt(L, R));
}
rdEoln();
return a;
}
vector<string> rdLnMultiInt(int cnt, const char* L, const char* R, char sep = ' ') {
return rdLnMultiInt(cnt, string(L), string(R), sep);
}
vector<long long> rdLnMultiInt(int cnt, long long L, long long R, char sep = ' ') {
ensure(cnt >= 0, "internal error: negative count");
vector<long long> a;
a.reserve(cnt);
for (int i = 0; i < cnt; ++i) {
if (i) rdSpace(sep);
a.push_back(rdInt(L, R));
}
rdEoln();
return a;
}
string rdRealToken(RealOptions opt = {}) {
string x = readRealTokenNoEmit(opt);
emit(x);
return x;
}
long double rdReal(long double L, long double R, RealOptions opt = {}) {
ensure(L <= R, "internal error: empty real range");
string s = readRealTokenNoEmit(opt);
errno = 0;
char* ed = nullptr;
long double x = strtold(s.c_str(), &ed);
if (!ed || *ed != '\0') fail("bad real number: " + s);
if (errno == ERANGE || !isfinite((double)x)) fail("real number is not finite: " + s);
if (x < L || x > R) {
ostringstream oss;
oss << "real " << s << " out of range [" << (double)L << ", " << (double)R << "]";
fail(oss.str());
}
emit(s);
return x;
}
long double rdLnReal(long double L, long double R, RealOptions opt = {}) {
long double x = rdReal(L, R, opt);
rdEoln();
return x;
}
vector<long double> rdLnMultiReal(int cnt, long double L, long double R, char sep = ' ', RealOptions opt = {}) {
ensure(cnt >= 0, "internal error: negative count");
vector<long double> a;
a.reserve(cnt);
for (int i = 0; i < cnt; ++i) {
if (i) rdSpace(sep);
a.push_back(rdReal(L, R, opt));
}
rdEoln();
return a;
}
};
inline string readFile(const fs::path& p) {
ifstream fin(p, ios::binary);
if (!fin) throw runtime_error("cannot open file");
return string((istreambuf_iterator<char>(fin)), istreambuf_iterator<char>());
}
inline void writeFile(const fs::path& p, const string& s) {
ofstream fout(p, ios::binary | ios::trunc);
if (!fout) throw runtime_error("cannot write file");
fout.write(s.data(), (streamsize)s.size());
if (!fout) throw runtime_error("write failed");
}
inline string globToRegex(const string& g) {
string r = "^";
for (char c : g) {
if (c == '*') r += ".*";
else if (c == '?') r += ".";
else {
static const string sp = R"(\.^$|()[]{}+)";
if (sp.find(c) != string::npos) r += '\\';
r += c;
}
}
r += "$";
return r;
}
inline bool nameMatch(const string& name, const string& pattern, PatternMode mode) {
return regex_match(name, regex(mode == PatternMode::Glob ? globToRegex(pattern) : pattern));
}
inline vector<fs::path> collectFiles(const string& pattern, const BatchOptions& opt, PatternMode mode) {
vector<fs::path> files;
if (opt.recursive) {
for (const auto& e : fs::recursive_directory_iterator(opt.dir)) {
if (!e.is_regular_file()) continue;
if (nameMatch(e.path().filename().string(), pattern, mode)) files.push_back(e.path());
}
} else {
for (const auto& e : fs::directory_iterator(opt.dir)) {
if (!e.is_regular_file()) continue;
if (nameMatch(e.path().filename().string(), pattern, mode)) files.push_back(e.path());
}
}
sort(files.begin(), files.end());
return files;
}
template<class Func>
bool validateOneFile(const fs::path& path, Func func, vector<Error>& all, const BatchOptions& opt) {
vector<Error> local;
string filename = path.string();
try {
Input in(filename, readFile(path), &local, opt.raw, false);
func(in);
if (opt.autoEof) in.rdEof();
} catch (const StopParse&) {
} catch (const exception& e) {
local.push_back({filename, 1, 1, string("internal validator exception: ") + e.what()});
}
bool ok = local.empty();
all.insert(all.end(), local.begin(), local.end());
return ok;
}
template<class Func>
bool validateAll(const string& pattern, Func func, BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
auto files = collectFiles(pattern, opt, mode);
vector<Error> all;
for (const auto& f : files) {
validateOneFile(f, func, all, opt);
}
ofstream log(opt.logFile, ios::binary);
if (!log) {
cerr << "cannot create log file: " << opt.logFile << '\n';
return false;
}
if (files.empty()) {
log << "no matched files: " << pattern << '\n';
cerr << "no matched files, see " << opt.logFile << '\n';
return false;
}
if (all.empty()) {
log << "all " << files.size() << " file(s) passed\n";
cerr << "all " << files.size() << " file(s) passed, see " << opt.logFile << '\n';
return true;
}
log << all.size() << " error(s) found in " << files.size() << " file(s)\n";
for (auto& e : all) {
log << e.file << ":" << e.line << ":" << e.col << ": " << e.msg << '\n';
}
cerr << all.size() << " error(s) found, see " << opt.logFile << '\n';
return false;
}
template<class Func>
int mainWithValidateAll(const string& pattern, Func func, BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
return validateAll(pattern, func, opt, mode) ? 0 : 1;
}
inline bool formatTextAll(const string& pattern = "*.in", BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
if (opt.logFile == "validator.log") opt.logFile = "format.log";
auto files = collectFiles(pattern, opt, mode);
vector<string> changed;
vector<string> same;
vector<string> failed;
for (const auto& f : files) {
try {
string old = readFile(f);
string neu = normalizeText(old);
if (old != neu) {
if (opt.makeBackup) {
writeFile(fs::path(f.string() + opt.backupSuffix), old);
}
writeFile(f, neu);
changed.push_back(f.string());
} else {
same.push_back(f.string());
}
} catch (const exception& e) {
failed.push_back(f.string() + ": " + e.what());
}
}
ofstream log(opt.logFile, ios::binary);
if (!log) {
cerr << "cannot create log file: " << opt.logFile << '\n';
return false;
}
if (files.empty()) {
log << "no matched files: " << pattern << '\n';
cerr << "no matched files, see " << opt.logFile << '\n';
return false;
}
log << "formatted text files: " << changed.size() << " changed, "
<< same.size() << " unchanged, " << failed.size() << " failed\n";
for (auto& x : changed) log << "[changed] " << x << '\n';
for (auto& x : failed) log << "[failed] " << x << '\n';
cerr << changed.size() << " changed, " << failed.size() << " failed, see " << opt.logFile << '\n';
return failed.empty();
}
template<class Func>
bool formatAll(const string& pattern, Func func, BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
if (opt.logFile == "validator.log") opt.logFile = "format.log";
auto files = collectFiles(pattern, opt, mode);
vector<Error> all;
vector<string> changed;
vector<string> same;
for (const auto& f : files) {
vector<Error> local;
string filename = f.string();
try {
string old = readFile(f);
Input in(filename, old, &local, opt.raw, true);
func(in);
if (opt.autoEof) in.rdEof();
if (local.empty()) {
string neu = in.formatted();
if (neu != old) {
if (opt.makeBackup) {
writeFile(fs::path(f.string() + opt.backupSuffix), old);
}
writeFile(f, neu);
changed.push_back(filename);
} else {
same.push_back(filename);
}
}
} catch (const StopParse&) {
} catch (const exception& e) {
local.push_back({filename, 1, 1, string("internal formatter exception: ") + e.what()});
}
all.insert(all.end(), local.begin(), local.end());
}
ofstream log(opt.logFile, ios::binary);
if (!log) {
cerr << "cannot create log file: " << opt.logFile << '\n';
return false;
}
if (files.empty()) {
log << "no matched files: " << pattern << '\n';
cerr << "no matched files, see " << opt.logFile << '\n';
return false;
}
if (all.empty()) {
log << "semantic format finished: " << changed.size()
<< " changed, " << same.size() << " unchanged\n";
for (auto& x : changed) log << "[changed] " << x << '\n';
cerr << changed.size() << " changed, see " << opt.logFile << '\n';
return true;
}
log << all.size() << " error(s), no write for failed files\n";
for (auto& e : all) {
log << e.file << ":" << e.line << ":" << e.col << ": " << e.msg << '\n';
}
for (auto& x : changed) {
log << "[changed] " << x << '\n';
}
cerr << all.size() << " error(s), " << changed.size()
<< " changed, see " << opt.logFile << '\n';
return false;
}
template<class Func>
int mainWithFormatAll(const string& pattern, Func func, BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
return formatAll(pattern, func, opt, mode) ? 0 : 1;
}
inline bool FormatAll(const string& pattern = "*.in", BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
return formatTextAll(pattern, opt, mode);
}
template<class Func>
bool FormatAll(const string& pattern, Func func, BatchOptions opt = {}, PatternMode mode = PatternMode::Glob) {
return formatAll(pattern, func, opt, mode);
}
}