Text: add ICU-style message formatting, plural rules and catalog (#56)

This commit is contained in:
faumaray committed 2026-12-04 10:04:14 +03:00
1 parent 55a1399e01
commit 3010b8a913
2 files changed
+1215

No files matched your search

+906
View File
@@ -0,0 +1,906 @@
#pragma once
#include <Void/Text/Str.hpp>
#include <algorithm>
#include <array>
#include <charconv>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <format>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <variant>
#include <vector>
namespace Void::Text::I18n
{
// ── Errors ───────────────────────────────────────────────────────────────────
struct I18nError
{
enum class Code : std::uint8_t
{
invalid_pattern,
unsupported_type,
unknown_argument,
wrong_argument_type,
missing_branch,
missing_key,
invalid_catalog,
limit
};
Code code{Code::invalid_pattern};
/// Byte offset in the pattern (format/validate) or in the catalog source
/// (load). Zero when the error is not position-specific.
std::size_t offset{0};
/// Argument or catalog key involved, when applicable.
std::string key{};
[[nodiscard]] bool operator==(const I18nError&) const noexcept = default;
};
// ── Arguments ────────────────────────────────────────────────────────────────
/// One message argument: either text (for `{name}` and `select`) or a number
/// (for `plural` and `#`).
using Argument = std::variant<std::string, double>;
using Arguments = std::map<std::string, Argument, std::less<>>;
// ── Plural categories ────────────────────────────────────────────────────────
enum class PluralCategory : std::uint8_t
{
zero,
one,
two,
few,
many,
other
};
[[nodiscard]] constexpr std::string_view
plural_category_name(PluralCategory category) noexcept
{
switch (category) {
case PluralCategory::zero: return "zero";
case PluralCategory::one: return "one";
case PluralCategory::two: return "two";
case PluralCategory::few: return "few";
case PluralCategory::many: return "many";
case PluralCategory::other: return "other";
}
return "other";
}
/// Primary language subtag, lowercased ("ru-RU" → "ru").
[[nodiscard]] inline std::string_view
locale_language_view(std::string_view locale) noexcept
{
return locale.substr(0, locale.find_first_of("-_"));
}
[[nodiscard]] inline bool locale_is(std::string_view locale,
std::string_view language) noexcept
{
return Void::Str::iequals_ascii(locale_language_view(locale), language);
}
[[nodiscard]] inline std::string locale_language(std::string_view locale)
{
return Void::Str::to_lower_ascii(locale_language_view(locale));
}
/// CLDR cardinal plural category for the supported locale set. Locales
/// without a dedicated rule fall back to the English one/other distinction.
/// Exact ICU vectors are covered for English and Russian; Arabic, Czech,
/// French, Polish and the no-plural languages are best-effort.
[[nodiscard]] inline PluralCategory
plural_category(std::string_view locale, double value) noexcept
{
if (!std::isfinite(value)) {
return PluralCategory::other;
}
const double n = std::abs(value);
const bool integer = n == std::trunc(n);
const auto i = static_cast<std::uint64_t>(integer ? n : 0);
const std::uint64_t mod10 = i % 10;
const std::uint64_t mod100 = i % 100;
if (locale_is(locale, "ja") || locale_is(locale, "ko") ||
locale_is(locale, "zh") || locale_is(locale, "th") ||
locale_is(locale, "vi") || locale_is(locale, "id")) {
return PluralCategory::other;
}
if (locale_is(locale, "ar")) {
if (n == 0) return PluralCategory::zero;
if (n == 1) return PluralCategory::one;
if (n == 2) return PluralCategory::two;
if (mod100 >= 3 && mod100 <= 10) return PluralCategory::few;
if (mod100 >= 11 && mod100 <= 99) return PluralCategory::many;
return PluralCategory::other;
}
if (locale_is(locale, "ru") || locale_is(locale, "pl")) {
if (!integer) return PluralCategory::other;
if (mod10 == 1 && mod100 != 11) return PluralCategory::one;
if (mod10 >= 2 && mod10 <= 4 &&
!(mod100 >= 12 && mod100 <= 14)) {
return PluralCategory::few;
}
return PluralCategory::many;
}
if (locale_is(locale, "cs")) {
if (!integer) return PluralCategory::many;
if (i == 1) return PluralCategory::one;
if (i >= 2 && i <= 4) return PluralCategory::few;
return PluralCategory::other;
}
if (locale_is(locale, "fr")) {
if (integer && i <= 1) return PluralCategory::one;
return PluralCategory::other;
}
// en, de, es, it, nl, pt, sv, ... and the fallback.
return n == 1 ? PluralCategory::one : PluralCategory::other;
}
// ── Locale-aware number formatting ──────────────────────────────────────────
struct NumberSymbols
{
char grouping{','};
char decimal{'.'};
};
[[nodiscard]] inline NumberSymbols
number_symbols(std::string_view locale) noexcept
{
if (locale_is(locale, "de") || locale_is(locale, "it") ||
locale_is(locale, "es")) {
return NumberSymbols{'.', ','};
}
if (locale_is(locale, "fr")) {
return NumberSymbols{' ', ','};
}
if (locale_is(locale, "ru") || locale_is(locale, "uk") ||
locale_is(locale, "pl") || locale_is(locale, "cs") ||
locale_is(locale, "sv") || locale_is(locale, "fi")) {
return NumberSymbols{' ', ','};
}
return NumberSymbols{',', '.'};
}
/// Formats a decimal number with locale grouping and decimal separators.
/// Trailing fractional zeros are removed; at most `max_fraction_digits`
/// fractional digits are emitted.
[[nodiscard]] inline std::string
format_decimal(std::string_view locale, double value,
int max_fraction_digits = 3)
{
if (!std::isfinite(value)) {
return std::format("{}", value);
}
if (max_fraction_digits < 0) {
max_fraction_digits = 0;
}
const NumberSymbols symbols = number_symbols(locale);
std::string fixed =
std::format("{:.{}f}", value, static_cast<std::size_t>(max_fraction_digits));
if (fixed.find('.') != std::string::npos) {
while (!fixed.empty() && fixed.back() == '0') {
fixed.pop_back();
}
if (!fixed.empty() && fixed.back() == '.') {
fixed.pop_back();
}
}
if (fixed.empty()) {
fixed = "0";
}
bool negative = false;
if (fixed.front() == '-') {
negative = true;
fixed.erase(fixed.begin());
}
const std::size_t point = fixed.find('.');
std::string integer =
point == std::string::npos ? fixed : fixed.substr(0, point);
const std::string fraction =
point == std::string::npos ? std::string{} : fixed.substr(point + 1);
std::string grouped;
grouped.reserve(integer.size() + integer.size() / 3 + 1);
for (std::size_t index = 0; index < integer.size(); ++index) {
if (index > 0 && (integer.size() - index) % 3 == 0) {
grouped.push_back(symbols.grouping);
}
grouped.push_back(integer[index]);
}
std::string out;
if (negative) {
out.push_back('-');
}
out += grouped;
if (!fraction.empty()) {
out.push_back(symbols.decimal);
out += fraction;
}
return out;
}
// ── ICU message formatting (documented subset) ──────────────────────────────
//
// Supported syntax:
// {name} simple argument
// {name, plural, offset:N ...} plural with `=N` exact branches,
// CLDR categories and `#`
// {name, select, key {...} other {...}} select
// '' '{' '}' '#' ICU apostrophe quoting
//
// `#` inside a plural branch expands to the plural value minus `offset`.
// Nested messages are supported up to an internal depth limit. Apostrophe
// quoting follows the simplified ICU form: `''` is a literal apostrophe and an
// apostrophe before `{`, `}` or `#` starts a quoted literal that ends at the
// next apostrophe. `number`/`date`/`choice` argument types and skeletons are
// not implemented; they are rejected as unsupported types rather than guessed.
namespace Detail
{
struct AstNode
{
enum class Kind : std::uint8_t
{
text,
argument,
pound,
plural,
select
};
Kind kind{Kind::text};
std::string text;
double offset{0};
std::vector<std::pair<std::string, std::size_t>> branches;
};
struct AstMessage
{
std::vector<std::size_t> nodes;
};
struct Ast
{
std::vector<AstNode> nodes;
std::vector<AstMessage> messages;
[[nodiscard]] std::size_t add_message()
{
messages.emplace_back();
return messages.size() - 1;
}
[[nodiscard]] std::size_t add_node(AstNode node)
{
nodes.push_back(std::move(node));
return nodes.size() - 1;
}
};
class Parser
{
public:
explicit Parser(std::string_view input, Ast& ast) noexcept
: input_(input), ast_(ast)
{
}
[[nodiscard]] std::expected<std::size_t, I18nError> parse()
{
const auto root = parse_message(false, 0);
if (!root) {
return root;
}
if (position_ != input_.size()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, position_, {}}};
}
return root;
}
private:
static constexpr std::size_t max_depth = 16;
[[nodiscard]] bool at_end() const noexcept
{
return position_ >= input_.size();
}
[[nodiscard]] char peek(std::size_t ahead = 0) const noexcept
{
return position_ + ahead < input_.size()
? input_[position_ + ahead]
: '\0';
}
void skip_spaces() noexcept
{
while (!at_end() && (peek() == ' ' || peek() == '\t' ||
peek() == '\r' || peek() == '\n')) {
++position_;
}
}
[[nodiscard]] std::string_view parse_identifier() noexcept
{
const std::size_t begin = position_;
while (!at_end()) {
const char c = peek();
if (!Void::Str::is_ascii_alnum(c) && c != '_' && c != '.' &&
c != '-') {
break;
}
++position_;
}
return input_.substr(begin, position_ - begin);
}
[[nodiscard]] std::expected<double, I18nError> parse_number()
{
const std::size_t begin = position_;
if (peek() == '-') {
++position_;
}
while (!at_end() && Void::Str::is_ascii_digit(peek())) {
++position_;
}
if (peek() == '.') {
++position_;
while (!at_end() && Void::Str::is_ascii_digit(peek())) {
++position_;
}
}
double value = 0;
const char* first = input_.data() + begin;
const char* last = input_.data() + position_;
const auto [pointer, error] = std::from_chars(first, last, value);
if (error != std::errc{} || pointer != last) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, begin, {}}};
}
return value;
}
[[nodiscard]] std::expected<std::size_t, I18nError>
parse_message(bool in_plural, std::size_t depth)
{
if (depth > max_depth) {
return std::unexpected{I18nError{
I18nError::Code::limit, position_, {}}};
}
const std::size_t message = ast_.add_message();
std::string text;
const auto flush_text = [&] {
if (text.empty()) {
return;
}
AstNode node;
node.kind = AstNode::Kind::text;
node.text = std::move(text);
text.clear();
ast_.messages[message].nodes.push_back(
ast_.add_node(std::move(node)));
};
while (!at_end()) {
if (peek() == '}') {
break; // Caller consumes the closing brace.
}
const char c = peek();
if (c == '\'') {
if (peek(1) == '\'') {
text.push_back('\'');
position_ += 2;
} else if (peek(1) == '{' || peek(1) == '}' ||
peek(1) == '#') {
++position_; // Opening quote.
while (!at_end() && peek() != '\'') {
text.push_back(peek());
++position_;
}
if (!at_end()) {
++position_; // Closing quote.
}
} else {
text.push_back('\'');
++position_;
}
} else if (c == '{') {
flush_text();
auto node = parse_argument(in_plural, depth);
if (!node) {
return std::unexpected{node.error()};
}
ast_.messages[message].nodes.push_back(*node);
} else if (c == '#' && in_plural) {
flush_text();
AstNode node;
node.kind = AstNode::Kind::pound;
ast_.messages[message].nodes.push_back(
ast_.add_node(std::move(node)));
++position_;
} else {
text.push_back(c);
++position_;
}
}
flush_text();
return message;
}
[[nodiscard]] std::expected<std::size_t, I18nError>
parse_argument(bool in_plural, std::size_t depth)
{
const std::size_t begin = position_;
++position_; // '{'
skip_spaces();
const std::string_view name = parse_identifier();
if (name.empty()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, begin, {}}};
}
skip_spaces();
if (peek() == '}') {
++position_;
AstNode node;
node.kind = AstNode::Kind::argument;
node.text = std::string{name};
return ast_.add_node(std::move(node));
}
if (peek() != ',') {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, position_, {}}};
}
++position_;
skip_spaces();
const std::size_t type_begin = position_;
const std::string_view type = parse_identifier();
if (type.empty()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, type_begin, {}}};
}
skip_spaces();
if (peek() == ',') {
++position_;
skip_spaces();
}
if (type == "plural") {
return parse_plural(std::string{name}, depth);
}
if (type == "select") {
return parse_select(std::string{name}, in_plural, depth);
}
return std::unexpected{I18nError{
I18nError::Code::unsupported_type, type_begin,
std::string{type}}};
}
[[nodiscard]] std::expected<std::size_t, I18nError>
parse_branch(std::string_view selector, bool in_plural,
std::size_t depth,
std::vector<std::pair<std::string, std::size_t>>&
branches)
{
for (const auto& [existing, message] : branches) {
(void)message;
if (existing == selector) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, position_,
std::string{selector}}};
}
}
skip_spaces();
if (peek() != '{') {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, position_, {}}};
}
++position_;
const auto child = parse_message(in_plural, depth + 1);
if (!child) {
return std::unexpected{child.error()};
}
if (peek() != '}') {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, position_, {}}};
}
++position_;
branches.emplace_back(std::string{selector}, *child);
return {};
}
[[nodiscard]] std::expected<void, I18nError>
finish_branches(const std::vector<std::pair<std::string,
std::size_t>>&
branches,
std::size_t begin)
{
bool has_other = false;
for (const auto& [selector, message] : branches) {
(void)message;
has_other = has_other || selector == "other";
}
if (!has_other) {
return std::unexpected{I18nError{
I18nError::Code::missing_branch, begin, "other"}};
}
return {};
}
[[nodiscard]] std::expected<std::size_t, I18nError>
parse_plural(std::string name, std::size_t depth)
{
AstNode node;
node.kind = AstNode::Kind::plural;
node.text = std::move(name);
skip_spaces();
if (input_.substr(position_).starts_with("offset:")) {
position_ += 7;
skip_spaces();
auto offset = parse_number();
if (!offset) {
return std::unexpected{offset.error()};
}
node.offset = *offset;
skip_spaces();
}
const std::size_t begin = position_;
for (;;) {
skip_spaces();
if (at_end()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, begin, {}}};
}
if (peek() == '}') {
++position_;
break;
}
const std::size_t selector_begin = position_;
std::string selector;
if (peek() == '=') {
++position_;
auto exact = parse_number();
if (!exact) {
return std::unexpected{exact.error()};
}
selector = std::format("={}", *exact);
} else {
selector = std::string{parse_identifier()};
}
if (selector.empty()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, selector_begin,
{}}};
}
auto branch = parse_branch(selector, true, depth,
node.branches);
if (!branch) {
return std::unexpected{branch.error()};
}
}
auto complete = finish_branches(node.branches, begin);
if (!complete) {
return std::unexpected{complete.error()};
}
return ast_.add_node(std::move(node));
}
[[nodiscard]] std::expected<std::size_t, I18nError>
parse_select(std::string name, bool in_plural, std::size_t depth)
{
AstNode node;
node.kind = AstNode::Kind::select;
node.text = std::move(name);
const std::size_t begin = position_;
for (;;) {
skip_spaces();
if (at_end()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, begin, {}}};
}
if (peek() == '}') {
++position_;
break;
}
const std::size_t selector_begin = position_;
const std::string selector{parse_identifier()};
if (selector.empty()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, selector_begin,
{}}};
}
auto branch = parse_branch(selector, in_plural, depth,
node.branches);
if (!branch) {
return std::unexpected{branch.error()};
}
}
auto complete = finish_branches(node.branches, begin);
if (!complete) {
return std::unexpected{complete.error()};
}
return ast_.add_node(std::move(node));
}
std::string_view input_;
Ast& ast_;
std::size_t position_{0};
};
[[nodiscard]] inline std::string format_plural_value(double value)
{
return std::format("{}", value);
}
[[nodiscard]] inline const std::pair<std::string, std::size_t>*
find_branch(const AstNode& node, std::string_view selector) noexcept
{
for (const auto& branch : node.branches) {
if (branch.first == selector) {
return &branch;
}
}
return nullptr;
}
[[nodiscard]] inline std::expected<std::string, I18nError>
format_message(const Ast& ast, std::size_t message_index,
std::string_view locale, const Arguments& arguments,
std::optional<double> pound_value)
{
std::string out;
const AstMessage& message = ast.messages[message_index];
for (const std::size_t node_index : message.nodes) {
const AstNode& node = ast.nodes[node_index];
switch (node.kind) {
case AstNode::Kind::text:
out += node.text;
break;
case AstNode::Kind::pound:
if (!pound_value.has_value()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_pattern, 0, "#"}};
}
out += format_plural_value(*pound_value);
break;
case AstNode::Kind::argument: {
const auto found = arguments.find(node.text);
if (found == arguments.end()) {
return std::unexpected{I18nError{
I18nError::Code::unknown_argument, 0, node.text}};
}
if (const auto* text =
std::get_if<std::string>(&found->second)) {
out += *text;
} else {
out += format_plural_value(
std::get<double>(found->second));
}
break;
}
case AstNode::Kind::plural: {
const auto found = arguments.find(node.text);
if (found == arguments.end()) {
return std::unexpected{I18nError{
I18nError::Code::unknown_argument, 0, node.text}};
}
const auto* number = std::get_if<double>(&found->second);
if (number == nullptr) {
return std::unexpected{I18nError{
I18nError::Code::wrong_argument_type, 0,
node.text}};
}
const std::pair<std::string, std::size_t>* branch =
find_branch(node, std::format("={}", *number));
if (branch == nullptr) {
const double adjusted = *number - node.offset;
branch = find_branch(
node, plural_category_name(
plural_category(locale, adjusted)));
}
if (branch == nullptr) {
branch = find_branch(node, "other");
}
if (branch == nullptr) {
return std::unexpected{I18nError{
I18nError::Code::missing_branch, 0, node.text}};
}
auto nested = format_message(ast, branch->second, locale,
arguments,
*number - node.offset);
if (!nested) {
return nested;
}
out += *nested;
break;
}
case AstNode::Kind::select: {
const auto found = arguments.find(node.text);
if (found == arguments.end()) {
return std::unexpected{I18nError{
I18nError::Code::unknown_argument, 0, node.text}};
}
const auto* text = std::get_if<std::string>(&found->second);
if (text == nullptr) {
return std::unexpected{I18nError{
I18nError::Code::wrong_argument_type, 0,
node.text}};
}
const std::pair<std::string, std::size_t>* branch =
find_branch(node, *text);
if (branch == nullptr) {
branch = find_branch(node, "other");
}
if (branch == nullptr) {
return std::unexpected{I18nError{
I18nError::Code::missing_branch, 0, node.text}};
}
auto nested = format_message(ast, branch->second, locale,
arguments, pound_value);
if (!nested) {
return nested;
}
out += *nested;
break;
}
}
}
return out;
}
} // namespace Detail
/// Parses and validates an ICU-style pattern without formatting it.
[[nodiscard]] inline std::expected<void, I18nError>
validate(std::string_view pattern)
{
Detail::Ast ast;
Detail::Parser parser{pattern, ast};
auto root = parser.parse();
if (!root) {
return std::unexpected{root.error()};
}
(void)root;
return {};
}
/// Formats an ICU-style pattern. Missing arguments, wrong argument types and
/// malformed patterns are reported as errors instead of being left in place.
[[nodiscard]] inline std::expected<std::string, I18nError>
format(std::string_view pattern, std::string_view locale,
const Arguments& arguments)
{
Detail::Ast ast;
Detail::Parser parser{pattern, ast};
auto root = parser.parse();
if (!root) {
return std::unexpected{root.error()};
}
return Detail::format_message(ast, *root, locale, arguments, std::nullopt);
}
// ── Message catalog ─────────────────────────────────────────────────────────
/// Validated message catalog. The text format is one `key = pattern` per
/// line; blank lines and lines starting with `#` are ignored. Keys must be
/// unique and patterns are validated while loading.
class Catalog
{
public:
[[nodiscard]] std::expected<void, I18nError>
set(std::string key, std::string pattern)
{
if (key.empty()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_catalog, 0, std::move(key)}};
}
auto valid = validate(pattern);
if (!valid) {
return std::unexpected{valid.error()};
}
messages_.insert_or_assign(std::move(key), std::move(pattern));
return {};
}
[[nodiscard]] std::expected<void, I18nError>
load(std::string_view source)
{
std::size_t line_begin = 0;
while (line_begin <= source.size()) {
const std::size_t line_end = source.find('\n', line_begin);
const std::string_view line =
source.substr(line_begin, line_end == std::string_view::npos
? std::string_view::npos
: line_end - line_begin);
const std::string_view trimmed = Void::Str::trim_ascii(line);
if (!trimmed.empty() && !trimmed.starts_with('#')) {
const std::size_t equals = line.find('=');
if (equals == std::string_view::npos) {
return std::unexpected{I18nError{
I18nError::Code::invalid_catalog, line_begin, {}}};
}
const std::string_view key =
Void::Str::trim_ascii(line.substr(0, equals));
const std::string_view pattern =
Void::Str::trim_ascii(line.substr(equals + 1));
if (key.empty()) {
return std::unexpected{I18nError{
I18nError::Code::invalid_catalog, line_begin, {}}};
}
if (messages_.contains(key)) {
return std::unexpected{I18nError{
I18nError::Code::invalid_catalog, line_begin,
std::string{key}}};
}
auto stored = set(std::string{key}, std::string{pattern});
if (!stored) {
I18nError error = stored.error();
error.offset += line_begin + equals + 1;
return std::unexpected{std::move(error)};
}
}
if (line_end == std::string_view::npos) {
break;
}
line_begin = line_end + 1;
}
return {};
}
[[nodiscard]] const std::string* find(std::string_view key) const
noexcept
{
const auto found = messages_.find(key);
return found == messages_.end() ? nullptr : &found->second;
}
[[nodiscard]] std::expected<std::string, I18nError>
format(std::string_view key, std::string_view locale,
const Arguments& arguments) const
{
const std::string* pattern = find(key);
if (pattern == nullptr) {
return std::unexpected{I18nError{
I18nError::Code::missing_key, 0, std::string{key}}};
}
return Void::Text::I18n::format(*pattern, locale, arguments);
}
[[nodiscard]] std::size_t size() const noexcept
{
return messages_.size();
}
[[nodiscard]] bool empty() const noexcept
{
return messages_.empty();
}
private:
std::map<std::string, std::string, std::less<>> messages_;
};
} // namespace Void::Text::I18n