diff --git a/include/Void/Data/StrictJson.hpp b/include/Void/Data/StrictJson.hpp index 9172ac7..2f92484 100644 --- a/include/Void/Data/StrictJson.hpp +++ b/include/Void/Data/StrictJson.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -41,6 +42,72 @@ namespace Void::Json::Strict ParseError error; }; + [[nodiscard]] constexpr std::size_t + validate_utf8_at(const std::string_view input, + const std::size_t pos) noexcept + { + if (pos >= input.size()) { + return 0U; + } + const auto b0 = static_cast(input[pos]); + if (b0 <= 0x7FU) { + return 1U; + } + if (b0 >= 0xC2U && b0 <= 0xDFU) { + if (pos + 1U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + return (b1 >= 0x80U && b1 <= 0xBFU) ? 2U : 0U; + } + if (b0 >= 0xE0U && b0 <= 0xEFU) { + if (pos + 2U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U; + const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU; + if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU) { + return 0U; + } + return 3U; + } + if (b0 >= 0xF0U && b0 <= 0xF4U) { + if (pos + 3U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const auto b3 = static_cast(input[pos + 3U]); + const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U; + const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU; + if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU || + b3 < 0x80U || b3 > 0xBFU) { + return 0U; + } + return 4U; + } + return 0U; + } + + [[nodiscard]] inline std::expected + validate_utf8_bytes(const std::string_view input) + { + std::size_t pos = 0U; + while (pos < input.size()) { + const std::size_t len = validate_utf8_at(input, pos); + if (len == 0U) { + return std::unexpected{ParseError{ + .offset = pos, + .message = "invalid UTF-8 sequence", + }}; + } + pos += len; + } + return {}; + } + class Parser final { public: @@ -179,6 +246,18 @@ namespace Void::Json::Strict fail("control character in string"); } if (value != '\\') { + if (value >= 0x80U) { + const std::size_t seq_start = position_ - 1U; + const std::size_t len = + validate_utf8_at(input_, seq_start); + if (len == 0U) { + position_ = seq_start; + fail("invalid UTF-8 sequence"); + } + output.append(input_.substr(seq_start, len)); + position_ = seq_start + len; + continue; + } output.push_back(static_cast(value)); continue; } @@ -435,4 +514,171 @@ namespace Void::Json::Strict .allowDecimals = true}); } + [[nodiscard]] inline bool is_valid_utf8(const std::string_view input) noexcept + { + std::size_t pos = 0U; + while (pos < input.size()) { + const std::size_t len = Detail::validate_utf8_at(input, pos); + if (len == 0U) { + return false; + } + pos += len; + } + return true; + } + + [[nodiscard]] inline std::expected + validate_utf8(const std::string_view input) + { + return Detail::validate_utf8_bytes(input); + } + + namespace Detail + { + inline void append_escaped_string(std::string& out, + const std::string_view text) + { + const auto utf8 = validate_utf8_bytes(text); + if (!utf8.has_value()) { + throw ParseFailure{.error = utf8.error()}; + } + out.push_back('"'); + std::size_t pos = 0U; + while (pos < text.size()) { + const auto ch = static_cast(text[pos]); + switch (ch) { + case '"': + out += "\\\""; + ++pos; + break; + case '\\': + out += "\\\\"; + ++pos; + break; + case '\b': + out += "\\b"; + ++pos; + break; + case '\f': + out += "\\f"; + ++pos; + break; + case '\n': + out += "\\n"; + ++pos; + break; + case '\r': + out += "\\r"; + ++pos; + break; + case '\t': + out += "\\t"; + ++pos; + break; + default: + if (ch < 0x20U) { + static constexpr char kHex[] = "0123456789abcdef"; + out += "\\u00"; + out.push_back(kHex[(ch >> 4U) & 0x0FU]); + out.push_back(kHex[ch & 0x0FU]); + ++pos; + } else if (ch >= 0x80U) { + const std::size_t len = validate_utf8_at(text, pos); + out.append(text.substr(pos, len)); + pos += len; + } else { + out.push_back(static_cast(ch)); + ++pos; + } + break; + } + } + out.push_back('"'); + } + + inline void serialize_value(std::string& out, const Value& val, + const std::size_t depth, + const std::size_t maximumDepth) + { + if (depth > maximumDepth) { + throw ParseFailure{ + .error = + { + .offset = out.size(), + .message = "nesting limit exceeded during serialize", + }, + }; + } + std::visit( + [&](const auto& node) { + using T = std::decay_t; + if constexpr (std::same_as) { + out += "null"; + } else if constexpr (std::same_as) { + out += (node ? "true" : "false"); + } else if constexpr (std::same_as) { + std::array buf{}; + const auto res = std::to_chars( + buf.data(), buf.data() + buf.size(), node); + out.append(buf.data(), res.ptr); + } else if constexpr (std::same_as) { + if (!std::isfinite(node)) { + throw ParseFailure{ + .error = + { + .offset = out.size(), + .message = + "non-finite double is not valid JSON", + }, + }; + } + std::array buf{}; + const auto res = std::to_chars( + buf.data(), buf.data() + buf.size(), node, + std::chars_format::general); + out.append(buf.data(), res.ptr); + } else if constexpr (std::same_as) { + append_escaped_string(out, node); + } else if constexpr (std::same_as) { + out.push_back('['); + for (std::size_t i = 0; i < node.size(); ++i) { + if (i > 0U) { + out.push_back(','); + } + serialize_value(out, node[i], depth + 1U, + maximumDepth); + } + out.push_back(']'); + } else if constexpr (std::same_as) { + out.push_back('{'); + bool first = true; + for (const auto& [k, v] : node) { + if (!first) { + out.push_back(','); + } + first = false; + append_escaped_string(out, k); + out.push_back(':'); + serialize_value(out, v, depth + 1U, maximumDepth); + } + out.push_back('}'); + } + }, + val.value); + } + } // namespace Detail + + [[nodiscard]] inline std::expected + serialize(const Value& value, + const std::size_t maximumDepth = default_maximum_depth) + { + try { + std::string out; + Detail::serialize_value(out, value, 0U, maximumDepth); + return out; + } catch (const Detail::ParseFailure& failure) { + return std::unexpected{failure.error}; + } + } + } // namespace Void::Json::Strict diff --git a/include/Void/Data/Toml.hpp b/include/Void/Data/Toml.hpp new file mode 100644 index 0000000..687e225 --- /dev/null +++ b/include/Void/Data/Toml.hpp @@ -0,0 +1,1906 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Data::Toml +{ + struct Origin { + std::size_t line{1}; + std::size_t column{1}; + + [[nodiscard]] constexpr auto + operator<=>(const Origin&) const noexcept = default; + }; + + struct ParseError { + Origin origin{}; + std::string message{}; + }; + + struct Date { + int year{0}; + int month{0}; + int day{0}; + + [[nodiscard]] constexpr bool + operator==(const Date&) const noexcept = default; + }; + + struct Time { + int hour{0}; + int minute{0}; + int second{0}; + std::uint32_t nanosecond{0}; + + [[nodiscard]] constexpr bool + operator==(const Time&) const noexcept = default; + }; + + enum class DateTimeKind : std::uint8_t { + OffsetDateTime, + LocalDateTime, + LocalDate, + LocalTime, + }; + + struct DateTime { + DateTimeKind kind{DateTimeKind::OffsetDateTime}; + Date date{}; + Time time{}; + bool utc{false}; + std::optional offset_minutes{}; + + void append_date_to(std::string& out) const + { + out += std::format("{:04d}-{:02d}-{:02d}", date.year, + date.month, date.day); + } + + void append_time_to(std::string& out) const + { + out += std::format("{:02d}:{:02d}:{:02d}", time.hour, + time.minute, time.second); + if (time.nanosecond != 0U) { + std::string frac = std::format("{:09d}", time.nanosecond); + while (!frac.empty() && frac.back() == '0') { + frac.pop_back(); + } + out.push_back('.'); + out += frac; + } + } + + [[nodiscard]] std::string to_string() const + { + std::string out; + switch (kind) { + case DateTimeKind::LocalDate: + append_date_to(out); + break; + case DateTimeKind::LocalTime: + append_time_to(out); + break; + case DateTimeKind::LocalDateTime: + append_date_to(out); + out.push_back('T'); + append_time_to(out); + break; + case DateTimeKind::OffsetDateTime: + append_date_to(out); + out.push_back('T'); + append_time_to(out); + if (utc) { + out.push_back('Z'); + } else if (offset_minutes.has_value()) { + const int mins = *offset_minutes; + const char sign = mins < 0 ? '-' : '+'; + const int abs_m = mins < 0 ? -mins : mins; + out += std::format("{}{:02d}:{:02d}", sign, + abs_m / 60, abs_m % 60); + } else { + out.push_back('Z'); + } + break; + } + return out; + } + + [[nodiscard]] bool + operator==(const DateTime&) const noexcept = default; + }; + + enum class ValueKind : std::uint8_t { + String, + Boolean, + Integer, + Float, + DateTime, + Array, + Table, + ArrayOfTables, + }; + + struct Value; + + struct Table { + std::map> entries{}; + bool is_inline{false}; + + [[nodiscard]] bool empty() const noexcept; + [[nodiscard]] std::size_t size() const noexcept; + [[nodiscard]] bool contains(std::string_view key) const noexcept; + [[nodiscard]] const Value* find(std::string_view key) const noexcept; + [[nodiscard]] Value* find(std::string_view key) noexcept; + }; + + struct Array { + std::vector elements{}; + + [[nodiscard]] bool empty() const noexcept; + [[nodiscard]] std::size_t size() const noexcept; + [[nodiscard]] const Value& operator[](std::size_t i) const noexcept; + }; + + struct ArrayOfTables { + std::vector tables{}; + + [[nodiscard]] bool empty() const noexcept; + [[nodiscard]] std::size_t size() const noexcept; + }; + + struct Value { + using Storage = + std::variant; + + Storage data{}; + Origin origin{1, 1}; + + Value() = default; + Value(std::string v, Origin o = {}) + : data(std::move(v)), origin(o) + { + } + Value(std::string_view v, Origin o = {}) + : data(std::string{v}), origin(o) + { + } + Value(const char* v, Origin o = {}) + : data(std::string{v}), origin(o) + { + } + Value(bool v, Origin o = {}) : data(v), origin(o) {} + Value(std::int64_t v, Origin o = {}) : data(v), origin(o) {} + Value(int v, Origin o = {}) + : data(static_cast(v)), origin(o) + { + } + Value(double v, Origin o = {}) : data(v), origin(o) {} + Value(DateTime v, Origin o = {}) : data(std::move(v)), origin(o) {} + Value(Array v, Origin o = {}) : data(std::move(v)), origin(o) {} + Value(Table v, Origin o = {}) : data(std::move(v)), origin(o) {} + Value(ArrayOfTables v, Origin o = {}) + : data(std::move(v)), origin(o) + { + } + + [[nodiscard]] ValueKind kind() const noexcept + { + switch (data.index()) { + case 0: return ValueKind::String; + case 1: return ValueKind::Boolean; + case 2: return ValueKind::Integer; + case 3: return ValueKind::Float; + case 4: return ValueKind::DateTime; + case 5: return ValueKind::Array; + case 6: return ValueKind::Table; + case 7: return ValueKind::ArrayOfTables; + default: return ValueKind::String; + } + } + + [[nodiscard]] bool is_string() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_bool() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_integer() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_float() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_datetime() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_array() const noexcept + { + return std::holds_alternative(data); + } + [[nodiscard]] bool is_table() const noexcept + { + return std::holds_alternative
(data); + } + [[nodiscard]] bool is_array_of_tables() const noexcept + { + return std::holds_alternative(data); + } + + [[nodiscard]] const std::string* as_string() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const bool* as_bool() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const std::int64_t* as_integer() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const double* as_float() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const DateTime* as_datetime() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const Array* as_array() const noexcept + { + return std::get_if(&data); + } + [[nodiscard]] const Table* as_table() const noexcept + { + return std::get_if
(&data); + } + [[nodiscard]] const ArrayOfTables* + as_array_of_tables() const noexcept + { + return std::get_if(&data); + } + + [[nodiscard]] Table* as_table() noexcept + { + return std::get_if
(&data); + } + [[nodiscard]] Array* as_array() noexcept + { + return std::get_if(&data); + } + [[nodiscard]] ArrayOfTables* as_array_of_tables() noexcept + { + return std::get_if(&data); + } + }; + + inline bool Table::empty() const noexcept { return entries.empty(); } + inline std::size_t Table::size() const noexcept { return entries.size(); } + inline bool Table::contains(std::string_view key) const noexcept + { + return entries.find(key) != entries.end(); + } + + inline const Value* Table::find(std::string_view key) const noexcept + { + const auto it = entries.find(key); + return it == entries.end() ? nullptr : &it->second; + } + + inline Value* Table::find(std::string_view key) noexcept + { + const auto it = entries.find(key); + return it == entries.end() ? nullptr : &it->second; + } + + inline bool Array::empty() const noexcept { return elements.empty(); } + inline std::size_t Array::size() const noexcept { return elements.size(); } + + inline const Value& Array::operator[](std::size_t i) const noexcept + { + return elements[i]; + } + + inline bool ArrayOfTables::empty() const noexcept { return tables.empty(); } + inline std::size_t ArrayOfTables::size() const noexcept + { + return tables.size(); + } + + struct Document { + Table root{}; + Origin origin{1, 1}; + + [[nodiscard]] const Table& table() const noexcept { return root; } + [[nodiscard]] const Value* find(std::string_view key) const noexcept + { + return root.find(key); + } + [[nodiscard]] bool contains(std::string_view key) const noexcept + { + return root.contains(key); + } + }; + + struct ParseOptions { + std::size_t max_depth{64}; + std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL}; + }; + + namespace Detail + { + struct Failure { + ParseError error; + }; + + [[nodiscard]] constexpr std::size_t + utf8_seq_len(std::string_view input, std::size_t pos) noexcept + { + if (pos >= input.size()) { + return 0U; + } + const auto b0 = static_cast(input[pos]); + if (b0 <= 0x7FU) { + return 1U; + } + if (b0 >= 0xC2U && b0 <= 0xDFU) { + if (pos + 1U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + return (b1 >= 0x80U && b1 <= 0xBFU) ? 2U : 0U; + } + if (b0 >= 0xE0U && b0 <= 0xEFU) { + if (pos + 2U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U; + const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU; + return (b1 >= lo && b1 <= hi && b2 >= 0x80U && b2 <= 0xBFU) + ? 3U + : 0U; + } + if (b0 >= 0xF0U && b0 <= 0xF4U) { + if (pos + 3U >= input.size()) { + return 0U; + } + const auto b1 = static_cast(input[pos + 1U]); + const auto b2 = static_cast(input[pos + 2U]); + const auto b3 = static_cast(input[pos + 3U]); + const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U; + const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU; + return (b1 >= lo && b1 <= hi && b2 >= 0x80U && b2 <= 0xBFU && + b3 >= 0x80U && b3 <= 0xBFU) + ? 4U + : 0U; + } + return 0U; + } + + [[nodiscard]] inline std::optional + validate_document_utf8(std::string_view input) + { + std::size_t line = 1; + std::size_t col = 1; + std::size_t pos = 0; + while (pos < input.size()) { + const std::size_t len = utf8_seq_len(input, pos); + if (len == 0U) { + return ParseError{ + .origin = Origin{line, col}, + .message = "invalid UTF-8 byte sequence in TOML document", + }; + } + if (len == 1U && input[pos] == '\n') { + ++line; + col = 1; + } else { + ++col; + } + pos += len; + } + return std::nullopt; + } + + enum class NodeState : std::uint8_t { + Scalar, + ImplicitTable, + DottedTable, + ExplicitTable, + InlineTable, + ArrayOfTables, + }; + + struct MetaNode { + NodeState state{NodeState::ImplicitTable}; + std::map, std::less<>> + children{}; + std::vector> aot_items{}; + }; + + [[nodiscard]] constexpr bool is_ws(char ch) noexcept + { + return ch == ' ' || ch == '\t'; + } + + [[nodiscard]] constexpr bool is_bare_key_char(char ch) noexcept + { + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || + (ch >= '0' && ch <= '9') || ch == '_' || ch == '-'; + } + + [[nodiscard]] constexpr bool is_disallowed_control(unsigned char ch, + bool allow_newline) noexcept + { + if (ch == '\t') { + return false; + } + if (allow_newline && ch == '\n') { + return false; + } + return (ch < 0x20U) || (ch == 0x7FU); + } + + [[nodiscard]] constexpr int days_in_month(int year, int month) noexcept + { + constexpr int kDays[12] = {31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31}; + if (month < 1 || month > 12) { + return 0; + } + if (month == 2) { + const bool leap = + ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); + return leap ? 29 : 28; + } + return kDays[month - 1]; + } + + inline void append_utf8_scalar(std::string& out, std::uint32_t cp) + { + if (cp <= 0x7FU) { + out.push_back(static_cast(cp)); + } else if (cp <= 0x7FFU) { + out.push_back(static_cast(0xC0U | (cp >> 6U))); + out.push_back(static_cast(0x80U | (cp & 0x3FU))); + } else if (cp <= 0xFFFFU) { + out.push_back(static_cast(0xE0U | (cp >> 12U))); + out.push_back(static_cast(0x80U | ((cp >> 6U) & 0x3FU))); + out.push_back(static_cast(0x80U | (cp & 0x3FU))); + } else { + out.push_back(static_cast(0xF0U | (cp >> 18U))); + out.push_back(static_cast(0x80U | ((cp >> 12U) & 0x3FU))); + out.push_back(static_cast(0x80U | ((cp >> 6U) & 0x3FU))); + out.push_back(static_cast(0x80U | (cp & 0x3FU))); + } + } + + class Parser final + { + public: + + Parser(std::string_view input, ParseOptions options) + : input_(input), options_(options) + { + } + + [[nodiscard]] Document parse() + { + if (input_.size() > options_.max_input_bytes) { + fail("TOML input exceeds max_input_bytes"); + } + if (const auto err = validate_document_utf8(input_)) { + throw Failure{.error = *err}; + } + + Document doc; + root_meta_.state = NodeState::ImplicitTable; + current_table_ = &doc.root; + current_meta_ = &root_meta_; + + while (pos_ < input_.size()) { + skip_ws_and_comments(true); + if (pos_ >= input_.size()) { + break; + } + const char ch = input_[pos_]; + if (ch == '[') { + parse_table_header(doc); + } else { + parse_key_value_into(*current_table_, *current_meta_, + false, 0U); + skip_ws(); + skip_comment_to_eol(); + if (pos_ < input_.size() && !consume_newline()) { + fail("expected newline after key-value assignment"); + } + } + } + return doc; + } + + private: + + [[nodiscard]] Origin here() const noexcept + { + return Origin{line_, column_}; + } + + [[noreturn]] void fail(std::string_view msg, + std::optional at = std::nullopt) const + { + throw Failure{ + .error = + { + .origin = at.value_or(here()), + .message = std::string{msg}, + }, + }; + } + + [[nodiscard]] bool starts_with(std::string_view s) const noexcept + { + return input_.substr(pos_, s.size()) == s; + } + + char advance_byte() noexcept + { + const char ch = input_[pos_++]; + if (ch == '\n') { + ++line_; + column_ = 1; + } else { + const auto uc = static_cast(ch); + if ((uc & 0xC0U) != 0x80U) { + ++column_; + } + } + return ch; + } + + void skip_ws() noexcept + { + while (pos_ < input_.size() && is_ws(input_[pos_])) { + (void)advance_byte(); + } + } + + void skip_comment_to_eol() + { + if (pos_ >= input_.size() || input_[pos_] != '#') { + return; + } + (void)advance_byte(); + while (pos_ < input_.size()) { + const char ch = input_[pos_]; + if (ch == '\n') { + break; + } + if (ch == '\r') { + if (pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + break; + } + fail("bare CR is not allowed in comment"); + } + if (is_disallowed_control( + static_cast(ch), false)) { + fail("disallowed control character in comment"); + } + (void)advance_byte(); + } + } + + bool consume_newline() + { + if (pos_ >= input_.size()) { + return false; + } + if (input_[pos_] == '\n') { + (void)advance_byte(); + return true; + } + if (input_[pos_] == '\r') { + if (pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + (void)advance_byte(); + (void)advance_byte(); + return true; + } + fail("bare CR without LF is not valid in TOML"); + } + return false; + } + + void skip_ws_and_comments(bool allow_newlines) + { + while (pos_ < input_.size()) { + skip_ws(); + if (allow_newlines) { + skip_comment_to_eol(); + if (consume_newline()) { + continue; + } + } + break; + } + } + + struct KeyPart { + std::string name{}; + Origin origin{}; + }; + + [[nodiscard]] static int hex_val(char ch) noexcept + { + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'a' && ch <= 'f') return 10 + (ch - 'a'); + if (ch >= 'A' && ch <= 'F') return 10 + (ch - 'A'); + return -1; + } + + [[nodiscard]] std::uint32_t parse_hex_escape(int digits, + Origin esc_origin) + { + std::uint32_t cp = 0; + for (int i = 0; i < digits; ++i) { + if (pos_ >= input_.size()) { + fail("unterminated unicode escape", esc_origin); + } + const int v = hex_val(advance_byte()); + if (v < 0) { + fail("invalid hexadecimal digit in unicode escape", + esc_origin); + } + cp = (cp << 4U) | static_cast(v); + } + if (cp > 0x10FFFFU || (cp >= 0xD800U && cp <= 0xDFFFU)) { + fail("unicode escape is not a valid scalar value", + esc_origin); + } + return cp; + } + + [[nodiscard]] std::string parse_basic_string(bool allow_multiline) + { + const Origin start = here(); + (void)advance_byte(); // opening '"' + const bool multiline = + allow_multiline && starts_with("\"\""); + if (multiline) { + (void)advance_byte(); + (void)advance_byte(); + // Trim one immediate newline after opening delimiter. + (void)consume_newline(); + } + + std::string out; + while (pos_ < input_.size()) { + const char ch = input_[pos_]; + if (ch == '"') { + if (!multiline) { + (void)advance_byte(); + return out; + } + if (starts_with("\"\"\"")) { + std::size_t qcount = 0; + while (pos_ + qcount < input_.size() && + input_[pos_ + qcount] == '"' && + qcount < 6U) { + ++qcount; + } + if (qcount == 6U) { + fail("too many closing quotes in multiline " + "basic string"); + } + for (std::size_t i = 0; i < qcount; ++i) { + (void)advance_byte(); + } + for (std::size_t i = 0; i < qcount - 3U; ++i) { + out.push_back('"'); + } + return out; + } + out.push_back(advance_byte()); + continue; + } + + if (ch == '\\') { + const Origin esc_origin = here(); + (void)advance_byte(); + if (pos_ >= input_.size()) { + fail("unterminated escape sequence", + esc_origin); + } + const char esc = input_[pos_]; + if (multiline && (is_ws(esc) || esc == '\n' || + esc == '\r')) { + while (pos_ < input_.size() && + is_ws(input_[pos_])) { + (void)advance_byte(); + } + if (!consume_newline()) { + fail("invalid line-ending backslash escape", + esc_origin); + } + while (pos_ < input_.size()) { + if (is_ws(input_[pos_])) { + (void)advance_byte(); + } else if (consume_newline()) { + // continue trimming + } else { + break; + } + } + continue; + } + (void)advance_byte(); + switch (esc) { + case 'b': out.push_back('\b'); break; + case 't': out.push_back('\t'); break; + case 'n': out.push_back('\n'); break; + case 'f': out.push_back('\f'); break; + case 'r': out.push_back('\r'); break; + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case 'u': + append_utf8_scalar( + out, parse_hex_escape(4, esc_origin)); + break; + case 'U': + append_utf8_scalar( + out, parse_hex_escape(8, esc_origin)); + break; + default: + fail("invalid basic string escape sequence", + esc_origin); + } + continue; + } + + if (ch == '\r') { + if (multiline && pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + (void)advance_byte(); + (void)advance_byte(); + out.push_back('\n'); + continue; + } + fail("invalid carriage return in string"); + } + if (ch == '\n') { + if (!multiline) { + fail("newline not allowed in single-line basic " + "string", + start); + } + out.push_back(advance_byte()); + continue; + } + if (is_disallowed_control( + static_cast(ch), false)) { + fail("disallowed control character in string"); + } + out.push_back(advance_byte()); + } + fail("unterminated basic string", start); + } + + [[nodiscard]] std::string + parse_literal_string(bool allow_multiline) + { + const Origin start = here(); + (void)advance_byte(); // opening '\'' + const bool multiline = + allow_multiline && starts_with("''"); + if (multiline) { + (void)advance_byte(); + (void)advance_byte(); + (void)consume_newline(); + } + + std::string out; + while (pos_ < input_.size()) { + const char ch = input_[pos_]; + if (ch == '\'') { + if (!multiline) { + (void)advance_byte(); + return out; + } + if (starts_with("'''")) { + std::size_t qcount = 0; + while (pos_ + qcount < input_.size() && + input_[pos_ + qcount] == '\'' && + qcount < 6U) { + ++qcount; + } + if (qcount == 6U) { + fail("too many closing quotes in multiline " + "literal string"); + } + for (std::size_t i = 0; i < qcount; ++i) { + (void)advance_byte(); + } + for (std::size_t i = 0; i < qcount - 3U; ++i) { + out.push_back('\''); + } + return out; + } + out.push_back(advance_byte()); + continue; + } + if (ch == '\r') { + if (multiline && pos_ + 1U < input_.size() && + input_[pos_ + 1U] == '\n') { + (void)advance_byte(); + (void)advance_byte(); + out.push_back('\n'); + continue; + } + fail("invalid carriage return in literal string"); + } + if (ch == '\n') { + if (!multiline) { + fail("newline not allowed in single-line " + "literal string", + start); + } + out.push_back(advance_byte()); + continue; + } + if (is_disallowed_control( + static_cast(ch), false)) { + fail("disallowed control character in literal " + "string"); + } + out.push_back(advance_byte()); + } + fail("unterminated literal string", start); + } + + [[nodiscard]] KeyPart parse_simple_key() + { + const Origin start = here(); + if (pos_ >= input_.size()) { + fail("expected key"); + } + if (input_[pos_] == '"') { + if (starts_with("\"\"\"")) { + fail("multiline strings cannot be keys", start); + } + return KeyPart{parse_basic_string(false), start}; + } + if (input_[pos_] == '\'') { + if (starts_with("'''")) { + fail("multiline literal strings cannot be keys", + start); + } + return KeyPart{parse_literal_string(false), start}; + } + std::string bare; + while (pos_ < input_.size() && + is_bare_key_char(input_[pos_])) { + bare.push_back(advance_byte()); + } + if (bare.empty()) { + fail("expected valid key", start); + } + return KeyPart{std::move(bare), start}; + } + + [[nodiscard]] std::vector parse_key_path() + { + std::vector path; + path.push_back(parse_simple_key()); + while (true) { + skip_ws(); + if (pos_ < input_.size() && input_[pos_] == '.') { + (void)advance_byte(); + skip_ws(); + path.push_back(parse_simple_key()); + } else { + break; + } + } + return path; + } + + void parse_table_header(Document& doc) + { + const Origin hdr_origin = here(); + (void)advance_byte(); // '[' + const bool is_aot = + pos_ < input_.size() && input_[pos_] == '['; + if (is_aot) { + (void)advance_byte(); + } + skip_ws(); + auto path = parse_key_path(); + skip_ws(); + if (pos_ >= input_.size() || input_[pos_] != ']') { + fail("expected ']' closing table header", hdr_origin); + } + (void)advance_byte(); + if (is_aot) { + if (pos_ >= input_.size() || input_[pos_] != ']') { + fail("expected ']]' closing array-of-tables header", + hdr_origin); + } + (void)advance_byte(); + } + skip_ws(); + skip_comment_to_eol(); + if (pos_ < input_.size() && !consume_newline()) { + fail("expected newline after table header"); + } + + Table* cur_tbl = &doc.root; + MetaNode* cur_meta = &root_meta_; + + for (std::size_t i = 0; i + 1U < path.size(); ++i) { + const auto& seg = path[i]; + auto* val = cur_tbl->find(seg.name); + if (val == nullptr) { + auto [it, ok] = cur_tbl->entries.emplace( + seg.name, Value{Table{}, seg.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::ImplicitTable; + auto [mit, mok] = cur_meta->children.emplace( + seg.name, std::move(meta_ptr)); + static_cast(mok); + cur_tbl = it->second.as_table(); + cur_meta = mit->second.get(); + } else { + auto mit = cur_meta->children.find(seg.name); + if (mit == cur_meta->children.end()) { + fail("internal metadata mismatch", seg.origin); + } + MetaNode* child_meta = mit->second.get(); + if (child_meta->state == NodeState::ArrayOfTables) { + auto* aot = val->as_array_of_tables(); + cur_tbl = &aot->tables.back(); + cur_meta = child_meta->aot_items.back().get(); + } else if (auto* sub = val->as_table(); + sub != nullptr && + child_meta->state != + NodeState::InlineTable) { + cur_tbl = sub; + cur_meta = child_meta; + } else { + fail(std::format("cannot traverse non-table " + "key '{}'", + seg.name), + seg.origin); + } + } + } + + const auto& leaf = path.back(); + auto* existing = cur_tbl->find(leaf.name); + if (!is_aot) { + if (existing == nullptr) { + auto [it, ok] = cur_tbl->entries.emplace( + leaf.name, Value{Table{}, leaf.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::ExplicitTable; + auto [mit, mok] = cur_meta->children.emplace( + leaf.name, std::move(meta_ptr)); + static_cast(mok); + current_table_ = it->second.as_table(); + current_meta_ = mit->second.get(); + return; + } + auto mit = cur_meta->children.find(leaf.name); + MetaNode* leaf_meta = mit->second.get(); + if (leaf_meta->state != NodeState::ImplicitTable) { + fail(std::format("redefinition of table or key " + "'{}'", + leaf.name), + hdr_origin); + } + leaf_meta->state = NodeState::ExplicitTable; + existing->origin = leaf.origin; + current_table_ = existing->as_table(); + current_meta_ = leaf_meta; + } else { + if (existing == nullptr) { + ArrayOfTables aot; + aot.tables.push_back(Table{}); + auto [it, ok] = cur_tbl->entries.emplace( + leaf.name, + Value{std::move(aot), leaf.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::ArrayOfTables; + auto elem_meta = std::make_unique(); + elem_meta->state = NodeState::ExplicitTable; + meta_ptr->aot_items.push_back(std::move(elem_meta)); + MetaNode* next_meta = meta_ptr->aot_items.back().get(); + cur_meta->children.emplace(leaf.name, + std::move(meta_ptr)); + current_table_ = + &it->second.as_array_of_tables()->tables.back(); + current_meta_ = next_meta; + return; + } + auto mit = cur_meta->children.find(leaf.name); + MetaNode* leaf_meta = mit->second.get(); + if (leaf_meta->state != NodeState::ArrayOfTables) { + fail(std::format("key '{}' is not an array of " + "tables", + leaf.name), + hdr_origin); + } + auto* aot = existing->as_array_of_tables(); + aot->tables.push_back(Table{}); + auto elem_meta = std::make_unique(); + elem_meta->state = NodeState::ExplicitTable; + leaf_meta->aot_items.push_back(std::move(elem_meta)); + current_table_ = &aot->tables.back(); + current_meta_ = leaf_meta->aot_items.back().get(); + } + } + + void parse_key_value_into(Table& root_tbl, MetaNode& root_meta, + bool in_inline, std::size_t depth) + { + auto path = parse_key_path(); + skip_ws(); + if (pos_ >= input_.size() || input_[pos_] != '=') { + fail("expected '=' after key"); + } + (void)advance_byte(); + skip_ws(); + Value val = parse_value(depth); + + Table* cur_tbl = &root_tbl; + MetaNode* cur_meta = &root_meta; + for (std::size_t i = 0; i + 1U < path.size(); ++i) { + const auto& seg = path[i]; + auto* existing = cur_tbl->find(seg.name); + if (existing == nullptr) { + Table sub; + sub.is_inline = false; + auto [it, ok] = cur_tbl->entries.emplace( + seg.name, Value{std::move(sub), seg.origin}); + static_cast(ok); + auto meta_ptr = std::make_unique(); + meta_ptr->state = NodeState::DottedTable; + auto [mit, mok] = cur_meta->children.emplace( + seg.name, std::move(meta_ptr)); + static_cast(mok); + cur_tbl = it->second.as_table(); + cur_meta = mit->second.get(); + } else { + auto mit = cur_meta->children.find(seg.name); + MetaNode* child_meta = mit->second.get(); + if (!existing->is_table() || + child_meta->state == NodeState::InlineTable || + child_meta->state == NodeState::ExplicitTable) { + fail(std::format("cannot extend '{}' via " + "dotted key", + seg.name), + seg.origin); + } + if (!in_inline && + child_meta->state == NodeState::ImplicitTable) { + child_meta->state = NodeState::DottedTable; + } + cur_tbl = existing->as_table(); + cur_meta = child_meta; + } + } + + const auto& leaf = path.back(); + if (cur_tbl->contains(leaf.name)) { + fail(std::format("duplicate key '{}'", leaf.name), + leaf.origin); + } + NodeState val_state = NodeState::Scalar; + if (val.is_table()) { + val_state = val.as_table()->is_inline + ? NodeState::InlineTable + : NodeState::ExplicitTable; + } + auto meta_ptr = std::make_unique(); + meta_ptr->state = val_state; + cur_meta->children.emplace(leaf.name, std::move(meta_ptr)); + cur_tbl->entries.emplace(leaf.name, std::move(val)); + } + + [[nodiscard]] Value parse_value(std::size_t depth) + { + if (depth > options_.max_depth || pos_ >= input_.size()) { + fail("nesting depth exceeded or unexpected end of input"); + } + const Origin start = here(); + const char ch = input_[pos_]; + if (ch == '"') { + return Value{parse_basic_string(true), start}; + } + if (ch == '\'') { + return Value{parse_literal_string(true), start}; + } + if (ch == '[') { + return parse_array(depth); + } + if (ch == '{') { + return parse_inline_table(depth); + } + return parse_bare_scalar(start); + } + + [[nodiscard]] Value parse_array(std::size_t depth) + { + const Origin start = here(); + (void)advance_byte(); // '[' + Array arr; + while (true) { + skip_ws_and_comments(true); + if (pos_ >= input_.size()) { + fail("unterminated array", start); + } + if (input_[pos_] == ']') { + (void)advance_byte(); + return Value{std::move(arr), start}; + } + arr.elements.push_back(parse_value(depth + 1U)); + skip_ws_and_comments(true); + if (pos_ >= input_.size()) { + fail("unterminated array", start); + } + if (input_[pos_] == ',') { + (void)advance_byte(); + continue; + } + if (input_[pos_] == ']') { + (void)advance_byte(); + return Value{std::move(arr), start}; + } + fail("expected ',' or ']' in array"); + } + } + + [[nodiscard]] Value parse_inline_table(std::size_t depth) + { + const Origin start = here(); + (void)advance_byte(); // '{' + Table tbl; + tbl.is_inline = true; + MetaNode inline_meta; + inline_meta.state = NodeState::InlineTable; + + skip_ws(); + if (pos_ < input_.size() && input_[pos_] == '}') { + (void)advance_byte(); + return Value{std::move(tbl), start}; + } + + while (true) { + skip_ws(); + if (pos_ >= input_.size() || input_[pos_] == '\n' || + input_[pos_] == '\r') { + fail("inline tables must stay on a single line", + start); + } + if (input_[pos_] == '}' || input_[pos_] == ',') { + fail("invalid empty entry or trailing comma in " + "inline table"); + } + parse_key_value_into(tbl, inline_meta, true, + depth + 1U); + skip_ws(); + if (pos_ >= input_.size()) { + fail("unterminated inline table", start); + } + if (input_[pos_] == '}') { + (void)advance_byte(); + return Value{std::move(tbl), start}; + } + if (input_[pos_] != ',') { + fail("expected ',' or '}' in inline table"); + } + (void)advance_byte(); + skip_ws(); + if (pos_ < input_.size() && input_[pos_] == '}') { + fail("trailing comma is not allowed in inline " + "table"); + } + } + } + + [[nodiscard]] static bool + is_token_terminator(char ch) noexcept + { + return is_ws(ch) || ch == '\n' || ch == '\r' || ch == '#' || + ch == ',' || ch == ']' || ch == '}'; + } + + [[nodiscard]] static bool + parse_two_digits(std::string_view sv, std::size_t pos, + int& out) noexcept + { + if (pos + 2U > sv.size()) { + return false; + } + const char a = sv[pos]; + const char b = sv[pos + 1U]; + if (a < '0' || a > '9' || b < '0' || b > '9') { + return false; + } + out = (a - '0') * 10 + (b - '0'); + return true; + } + + [[nodiscard]] static bool + parse_date_prefix(std::string_view sv, Date& d) noexcept + { + if (sv.size() != 10U || sv[4] != '-' || sv[7] != '-') { + return false; + } + for (std::size_t i = 0; i < 4U; ++i) { + if (sv[i] < '0' || sv[i] > '9') { + return false; + } + } + int y = 0; + const auto [ptr, ec] = + std::from_chars(sv.data(), sv.data() + 4U, y); + if (ec != std::errc{} || ptr != sv.data() + 4U) { + return false; + } + int m = 0; + int day = 0; + if (!parse_two_digits(sv, 5U, m) || + !parse_two_digits(sv, 8U, day)) { + return false; + } + const int dim = days_in_month(y, m); + if (dim == 0 || day < 1 || day > dim) { + return false; + } + d = Date{y, m, day}; + return true; + } + + [[nodiscard]] static bool + parse_time_part(std::string_view sv, Time& t, + std::size_t& consumed) noexcept + { + if (sv.size() < 8U || sv[2] != ':' || sv[5] != ':') { + return false; + } + int hh = 0; + int mm = 0; + int ss = 0; + if (!parse_two_digits(sv, 0U, hh) || + !parse_two_digits(sv, 3U, mm) || + !parse_two_digits(sv, 6U, ss)) { + return false; + } + if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || + ss > 60) { + return false; + } + std::size_t idx = 8U; + std::uint32_t ns = 0; + if (idx < sv.size() && sv[idx] == '.') { + ++idx; + if (idx >= sv.size() || sv[idx] < '0' || + sv[idx] > '9') { + return false; + } + std::uint32_t scale = 100'000'000U; + int digits = 0; + while (idx < sv.size() && sv[idx] >= '0' && + sv[idx] <= '9') { + if (digits < 9) { + ns += static_cast(sv[idx] - '0') * + scale; + scale /= 10U; + ++digits; + } + ++idx; + } + } + t = Time{hh, mm, ss, ns}; + consumed = idx; + return true; + } + + [[nodiscard]] std::optional + try_parse_datetime(std::string_view tok) const noexcept + { + // Local Time only: HH:MM:SS[.fff] + if (tok.size() >= 8U && tok[2] == ':') { + Time t; + std::size_t used = 0; + if (parse_time_part(tok, t, used) && + used == tok.size()) { + return DateTime{ + .kind = DateTimeKind::LocalTime, + .time = t, + }; + } + return std::nullopt; + } + + // Date prefix YYYY-MM-DD + if (tok.size() < 10U) { + return std::nullopt; + } + Date d; + if (!parse_date_prefix(tok.substr(0, 10U), d)) { + return std::nullopt; + } + if (tok.size() == 10U) { + return DateTime{ + .kind = DateTimeKind::LocalDate, + .date = d, + }; + } + const char sep = tok[10U]; + if (sep != 'T' && sep != 't' && sep != ' ') { + return std::nullopt; + } + Time t; + std::size_t t_len = 0; + if (!parse_time_part(tok.substr(11U), t, t_len)) { + return std::nullopt; + } + const std::size_t rem_pos = 11U + t_len; + if (rem_pos == tok.size()) { + return DateTime{ + .kind = DateTimeKind::LocalDateTime, + .date = d, + .time = t, + }; + } + const std::string_view off = tok.substr(rem_pos); + if (off == "Z" || off == "z") { + return DateTime{ + .kind = DateTimeKind::OffsetDateTime, + .date = d, + .time = t, + .utc = true, + .offset_minutes = 0, + }; + } + if (off.size() == 6U && (off[0] == '+' || off[0] == '-') && + off[3] == ':') { + int oh = 0; + int om = 0; + if (!parse_two_digits(off, 1U, oh) || + !parse_two_digits(off, 4U, om) || oh > 23 || + om > 59) { + return std::nullopt; + } + const int total = + (off[0] == '-' ? -1 : 1) * (oh * 60 + om); + return DateTime{ + .kind = DateTimeKind::OffsetDateTime, + .date = d, + .time = t, + .utc = false, + .offset_minutes = total, + }; + } + return std::nullopt; + } + + [[nodiscard]] static bool validate_underscores( + std::string_view digits, bool allow_hex) noexcept + { + if (digits.empty()) { + return false; + } + auto is_dig = [&](char c) { + if (c >= '0' && c <= '9') return true; + return allow_hex && ((c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F')); + }; + if (!is_dig(digits.front()) || !is_dig(digits.back())) { + return false; + } + bool prev_underscore = false; + for (char c : digits) { + if (c == '_') { + if (prev_underscore) { + return false; + } + prev_underscore = true; + } else if (is_dig(c)) { + prev_underscore = false; + } else { + return false; + } + } + return true; + } + + [[nodiscard]] static std::string + strip_underscores(std::string_view s) + { + std::string out; + out.reserve(s.size()); + for (char c : s) { + if (c != '_') { + out.push_back(c); + } + } + return out; + } + + [[nodiscard]] Value parse_bare_scalar(Origin start) + { + const std::size_t tok_begin = pos_; + while (pos_ < input_.size() && + !is_token_terminator(input_[pos_])) { + (void)advance_byte(); + } + // TOML 1.0 permits a single space separating YYYY-MM-DD + // and HH:MM:SS in DateTime values. + if (pos_ - tok_begin == 10U && pos_ + 2U < input_.size() && + input_[pos_] == ' ' && input_[pos_ + 1U] >= '0' && + input_[pos_ + 1U] <= '9') { + Date dummy_d; + if (parse_date_prefix( + input_.substr(tok_begin, 10U), dummy_d)) { + const std::size_t save_pos = pos_; + const std::size_t save_line = line_; + const std::size_t save_col = column_; + (void)advance_byte(); // ' ' + while (pos_ < input_.size() && + !is_token_terminator(input_[pos_])) { + (void)advance_byte(); + } + const std::string_view cand = input_.substr( + tok_begin, pos_ - tok_begin); + if (const auto dt = try_parse_datetime(cand)) { + return Value{*dt, start}; + } + pos_ = save_pos; + line_ = save_line; + column_ = save_col; + } + } + + const std::string_view tok = + input_.substr(tok_begin, pos_ - tok_begin); + if (tok.empty()) { + fail("expected value", start); + } + if (tok == "true") { + return Value{true, start}; + } + if (tok == "false") { + return Value{false, start}; + } + if (tok == "inf" || tok == "+inf") { + return Value{std::numeric_limits::infinity(), + start}; + } + if (tok == "-inf") { + return Value{-std::numeric_limits::infinity(), + start}; + } + if (tok == "nan" || tok == "+nan") { + return Value{std::numeric_limits::quiet_NaN(), + start}; + } + if (tok == "-nan") { + return Value{-std::numeric_limits::quiet_NaN(), + start}; + } + + if (const auto dt = try_parse_datetime(tok)) { + return Value{*dt, start}; + } + + // Look for date/time mistakes vs numbers. + if (tok.find(':') != std::string_view::npos) { + fail("invalid date-time or time literal", start); + } + + // Based integer prefixes: 0x / 0o / 0b (no leading sign) + if (tok.size() >= 2U && tok[0] == '0' && + (tok[1] == 'x' || tok[1] == 'o' || tok[1] == 'b')) { + const int base = + (tok[1] == 'x') ? 16 : ((tok[1] == 'o') ? 8 : 2); + const std::string_view digits = tok.substr(2U); + if (!validate_underscores(digits, base == 16)) { + fail("invalid based integer literal", start); + } + if (base == 8) { + for (char c : digits) { + if (c != '_' && (c < '0' || c > '7')) { + fail("invalid octal digit", start); + } + } + } else if (base == 2) { + for (char c : digits) { + if (c != '_' && c != '0' && c != '1') { + fail("invalid binary digit", start); + } + } + } + const std::string cleaned = strip_underscores(digits); + std::uint64_t uval = 0; + const auto [ptr, ec] = std::from_chars( + cleaned.data(), cleaned.data() + cleaned.size(), + uval, base); + if (ec != std::errc{} || + ptr != cleaned.data() + cleaned.size() || + uval > static_cast( + std::numeric_limits::max())) { + fail("integer literal out of 64-bit signed range", + start); + } + return Value{static_cast(uval), start}; + } + + // Signed decimal integer or float + const bool has_dot = + tok.find('.') != std::string_view::npos; + const bool has_exp = + tok.find('e') != std::string_view::npos || + tok.find('E') != std::string_view::npos; + + if (!has_dot && !has_exp) { + if (tok.find('-') != std::string_view::npos && + tok.find('-', 1) != std::string_view::npos) { + fail("invalid integer or date literal", start); + } + std::string_view body = tok; + bool negative = false; + if (body.front() == '+' || body.front() == '-') { + negative = (body.front() == '-'); + body.remove_prefix(1U); + } + if (!validate_underscores(body, false)) { + fail("invalid integer literal", start); + } + if (body.size() > 1U && body.front() == '0') { + fail("leading zeros are not allowed in TOML " + "integers", + start); + } + const std::string cleaned = + (negative ? "-" : "") + strip_underscores(body); + std::int64_t ival = 0; + const auto [ptr, ec] = std::from_chars( + cleaned.data(), cleaned.data() + cleaned.size(), + ival, 10); + if (ec != std::errc{} || + ptr != cleaned.data() + cleaned.size()) { + fail("integer literal out of int64 range", start); + } + return Value{ival, start}; + } + + // Float: [+/-] int (. frac)? ([eE] [+/-]? exp)? + std::string_view rest = tok; + std::string clean_float; + if (rest.front() == '+' || rest.front() == '-') { + if (rest.front() == '-') { + clean_float.push_back('-'); + } + rest.remove_prefix(1U); + } + const std::size_t dot_pos = rest.find('.'); + const std::size_t exp_pos = rest.find_first_of("eE"); + if (dot_pos != std::string_view::npos && + exp_pos != std::string_view::npos && exp_pos < dot_pos) { + fail("decimal point cannot follow exponent in float", + start); + } + const std::size_t int_end = + dot_pos != std::string_view::npos ? dot_pos : exp_pos; + const std::string_view int_part = + rest.substr(0, int_end); + if (!validate_underscores(int_part, false)) { + fail("invalid float integer part", start); + } + if (int_part.size() > 1U && int_part.front() == '0') { + fail("leading zero in float integer part", start); + } + clean_float += strip_underscores(int_part); + + if (dot_pos != std::string_view::npos) { + const std::string_view frac = + exp_pos == std::string_view::npos + ? rest.substr(dot_pos + 1U) + : rest.substr(dot_pos + 1U, + exp_pos - dot_pos - 1U); + if (!validate_underscores(frac, false)) { + fail("invalid float fractional part", start); + } + clean_float.push_back('.'); + clean_float += strip_underscores(frac); + } + if (exp_pos != std::string_view::npos) { + std::string_view exp_part = rest.substr(exp_pos + 1U); + clean_float.push_back('e'); + if (!exp_part.empty() && + (exp_part.front() == '+' || + exp_part.front() == '-')) { + clean_float.push_back(exp_part.front()); + exp_part.remove_prefix(1U); + } + if (!validate_underscores(exp_part, false)) { + fail("invalid float exponent", start); + } + clean_float += strip_underscores(exp_part); + } + + double dval = 0.0; + const auto [ptr, ec] = std::from_chars( + clean_float.data(), + clean_float.data() + clean_float.size(), dval, + std::chars_format::general); + if (ec != std::errc{} || + ptr != clean_float.data() + clean_float.size()) { + fail("invalid or out-of-range float literal", start); + } + return Value{dval, start}; + } + + std::string_view input_; + ParseOptions options_; + std::size_t pos_{0}; + std::size_t line_{1}; + std::size_t column_{1}; + MetaNode root_meta_{}; + Table* current_table_{nullptr}; + MetaNode* current_meta_{nullptr}; + }; + + inline void append_escaped_basic(std::string& out, std::string_view s) + { + out.push_back('"'); + for (const char raw : s) { + const auto ch = static_cast(raw); + switch (ch) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (ch < 0x20U || ch == 0x7FU) { + static constexpr char kHex[] = "0123456789abcdef"; + out += "\\u00"; + out.push_back(kHex[(ch >> 4U) & 0x0FU]); + out.push_back(kHex[ch & 0x0FU]); + } else { + out.push_back(raw); + } + break; + } + } + out.push_back('"'); + } + + inline void append_key(std::string& out, std::string_view key) + { + const bool bare = !key.empty() && + std::all_of(key.begin(), key.end(), [](char ch) { + return is_bare_key_char(ch); + }); + if (bare) { + out += key; + } else { + append_escaped_basic(out, key); + } + } + + inline void serialize_inline_value(std::string& out, const Value& v); + + inline void serialize_inline_table(std::string& out, const Table& t) + { + if (t.entries.empty()) { + out += "{}"; + return; + } + out += "{ "; + bool first = true; + for (const auto& [k, v] : t.entries) { + if (!first) { + out += ", "; + } + first = false; + append_key(out, k); + out += " = "; + serialize_inline_value(out, v); + } + out += " }"; + } + + inline void serialize_inline_value(std::string& out, const Value& v) + { + switch (v.kind()) { + case ValueKind::String: + append_escaped_basic(out, *v.as_string()); + break; + case ValueKind::Boolean: + out += (*v.as_bool() ? "true" : "false"); + break; + case ValueKind::Integer: { + std::array buf{}; + const auto [ptr, ec] = std::to_chars( + buf.data(), buf.data() + buf.size(), *v.as_integer()); + static_cast(ec); + out.append(buf.data(), ptr); + break; + } + case ValueKind::Float: { + const double d = *v.as_float(); + if (std::isnan(d)) { + out += std::signbit(d) ? "-nan" : "nan"; + } else if (std::isinf(d)) { + out += std::signbit(d) ? "-inf" : "inf"; + } else { + std::array buf{}; + const auto [ptr, ec] = std::to_chars( + buf.data(), buf.data() + buf.size(), d, + std::chars_format::general); + static_cast(ec); + const std::string_view repr{buf.data(), ptr}; + out += repr; + if (repr.find('.') == std::string_view::npos && + repr.find('e') == std::string_view::npos && + repr.find('E') == std::string_view::npos) { + out += ".0"; + } + } + break; + } + case ValueKind::DateTime: + out += v.as_datetime()->to_string(); + break; + case ValueKind::Array: { + const auto& arr = *v.as_array(); + out.push_back('['); + for (std::size_t i = 0; i < arr.elements.size(); ++i) { + if (i > 0U) { + out += ", "; + } + serialize_inline_value(out, arr.elements[i]); + } + out.push_back(']'); + break; + } + case ValueKind::Table: + serialize_inline_table(out, *v.as_table()); + break; + case ValueKind::ArrayOfTables: { + const auto& aot = *v.as_array_of_tables(); + out.push_back('['); + for (std::size_t i = 0; i < aot.tables.size(); ++i) { + if (i > 0U) { + out += ", "; + } + serialize_inline_table(out, aot.tables[i]); + } + out.push_back(']'); + break; + } + } + } + + inline void append_dotted_prefix(std::string& out, + const std::vector& path) + { + for (std::size_t i = 0; i < path.size(); ++i) { + if (i > 0U) { + out.push_back('.'); + } + append_key(out, path[i]); + } + } + + inline void serialize_table_body(std::string& out, const Table& table, + std::vector& prefix) + { + for (const auto& [k, v] : table.entries) { + if (v.kind() == ValueKind::ArrayOfTables || + (v.kind() == ValueKind::Table && + !v.as_table()->is_inline)) { + continue; + } + append_key(out, k); + out += " = "; + serialize_inline_value(out, v); + out.push_back('\n'); + } + + for (const auto& [k, v] : table.entries) { + if (v.kind() == ValueKind::Table && !v.as_table()->is_inline) { + prefix.push_back(k); + if (!out.empty() && out.back() != '\n') { + out.push_back('\n'); + } + if (!out.empty()) { + out.push_back('\n'); + } + out.push_back('['); + append_dotted_prefix(out, prefix); + out += "]\n"; + serialize_table_body(out, *v.as_table(), prefix); + prefix.pop_back(); + } else if (v.kind() == ValueKind::ArrayOfTables) { + prefix.push_back(k); + for (const auto& elem : v.as_array_of_tables()->tables) { + if (!out.empty()) { + out.push_back('\n'); + } + out += "[["; + append_dotted_prefix(out, prefix); + out += "]]\n"; + serialize_table_body(out, elem, prefix); + } + prefix.pop_back(); + } + } + } + } // namespace Detail + + [[nodiscard]] inline std::expected + parse(std::string_view input, ParseOptions options = {}) + { + try { + return Detail::Parser{input, options}.parse(); + } catch (const Detail::Failure& failure) { + return std::unexpected{failure.error}; + } + } + + [[nodiscard]] inline std::string serialize_table(const Table& table) + { + std::string out; + std::vector prefix; + Detail::serialize_table_body(out, table, prefix); + return out; + } + + [[nodiscard]] inline std::string serialize(const Document& doc) + { + return serialize_table(doc.root); + } + +} // namespace Void::Data::Toml + +namespace Void::Toml +{ + using namespace Void::Data::Toml; +} // namespace Void::Toml \ No newline at end of file diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index 2908cac..045fb3b 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -75,6 +75,7 @@ namespace Void::Result inline constexpr std::uint32_t kPluginErrorDomain = 23; inline constexpr std::uint32_t kConfigurationErrorDomain = 24; inline constexpr std::uint32_t kFsmErrorDomain = 25; + inline constexpr std::uint32_t kNetErrorDomain = 26; struct ErrorCode { std::uint32_t domain{kGenericErrorDomain}; diff --git a/include/Void/Testing/Test.hpp b/include/Void/Testing/Test.hpp index 28c0544..42e6b15 100644 --- a/include/Void/Testing/Test.hpp +++ b/include/Void/Testing/Test.hpp @@ -1,10 +1,190 @@ #pragma once -namespace Void::Testing { +#include +#include -// Aliases to void so users can omit return statements safely -// and avoid compiler warnings/errors. Perfectly matches std::function. -using Test = void; -using DisabledTest = void; +#include +#include +#include +#include +#include + +namespace Void::Testing +{ + + // Aliases to void so users can omit return statements safely + // and avoid compiler warnings/errors. Perfectly matches + // std::function. + using Test = void; + using DisabledTest = void; + + namespace Detail + { + [[nodiscard]] inline std::string + normalize_suite_label(std::string_view raw) + { + if (raw.size() >= 2 && raw.front() == '"' && raw.back() == '"') { + raw = raw.substr(1, raw.size() - 2); + } + return std::string{raw}; + } + + class NativeRegistrar final + { + public: + + NativeRegistrar(void (*fn)(), std::string_view suite, + const char* file, int line, + std::string_view name, + std::initializer_list tags = {}, + bool disabled = false, + std::string_view skip_reason = {}) + { + std::vector tag_vec; + tag_vec.reserve(tags.size()); + for (const char* t : tags) { + if (t != nullptr) { + tag_vec.emplace_back(t); + } + } + Registry::instance().add(TestCase{ + .run = fn, + .name = std::string{name}, + .suite = normalize_suite_label(suite), + .file = file != nullptr ? file : "", + .line = line, + .disabled = disabled, + .skip_reason = std::string{skip_reason}, + .tags = std::move(tag_vec), + }); + } + }; + + template class NativeFixtureRegistrar final + { + public: + + NativeFixtureRegistrar(void (*fn)(FixtureT&), + std::string_view suite, + const char* file, int line, + std::string_view name, + std::initializer_list tags = {}, + bool disabled = false, + std::string_view skip_reason = {}) + { + std::vector tag_vec; + tag_vec.reserve(tags.size()); + for (const char* t : tags) { + if (t != nullptr) { + tag_vec.emplace_back(t); + } + } + Registry::instance().add(TestCase{ + .run = + [fn]() { + FixtureT fixture{}; + if constexpr (requires { fixture.setup(); }) { + fixture.setup(); + } + try { + fn(fixture); + } catch (...) { + if constexpr (requires { + fixture.teardown(); + }) { + fixture.teardown(); + } + throw; + } + if constexpr (requires { fixture.teardown(); }) { + fixture.teardown(); + } + }, + .name = std::string{name}, + .suite = normalize_suite_label(suite), + .file = file != nullptr ? file : "", + .line = line, + .disabled = disabled, + .skip_reason = std::string{skip_reason}, + .tags = std::move(tag_vec), + }); + } + }; + } // namespace Detail } // namespace Void::Testing + +#define VOID_TESTING_DETAIL_CAT_IMPL(a, b) a##b +#define VOID_TESTING_DETAIL_CAT(a, b) VOID_TESTING_DETAIL_CAT_IMPL(a, b) + +#ifdef __COUNTER__ +#define VOID_TESTING_DETAIL_NEXT_ID __COUNTER__ +#else +#define VOID_TESTING_DETAIL_NEXT_ID __LINE__ +#endif + +#define VOID_TESTING_DETAIL_DEFINE_TEST(suite_expr, test_name, disabled_flag, \ + skip_msg, uid, ...) \ + static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)(); \ + namespace \ + { \ + [[maybe_unused]] const ::Void::Testing::Detail::NativeRegistrar \ + VOID_TESTING_DETAIL_CAT(_void_native_test_reg_, uid){ \ + &VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid), \ + (suite_expr), \ + __FILE__, \ + __LINE__, \ + #test_name, \ + {__VA_ARGS__}, \ + (disabled_flag), \ + (skip_msg)}; \ + } \ + static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)() + +#define VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, test_name, \ + disabled_flag, skip_msg, uid) \ + static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \ + fixture_type&); \ + namespace \ + { \ + [[maybe_unused]] const ::Void::Testing::Detail::NativeFixtureRegistrar< \ + fixture_type> \ + VOID_TESTING_DETAIL_CAT(_void_native_fx_reg_, uid){ \ + &VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid), \ + #fixture_type, \ + __FILE__, \ + __LINE__, \ + #test_name, \ + {}, \ + (disabled_flag), \ + (skip_msg)}; \ + } \ + static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \ + [[maybe_unused]] fixture_type& fixture) + +/// Declare a self-registering test case with zero CMake scanner dependency. +/// Symbols are internal-linkage and counter-disambiguated so files sharing the +/// same basename in different subdirectories link cleanly together. +#define VOID_TEST(suite, name) \ + VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \ + VOID_TESTING_DETAIL_NEXT_ID) + +/// Same as VOID_TEST, taking tags (string literals) after `name`. +#define VOID_TEST_TAGGED(suite, name, ...) \ + VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \ + VOID_TESTING_DETAIL_NEXT_ID, __VA_ARGS__) + +/// Declare a skipped/disabled self-registering test case. +#define VOID_TEST_DISABLED(suite, name, reason) \ + VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, true, (reason), \ + VOID_TESTING_DETAIL_NEXT_ID) + +/// Declare a self-registering fixture test. The fixture instance is bound as +/// `fixture` inside the test body, with optional setup()/teardown() hooks. +#define VOID_TEST_FIXTURE(fixture_type, name) \ + VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, false, "", \ + VOID_TESTING_DETAIL_NEXT_ID) + +#define VOID_TEST_FIXTURE_DISABLED(fixture_type, name, reason) \ + VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, true, (reason), \ + VOID_TESTING_DETAIL_NEXT_ID) diff --git a/include/Void/Text/Semver.hpp b/include/Void/Text/Semver.hpp index fd4862d..5797ca1 100644 --- a/include/Void/Text/Semver.hpp +++ b/include/Void/Text/Semver.hpp @@ -438,6 +438,54 @@ namespace Void::Semver using Clause = std::vector; std::vector m_alternatives; + struct PartialVersion { + Version version{}; + int components{0}; + }; + + [[nodiscard]] static std::optional + parse_partial(std::string_view token) + { + if (token.empty()) { + return std::nullopt; + } + if (token.find('-') != std::string_view::npos || + token.find('+') != std::string_view::npos) { + const auto full = parse_strict(token); + if (!full) { + return std::nullopt; + } + return PartialVersion{*full, 3}; + } + const auto first_dot = token.find('.'); + if (first_dot == std::string_view::npos) { + unsigned major = 0; + if (!Detail::parse_component(token, major)) { + return std::nullopt; + } + return PartialVersion{ + Version{.major = major, .minor = 0, .patch = 0}, 1}; + } + const auto second_dot = token.find('.', first_dot + 1); + if (second_dot == std::string_view::npos) { + unsigned major = 0; + unsigned minor = 0; + if (!Detail::parse_component(token.substr(0, first_dot), + major) || + !Detail::parse_component(token.substr(first_dot + 1), + minor)) { + return std::nullopt; + } + return PartialVersion{ + Version{.major = major, .minor = minor, .patch = 0}, 2}; + } + const auto full = parse_strict(token); + if (!full) { + return std::nullopt; + } + return PartialVersion{*full, 3}; + } + [[nodiscard]] static bool append_token(Clause& clause, std::string_view token) { @@ -447,53 +495,76 @@ namespace Void::Semver if (token.starts_with('^') || token.starts_with('~')) { const char kind = token.front(); token.remove_prefix(1); - const auto lower = parse_strict(token); - if (!lower) { + const auto partial = parse_partial(token); + if (!partial) { return false; } + const Version& lower = partial->version; Version upper; if (kind == '~') { - if (lower->minor == + if (partial->components == 1) { + if (lower.major == + std::numeric_limits::max()) { + return false; + } + upper = Version{.major = lower.major + 1, + .minor = 0, + .patch = 0, + .pre_release = {}, + .build = {}}; + } else { + if (lower.minor == + std::numeric_limits::max()) { + return false; + } + upper = Version{.major = lower.major, + .minor = lower.minor + 1, + .patch = 0, + .pre_release = {}, + .build = {}}; + } + } else if (partial->components == 1) { + if (lower.major == std::numeric_limits::max()) { return false; } - upper = Version{.major = lower->major, - .minor = lower->minor + 1, - .patch = 0, - .pre_release = {}, - .build = {}}; - } else if (lower->major > 0) { - if (lower->major == - std::numeric_limits::max()) { - return false; - } - upper = Version{.major = lower->major + 1, + upper = Version{.major = lower.major + 1, .minor = 0, .patch = 0, .pre_release = {}, .build = {}}; - } else if (lower->minor > 0) { - if (lower->minor == + } else if (lower.major > 0) { + if (lower.major == + std::numeric_limits::max()) { + return false; + } + upper = Version{.major = lower.major + 1, + .minor = 0, + .patch = 0, + .pre_release = {}, + .build = {}}; + } else if (lower.minor > 0) { + if (lower.minor == std::numeric_limits::max()) { return false; } upper = Version{.major = 0, - .minor = lower->minor + 1, + .minor = lower.minor + 1, .patch = 0, .pre_release = {}, .build = {}}; } else { - if (lower->patch == + if (lower.patch == std::numeric_limits::max()) { return false; } upper = Version{.major = 0, .minor = 0, - .patch = lower->patch + 1, + .patch = lower.patch + 1, .pre_release = {}, .build = {}}; } - clause.push_back({Operation::GreaterEqual, *lower}); + clause.push_back({Operation::GreaterEqual, lower}); clause.push_back({Operation::Less, std::move(upper)}); return true; } @@ -518,11 +589,11 @@ namespace Void::Semver } else if (token.starts_with('=')) { token.remove_prefix(1); } - const auto version = parse_strict(token); - if (!version) { + const auto partial = parse_partial(token); + if (!partial) { return false; } - clause.push_back({operation, *version}); + clause.push_back({operation, partial->version}); return true; } diff --git a/tests/package/TestingNativeGxx/dir_a/dup.cpp b/tests/package/TestingNativeGxx/dir_a/dup.cpp new file mode 100644 index 0000000..f2fa72a --- /dev/null +++ b/tests/package/TestingNativeGxx/dir_a/dup.cpp @@ -0,0 +1,12 @@ +#include +#include + +VOID_TEST(NativeGxx, from_dir_a_first) +{ + Void::Testing::expect_eq(10 + 5, 15); +} + +VOID_TEST(NativeGxx, duplicate_name_test) +{ + Void::Testing::expect(true); +} \ No newline at end of file diff --git a/tests/package/TestingNativeGxx/dir_b/dup.cpp b/tests/package/TestingNativeGxx/dir_b/dup.cpp new file mode 100644 index 0000000..06e0e4d --- /dev/null +++ b/tests/package/TestingNativeGxx/dir_b/dup.cpp @@ -0,0 +1,12 @@ +#include +#include + +VOID_TEST(NativeGxx, from_dir_b_first) +{ + Void::Testing::expect_eq(6 * 7, 42); +} + +VOID_TEST(NativeGxx, duplicate_name_test) +{ + Void::Testing::expect_eq(1, 1); +} \ No newline at end of file diff --git a/tests/standalone/Data/StrictJson.cpp b/tests/standalone/Data/StrictJson.cpp index f314ac1..80991ea 100644 --- a/tests/standalone/Data/StrictJson.cpp +++ b/tests/standalone/Data/StrictJson.cpp @@ -152,3 +152,69 @@ Void::Testing::Test strict_json_decodes_valid_unicode_pairs() Void::Testing::expect( !Void::Json::Strict::parse(R"("\uD83D")").has_value()); } + +Void::Testing::Test strict_json_validates_utf8_in_parse_and_serialize() +{ + // Valid 1, 2, 3, and 4-byte scalars including boundaries U+D7FF, U+E000, U+10FFFF + const std::string valid_json = + std::string{R"({"ascii":"hello","latin":")"} + "\xC3\xA9" + + R"(","euro":")" + "\xE2\x82\xAC" + R"(","emoji":")" + + "\xF0\x9F\x98\x80" + R"(","hi_bmp":")" + "\xED\x9F\xBF" + + R"(","priv":")" + "\xEE\x80\x80" + R"(","max_cp":")" + + "\xF4\x8F\xBF\xBF" + R"("})"; + + const auto parsed = Void::Json::Strict::parse(valid_json); + Void::Testing::require(parsed.has_value()); + const auto serialized = Void::Json::Strict::serialize(*parsed); + Void::Testing::require(serialized.has_value()); + const auto reparsed = Void::Json::Strict::parse(*serialized); + Void::Testing::require(reparsed.has_value()); + + // Invalid UTF-8 sequences in string values and object keys + const std::array invalid_payloads{ + std::string{"\"\xFF\""}, // invalid lead 0xFF + std::string{"\"\x80\""}, // stray continuation byte + std::string{"\"\xBF\""}, // stray continuation byte + std::string{"\"\xC0\xAF\""}, // overlong 2-byte '/' + std::string{"\"\xC1\x81\""}, // overlong 2-byte 'A' + std::string{"\"\xE0\x9F\x80\""}, // overlong 3-byte + std::string{"\"\xED\xA0\x80\""}, // UTF-8 encoded U+D800 + std::string{"\"\xED\xBF\xBF\""}, // UTF-8 encoded U+DFFF + std::string{"\"\xF4\x90\x80\x80\""}, // > U+10FFFF (U+110000) + std::string{"{\"\xFF\":\"val\"}"}, // invalid UTF-8 in object key + }; + for (const auto& payload : invalid_payloads) { + const auto res = Void::Json::Strict::parse(payload); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect(!Void::Json::Strict::is_valid_utf8(payload)); + } + + // Truncated multi-byte sequences inside strings + Void::Testing::expect( + !Void::Json::Strict::parse(std::string{"\"\xC3\""}).has_value()); + Void::Testing::expect( + !Void::Json::Strict::parse(std::string{"\"\xF0\x9F\x98\""}) + .has_value()); + + // Serialization must also reject corrupt UTF-8 in Values or keys + const Void::Json::Strict::Value bad_val{std::string{"ok\xED\xA0\x80"}}; + Void::Testing::expect( + !Void::Json::Strict::serialize(bad_val).has_value()); + + Void::Json::Strict::Value::Object bad_key_obj; + bad_key_obj.emplace(std::string{"bad\xFFkey"}, + Void::Json::Strict::Value{1}); + Void::Testing::expect( + !Void::Json::Strict::serialize( + Void::Json::Strict::Value{std::move(bad_key_obj)}) + .has_value()); + + // Control char escaping & round-trip in serialize() + const Void::Json::Strict::Value ctrl{std::string{"a\nb\tc\x01\"\\"}}; + const auto escaped = Void::Json::Strict::serialize(ctrl); + Void::Testing::require(escaped.has_value()); + const auto ctrl_back = Void::Json::Strict::parse(*escaped); + Void::Testing::require(ctrl_back.has_value()); + Void::Testing::expect_eq(std::get(ctrl_back->value), + std::string{"a\nb\tc\x01\"\\"}); +} diff --git a/tests/standalone/Data/Toml.cpp b/tests/standalone/Data/Toml.cpp new file mode 100644 index 0000000..84d8cec --- /dev/null +++ b/tests/standalone/Data/Toml.cpp @@ -0,0 +1,235 @@ +#include +#include +#include + +#include +#include +#include +#include + +Void::Testing::Test toml_parses_scalars_multilines_and_numbers() +{ + constexpr std::string_view kDoc = R"toml( +# Comment line +title = "Void Build" +literal_win = 'C:\Users\Void' +multi_basic = """ +Hello \ + world ""escaped"" \u0041 \U0001F600!""" +multi_quotes = """here are two ""quotes"" and two at end "" """ +five_quotes = """say """"" +multi_lit = ''' +line1\nraw +line2 'ok' ''ok'' +''' + +flag_t = true +flag_f = false + +dec_pos = +42 +dec_neg = -1_000_000 +hex_num = 0xDEAD_BEEF +oct_num = 0o755 +bin_num = 0b1101_0110 +min_i64 = -9223372036854775808 +max_i64 = 9223372036854775807 + +flt = -1.25e+2 +flt_zero = 0.0 +inf_pos = +inf +inf_neg = -inf +not_a_num = nan +)toml"; + + const auto parsed = Void::Data::Toml::parse(kDoc); + Void::Testing::require(parsed.has_value()); + const auto& root = parsed->root; + + Void::Testing::require(root.find("title") != nullptr); + Void::Testing::expect_eq( + *root.find("title")->as_string(), std::string{"Void Build"}); + Void::Testing::expect(root.find("title")->origin.line >= 3U); + Void::Testing::expect_eq( + *root.find("literal_win")->as_string(), std::string{R"(C:\Users\Void)"}); + Void::Testing::expect_eq( + *root.find("multi_basic")->as_string(), + std::string{"Hello world \"\"escaped\"\" A \xF0\x9F\x98\x80!"}); + Void::Testing::expect_eq( + *root.find("five_quotes")->as_string(), std::string{"say \"\""}); + Void::Testing::expect_eq( + *root.find("multi_lit")->as_string(), + std::string{"line1\\nraw\nline2 'ok' ''ok''\n"}); + + Void::Testing::expect_eq(*root.find("flag_t")->as_bool(), true); + Void::Testing::expect_eq(*root.find("flag_f")->as_bool(), false); + + Void::Testing::expect_eq(*root.find("dec_pos")->as_integer(), + std::int64_t{42}); + Void::Testing::expect_eq(*root.find("dec_neg")->as_integer(), + std::int64_t{-1000000}); + Void::Testing::expect_eq(*root.find("hex_num")->as_integer(), + std::int64_t{0xDEADBEEFLL}); + Void::Testing::expect_eq(*root.find("oct_num")->as_integer(), + std::int64_t{0755}); + Void::Testing::expect_eq(*root.find("bin_num")->as_integer(), + std::int64_t{0b11010110}); + Void::Testing::expect_eq(*root.find("min_i64")->as_integer(), + std::numeric_limits::min()); + Void::Testing::expect_eq(*root.find("max_i64")->as_integer(), + std::numeric_limits::max()); + + Void::Testing::expect_eq(*root.find("flt")->as_float(), -125.0); + Void::Testing::expect_eq(*root.find("flt_zero")->as_float(), 0.0); + Void::Testing::expect(std::isinf(*root.find("inf_pos")->as_float()) && + *root.find("inf_pos")->as_float() > 0.0); + Void::Testing::expect(std::isinf(*root.find("inf_neg")->as_float()) && + *root.find("inf_neg")->as_float() < 0.0); + Void::Testing::expect(std::isnan(*root.find("not_a_num")->as_float())); +} + +Void::Testing::Test toml_parses_datetimes_tables_inline_and_arrays_of_tables() +{ + constexpr std::string_view kDoc = R"toml( +odt_utc = 1979-05-27T07:32:00Z +odt_space = 1979-05-27 07:32:00.123456-07:00 +ldt = 2000-02-29T12:00:00 +ld = 2026-11-26 +lt = 08:15:30.5 + +name.first = "Ada" +name."last.part" = "Lovelace" +inline_pt = { x = 1, y = 2, nested.z = "ok" } +arr = [ + 1, + "two", # comment inside array + { k = true }, +] + +[server] +host = "127.0.0.1" +ports = [8080, 8443] + +[server.tls] +enabled = true + +[[products]] +name = "Hammer" +sku = 738594937 + +[[products]] # empty entry in middle is allowed +[[products]] +name = "Nail" +sku = 284758393 +color = ["gray", "steel"] + +[products.meta] +origin = "local" +)toml"; + + const auto parsed = Void::Data::Toml::parse(kDoc); + Void::Testing::require(parsed.has_value()); + const auto& root = parsed->root; + + const auto* odt = root.find("odt_utc")->as_datetime(); + Void::Testing::require(odt != nullptr); + Void::Testing::expect_eq(odt->to_string(), + std::string{"1979-05-27T07:32:00Z"}); + + const auto* odt2 = root.find("odt_space")->as_datetime(); + Void::Testing::require(odt2 != nullptr); + Void::Testing::expect_eq( + odt2->to_string(), std::string{"1979-05-27T07:32:00.123456-07:00"}); + + const auto* ldt = root.find("ldt")->as_datetime(); + Void::Testing::require(ldt != nullptr); + Void::Testing::expect_eq(ldt->date.year, 2000); + Void::Testing::expect_eq(ldt->date.month, 2); + Void::Testing::expect_eq(ldt->date.day, 29); + + const auto* name_tbl = root.find("name")->as_table(); + Void::Testing::require(name_tbl != nullptr); + Void::Testing::expect_eq(*name_tbl->find("first")->as_string(), + std::string{"Ada"}); + Void::Testing::expect_eq(*name_tbl->find("last.part")->as_string(), + std::string{"Lovelace"}); + + const auto* inline_pt = root.find("inline_pt")->as_table(); + Void::Testing::require(inline_pt != nullptr); + Void::Testing::expect(inline_pt->is_inline); + Void::Testing::expect_eq(*inline_pt->find("x")->as_integer(), + std::int64_t{1}); + Void::Testing::expect_eq( + *inline_pt->find("nested")->as_table()->find("z")->as_string(), + std::string{"ok"}); + + const auto* aot = root.find("products")->as_array_of_tables(); + Void::Testing::require(aot != nullptr); + Void::Testing::expect_eq(aot->tables.size(), std::size_t{3}); + Void::Testing::expect_eq(*aot->tables[0].find("name")->as_string(), + std::string{"Hammer"}); + Void::Testing::expect(aot->tables[1].empty()); + Void::Testing::expect_eq(*aot->tables[2].find("name")->as_string(), + std::string{"Nail"}); + Void::Testing::expect_eq( + *aot->tables[2].find("meta")->as_table()->find("origin")->as_string(), + std::string{"local"}); + + // Deterministic canonical serialize & round-trip idempotence + const std::string out1 = Void::Data::Toml::serialize(*parsed); + const auto reparsed = Void::Data::Toml::parse(out1); + Void::Testing::require(reparsed.has_value()); + const std::string out2 = Void::Data::Toml::serialize(*reparsed); + Void::Testing::expect_eq(out1, out2); +} + +Void::Testing::Test toml_reports_exact_origin_and_rejects_errors() +{ + // Line 1: ok, Line 2: ok, Line 3: duplicate key starts at col 1 + constexpr std::string_view kDupKey = "a = 1\nb = 2\na = 3\n"; + const auto e1 = Void::Data::Toml::parse(kDupKey); + Void::Testing::require(!e1.has_value()); + Void::Testing::expect_eq(e1.error().origin.line, std::size_t{3}); + Void::Testing::expect_eq(e1.error().origin.column, std::size_t{1}); + + // Duplicate [table] + constexpr std::string_view kDupTable = "[pkg]\nname = \"x\"\n\n[pkg]\n"; + const auto e2 = Void::Data::Toml::parse(kDupTable); + Void::Testing::require(!e2.has_value()); + Void::Testing::expect_eq(e2.error().origin.line, std::size_t{4}); + + // Defining explicit [table] after dotted key + const auto e3 = Void::Data::Toml::parse("a.b = 1\n[a]\n"); + Void::Testing::expect(!e3.has_value()); + + // Extending inline table + const auto e4 = Void::Data::Toml::parse("t = { a = 1 }\nt.b = 2\n"); + Void::Testing::expect(!e4.has_value()); + + // Multiline inline table forbidden in TOML 1.0 + const auto e5 = Void::Data::Toml::parse("t = {\n a = 1\n}\n"); + Void::Testing::expect(!e5.has_value()); + + // Trailing comma in inline table forbidden in TOML 1.0 + const auto e6 = Void::Data::Toml::parse("t = { a = 1, }\n"); + Void::Testing::expect(!e6.has_value()); + + // Invalid calendar date (non-leap year 1900-02-29) + const auto e7 = Void::Data::Toml::parse("d = 1900-02-29\n"); + Void::Testing::expect(!e7.has_value()); + + // Invalid 6-quote basic string close + const auto e8 = Void::Data::Toml::parse("s = \"\"\"hello\"\"\"\"\"\"\n"); + Void::Testing::expect(!e8.has_value()); + + // Invalid UTF-8 byte + const auto e9 = Void::Data::Toml::parse(std::string{"s = \"\xFF\"\n"}); + Void::Testing::expect(!e9.has_value()); + + // Subtable before parent table IS valid per TOML 1.0 + const auto super_after = + Void::Data::Toml::parse("[a.b]\nx = 1\n[a]\ny = 2\n"); + Void::Testing::require(super_after.has_value()); + Void::Testing::expect_eq( + *super_after->root.find("a")->as_table()->find("y")->as_integer(), + std::int64_t{2}); +} \ No newline at end of file diff --git a/tests/standalone/Testing/NativeRegistration.cpp b/tests/standalone/Testing/NativeRegistration.cpp new file mode 100644 index 0000000..a2cf0b5 --- /dev/null +++ b/tests/standalone/Testing/NativeRegistration.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +#include + +namespace void_testing_native_test +{ + struct CounterFixture { + int value{0}; + void setup() { value = 41; } + void teardown() { value = 0; } + }; +} // namespace void_testing_native_test + +VOID_TEST(NativeApi, self_registers_free_test) +{ + Void::Testing::expect_eq(2 + 3, 5); +} + +VOID_TEST_TAGGED(NativeApi, tagged_native_test, "fast", "native") +{ + const auto& tests = Void::Testing::Detail::Registry::instance().tests(); + bool found = false; + for (const auto& t : tests) { + if (t.suite == "NativeApi" && t.name == "tagged_native_test") { + found = (t.tags.size() == 2U && t.tags[0] == "fast" && + t.tags[1] == "native"); + break; + } + } + Void::Testing::expect(found); +} + +VOID_TEST_DISABLED(NativeApi, disabled_native_test, "intentional skip check") +{ + Void::Testing::expect(false); +} + +VOID_TEST_FIXTURE(void_testing_native_test::CounterFixture, + fixture_runs_setup_hook) +{ + Void::Testing::expect_eq(fixture.value, 41); + fixture.value += 1; + Void::Testing::expect_eq(fixture.value, 42); +} \ No newline at end of file diff --git a/tests/standalone/Text/Semver.cpp b/tests/standalone/Text/Semver.cpp index c0f4d3c..9d7bdab 100644 --- a/tests/standalone/Text/Semver.cpp +++ b/tests/standalone/Text/Semver.cpp @@ -148,12 +148,97 @@ Void::Testing::Test semver_version_ranges_reject_overflowing_upper_bounds() { Void::Testing::expect( !Void::Semver::parse_range("^4294967295.0.0").has_value()); + Void::Testing::expect( + !Void::Semver::parse_range("^4294967295").has_value()); + Void::Testing::expect( + !Void::Semver::parse_range("~4294967295").has_value()); Void::Testing::expect( !Void::Semver::parse_range("4294967295.x").has_value()); Void::Testing::expect( !Void::Semver::parse_range("1.4294967295.x").has_value()); } +Void::Testing::Test semver_shorthand_comparators() +{ + const auto caret_major = Void::Semver::parse_range("^1"); + Void::Testing::require(caret_major.has_value()); + Void::Testing::expect( + caret_major->contains(*Void::Semver::parse("1.0.0"))); + Void::Testing::expect( + caret_major->contains(*Void::Semver::parse("1.9.9"))); + Void::Testing::expect( + !caret_major->contains(*Void::Semver::parse("2.0.0"))); + Void::Testing::expect( + !caret_major->contains(*Void::Semver::parse("0.9.0"))); + + const auto caret_zero = Void::Semver::parse_range("^0"); + Void::Testing::require(caret_zero.has_value()); + Void::Testing::expect( + caret_zero->contains(*Void::Semver::parse("0.0.0"))); + Void::Testing::expect( + caret_zero->contains(*Void::Semver::parse("0.9.5"))); + Void::Testing::expect( + !caret_zero->contains(*Void::Semver::parse("1.0.0"))); + + const auto caret_minor = Void::Semver::parse_range("^1.0"); + Void::Testing::require(caret_minor.has_value()); + Void::Testing::expect( + caret_minor->contains(*Void::Semver::parse("1.0.0"))); + Void::Testing::expect( + caret_minor->contains(*Void::Semver::parse("1.5.2"))); + Void::Testing::expect( + !caret_minor->contains(*Void::Semver::parse("2.0.0"))); + + const auto caret_11 = Void::Semver::parse_range("^11.0"); + Void::Testing::require(caret_11.has_value()); + Void::Testing::expect( + caret_11->contains(*Void::Semver::parse("11.4.2"))); + Void::Testing::expect( + !caret_11->contains(*Void::Semver::parse("12.0.0"))); + + const auto caret_zero_minor = Void::Semver::parse_range("^0.2"); + Void::Testing::require(caret_zero_minor.has_value()); + Void::Testing::expect( + caret_zero_minor->contains(*Void::Semver::parse("0.2.7"))); + Void::Testing::expect( + !caret_zero_minor->contains(*Void::Semver::parse("0.3.0"))); + + const auto tilde_minor = Void::Semver::parse_range("~1.2"); + Void::Testing::require(tilde_minor.has_value()); + Void::Testing::expect( + tilde_minor->contains(*Void::Semver::parse("1.2.0"))); + Void::Testing::expect( + tilde_minor->contains(*Void::Semver::parse("1.2.9"))); + Void::Testing::expect( + !tilde_minor->contains(*Void::Semver::parse("1.3.0"))); + + const auto tilde_major = Void::Semver::parse_range("~2"); + Void::Testing::require(tilde_major.has_value()); + Void::Testing::expect( + tilde_major->contains(*Void::Semver::parse("2.5.0"))); + Void::Testing::expect( + !tilde_major->contains(*Void::Semver::parse("3.0.0"))); + + const auto mixed = Void::Semver::parse_range(">=1.2 <2"); + Void::Testing::require(mixed.has_value()); + Void::Testing::expect(mixed->contains(*Void::Semver::parse("1.2.0"))); + Void::Testing::expect(mixed->contains(*Void::Semver::parse("1.9.4"))); + Void::Testing::expect(!mixed->contains(*Void::Semver::parse("1.1.9"))); + Void::Testing::expect(!mixed->contains(*Void::Semver::parse("2.0.0"))); + + const auto less_only = Void::Semver::parse_range("<1.2.0"); + Void::Testing::require(less_only.has_value()); + Void::Testing::expect(less_only->contains(*Void::Semver::parse("1.1.9"))); + Void::Testing::expect( + !less_only->contains(*Void::Semver::parse("1.2.0"))); + + Void::Testing::expect(!Void::Semver::parse_range("^").has_value()); + Void::Testing::expect(!Void::Semver::parse_range("^1.").has_value()); + Void::Testing::expect(!Void::Semver::parse_range("^01").has_value()); + Void::Testing::expect( + !Void::Semver::parse_range(">=1.2-alpha").has_value()); +} + // ── bump ───────────────────────────────────────────────────────────────────── Void::Testing::Test semver_bump_major()