Headers move, CMake targets merge, C++ namespaces stay unchanged: - Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant - Functional: Pipeline, Either, Result, Retry - Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval - Math: +Matrix, Numeric, Random, Histogram - Text: Str, Format, Tokenizer, Diff, Encoding, Semver - Data: Json, Csv, Ini - Async: Coro, Concurrency, EventBus, Observable - Time: +Bench - Log: Log facade + Logging framework (facade now header-only, breaking the Stacktrace<->Log link cycle the merge would have created) - System: FileSystem + Process - Configuration: +Argparse - Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail Module system fixes: - OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no longer depends on the alphabetical discovery order of src/ subdirs (Testing -> Text would have been silently dropped). - Every header-only module now has a tracked module.cmake; previously the empty src/<Name> marker dirs were untracked, so a fresh clone would have silently skipped those modules. - VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT. Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files prefixed: ResultBasic etc.). Test count verified identical (831) before and after. README/CLAUDE.md module tables updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
190 lines
6.1 KiB
C++
190 lines
6.1 KiB
C++
#pragma once
|
|
|
|
#include <cctype>
|
|
#include <cstddef>
|
|
#include <functional>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <variant>
|
|
#include <vector>
|
|
|
|
namespace Void::Tokenizer
|
|
{
|
|
|
|
// ── Token ─────────────────────────────────────────────────────────────────────
|
|
|
|
struct Token {
|
|
std::string kind; // rule name / category
|
|
std::string value; // raw matched text
|
|
std::size_t line; // 1-based
|
|
std::size_t col; // 1-based, column of first char
|
|
};
|
|
|
|
// ── Rule ──────────────────────────────────────────────────────────────────────
|
|
// A rule matches a prefix of the remaining input.
|
|
// Returns the number of characters consumed, or 0 on no match.
|
|
|
|
using MatchFn = std::function<std::size_t(std::string_view)>;
|
|
|
|
struct Rule {
|
|
std::string kind;
|
|
MatchFn match;
|
|
bool skip{false}; // if true, consume but do not emit a token
|
|
};
|
|
|
|
// ── Built-in match helpers ────────────────────────────────────────────────────
|
|
|
|
// Matches a fixed literal string.
|
|
[[nodiscard]] inline MatchFn literal(std::string_view s)
|
|
{
|
|
return [s = std::string{s}](std::string_view in) -> std::size_t {
|
|
if (in.starts_with(s)) return s.size();
|
|
return 0;
|
|
};
|
|
}
|
|
|
|
// Matches one or more characters satisfying a predicate.
|
|
[[nodiscard]] inline MatchFn chars(std::function<bool(char)> pred, std::size_t min = 1)
|
|
{
|
|
return [pred, min](std::string_view in) -> std::size_t {
|
|
std::size_t n = 0;
|
|
while (n < in.size() && pred(in[n])) ++n;
|
|
return n >= min ? n : 0;
|
|
};
|
|
}
|
|
|
|
// Common character classes.
|
|
[[nodiscard]] inline MatchFn alpha()
|
|
{
|
|
return chars([](char c) { return std::isalpha(static_cast<unsigned char>(c)) != 0; });
|
|
}
|
|
[[nodiscard]] inline MatchFn digit()
|
|
{
|
|
return chars([](char c) { return std::isdigit(static_cast<unsigned char>(c)) != 0; });
|
|
}
|
|
[[nodiscard]] inline MatchFn alnum_or_underscore()
|
|
{
|
|
return chars([](char c) {
|
|
return std::isalnum(static_cast<unsigned char>(c)) != 0 || c == '_';
|
|
});
|
|
}
|
|
[[nodiscard]] inline MatchFn whitespace()
|
|
{
|
|
return chars([](char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; });
|
|
}
|
|
|
|
// Matches a C-style identifier: [a-zA-Z_][a-zA-Z0-9_]*
|
|
[[nodiscard]] inline MatchFn identifier()
|
|
{
|
|
return [](std::string_view in) -> std::size_t {
|
|
if (in.empty()) return 0;
|
|
const char first = in[0];
|
|
if (!std::isalpha(static_cast<unsigned char>(first)) && first != '_') return 0;
|
|
std::size_t n = 1;
|
|
while (n < in.size() &&
|
|
(std::isalnum(static_cast<unsigned char>(in[n])) || in[n] == '_'))
|
|
++n;
|
|
return n;
|
|
};
|
|
}
|
|
|
|
// Matches a decimal integer literal.
|
|
[[nodiscard]] inline MatchFn integer_literal()
|
|
{
|
|
return [](std::string_view in) -> std::size_t {
|
|
if (in.empty()) return 0;
|
|
std::size_t n = 0;
|
|
if (in[0] == '-' || in[0] == '+') ++n;
|
|
const std::size_t start = n;
|
|
while (n < in.size() && std::isdigit(static_cast<unsigned char>(in[n]))) ++n;
|
|
return n > start ? n : 0;
|
|
};
|
|
}
|
|
|
|
// Matches a double-quoted string (with simple backslash escape).
|
|
[[nodiscard]] inline MatchFn quoted_string()
|
|
{
|
|
return [](std::string_view in) -> std::size_t {
|
|
if (in.empty() || in[0] != '"') return 0;
|
|
std::size_t n = 1;
|
|
while (n < in.size()) {
|
|
if (in[n] == '\\') { n += 2; continue; }
|
|
if (in[n] == '"') { ++n; return n; }
|
|
++n;
|
|
}
|
|
return 0; // unterminated
|
|
};
|
|
}
|
|
|
|
// ── Tokenizer ─────────────────────────────────────────────────────────────────
|
|
// Greedy first-match: the first rule that matches at the current position wins.
|
|
|
|
class Tokenizer
|
|
{
|
|
public:
|
|
void add_rule(Rule rule) { rules_.push_back(std::move(rule)); }
|
|
|
|
void skip(std::string kind, MatchFn fn)
|
|
{
|
|
rules_.push_back({std::move(kind), std::move(fn), true});
|
|
}
|
|
|
|
struct Error {
|
|
std::size_t line;
|
|
std::size_t col;
|
|
char unexpected;
|
|
std::string message;
|
|
};
|
|
|
|
// Tokenize input, returning all tokens (skipped rules emit nothing).
|
|
// On unrecognized input returns an error.
|
|
[[nodiscard]] std::variant<std::vector<Token>, Error>
|
|
tokenize(std::string_view input) const
|
|
{
|
|
std::vector<Token> tokens;
|
|
std::size_t pos = 0;
|
|
std::size_t line = 1, col = 1;
|
|
|
|
while (pos < input.size()) {
|
|
bool matched = false;
|
|
for (const auto& rule : rules_) {
|
|
const std::size_t n = rule.match(input.substr(pos));
|
|
if (n == 0) continue;
|
|
if (!rule.skip) {
|
|
tokens.push_back({rule.kind,
|
|
std::string{input.substr(pos, n)},
|
|
line, col});
|
|
}
|
|
// Update position bookkeeping
|
|
for (std::size_t i = 0; i < n; ++i) {
|
|
if (input[pos + i] == '\n') { ++line; col = 1; }
|
|
else { ++col; }
|
|
}
|
|
pos += n;
|
|
matched = true;
|
|
break;
|
|
}
|
|
if (!matched) {
|
|
return Error{line, col, input[pos],
|
|
std::string{"unexpected character: '"} + input[pos] + "'"};
|
|
}
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
// Convenience: throws on error.
|
|
[[nodiscard]] std::vector<Token> tokenize_or_throw(std::string_view input) const
|
|
{
|
|
auto result = tokenize(input);
|
|
if (auto* err = std::get_if<Error>(&result))
|
|
throw std::runtime_error{err->message};
|
|
return std::get<std::vector<Token>>(std::move(result));
|
|
}
|
|
|
|
private:
|
|
std::vector<Rule> rules_;
|
|
};
|
|
|
|
} // namespace Void::Tokenizer
|