1961 lines
53 KiB
C++
1961 lines
53 KiB
C++
#pragma once
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <charconv>
|
|
#include <cmath>
|
|
#include <compare>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <format>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <utility>
|
|
#include <variant>
|
|
#include <vector>
|
|
|
|
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<int> 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<std::string, Value, std::less<>> 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<Value> 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<Table> tables{};
|
|
|
|
[[nodiscard]] bool empty() const noexcept;
|
|
[[nodiscard]] std::size_t size() const noexcept;
|
|
};
|
|
|
|
struct Value {
|
|
using Storage =
|
|
std::variant<std::string, bool, std::int64_t, double, DateTime,
|
|
Array, Table, ArrayOfTables>;
|
|
|
|
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<std::int64_t>(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<std::string>(data);
|
|
}
|
|
[[nodiscard]] bool is_bool() const noexcept
|
|
{
|
|
return std::holds_alternative<bool>(data);
|
|
}
|
|
[[nodiscard]] bool is_integer() const noexcept
|
|
{
|
|
return std::holds_alternative<std::int64_t>(data);
|
|
}
|
|
[[nodiscard]] bool is_float() const noexcept
|
|
{
|
|
return std::holds_alternative<double>(data);
|
|
}
|
|
[[nodiscard]] bool is_datetime() const noexcept
|
|
{
|
|
return std::holds_alternative<DateTime>(data);
|
|
}
|
|
[[nodiscard]] bool is_array() const noexcept
|
|
{
|
|
return std::holds_alternative<Array>(data);
|
|
}
|
|
[[nodiscard]] bool is_table() const noexcept
|
|
{
|
|
return std::holds_alternative<Table>(data);
|
|
}
|
|
[[nodiscard]] bool is_array_of_tables() const noexcept
|
|
{
|
|
return std::holds_alternative<ArrayOfTables>(data);
|
|
}
|
|
|
|
[[nodiscard]] const std::string* as_string() const noexcept
|
|
{
|
|
return std::get_if<std::string>(&data);
|
|
}
|
|
[[nodiscard]] const bool* as_bool() const noexcept
|
|
{
|
|
return std::get_if<bool>(&data);
|
|
}
|
|
[[nodiscard]] const std::int64_t* as_integer() const noexcept
|
|
{
|
|
return std::get_if<std::int64_t>(&data);
|
|
}
|
|
[[nodiscard]] const double* as_float() const noexcept
|
|
{
|
|
return std::get_if<double>(&data);
|
|
}
|
|
[[nodiscard]] const DateTime* as_datetime() const noexcept
|
|
{
|
|
return std::get_if<DateTime>(&data);
|
|
}
|
|
[[nodiscard]] const Array* as_array() const noexcept
|
|
{
|
|
return std::get_if<Array>(&data);
|
|
}
|
|
[[nodiscard]] const Table* as_table() const noexcept
|
|
{
|
|
return std::get_if<Table>(&data);
|
|
}
|
|
[[nodiscard]] const ArrayOfTables*
|
|
as_array_of_tables() const noexcept
|
|
{
|
|
return std::get_if<ArrayOfTables>(&data);
|
|
}
|
|
|
|
[[nodiscard]] Table* as_table() noexcept
|
|
{
|
|
return std::get_if<Table>(&data);
|
|
}
|
|
[[nodiscard]] Array* as_array() noexcept
|
|
{
|
|
return std::get_if<Array>(&data);
|
|
}
|
|
[[nodiscard]] ArrayOfTables* as_array_of_tables() noexcept
|
|
{
|
|
return std::get_if<ArrayOfTables>(&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 {
|
|
/// Maximum nesting level reached from the document root. It is
|
|
/// enforced uniformly for values (arrays, inline tables), dotted key
|
|
/// paths, table headers and array-of-tables headers.
|
|
std::size_t max_depth{64};
|
|
std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL};
|
|
/// Maximum number of document nodes (table entries, array elements
|
|
/// and array-of-tables entries plus their tables). Zero disables the
|
|
/// limit, preserving the historical behaviour. `max_input_bytes`
|
|
/// already bounds node count linearly; this knob bounds the constant
|
|
/// memory factor for untrusted input.
|
|
std::size_t max_nodes{0};
|
|
};
|
|
|
|
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<unsigned char>(input[pos]);
|
|
if (b0 <= 0x7FU) {
|
|
return 1U;
|
|
}
|
|
if (b0 >= 0xC2U && b0 <= 0xDFU) {
|
|
if (pos + 1U >= input.size()) {
|
|
return 0U;
|
|
}
|
|
const auto b1 = static_cast<unsigned char>(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<unsigned char>(input[pos + 1U]);
|
|
const auto b2 = static_cast<unsigned char>(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<unsigned char>(input[pos + 1U]);
|
|
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
|
|
const auto b3 = static_cast<unsigned char>(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<ParseError>
|
|
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::string, std::unique_ptr<MetaNode>, std::less<>>
|
|
children{};
|
|
std::vector<std::unique_ptr<MetaNode>> 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<char>(cp));
|
|
} else if (cp <= 0x7FFU) {
|
|
out.push_back(static_cast<char>(0xC0U | (cp >> 6U)));
|
|
out.push_back(static_cast<char>(0x80U | (cp & 0x3FU)));
|
|
} else if (cp <= 0xFFFFU) {
|
|
out.push_back(static_cast<char>(0xE0U | (cp >> 12U)));
|
|
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3FU)));
|
|
out.push_back(static_cast<char>(0x80U | (cp & 0x3FU)));
|
|
} else {
|
|
out.push_back(static_cast<char>(0xF0U | (cp >> 18U)));
|
|
out.push_back(static_cast<char>(0x80U | ((cp >> 12U) & 0x3FU)));
|
|
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3FU)));
|
|
out.push_back(static_cast<char>(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, table_depth_);
|
|
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<Origin> 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<unsigned char>(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<unsigned char>(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<std::uint32_t>(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<unsigned char>(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<unsigned char>(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};
|
|
}
|
|
|
|
/// Parse a dotted key path, rejecting it as soon as it grows past
|
|
/// `max_segments`. Checking while parsing keeps a pathologically
|
|
/// long path from being materialised before the depth limit applies.
|
|
[[nodiscard]] std::vector<KeyPart>
|
|
parse_key_path(std::size_t max_segments)
|
|
{
|
|
std::vector<KeyPart> path;
|
|
path.push_back(parse_simple_key());
|
|
while (true) {
|
|
if (path.size() > max_segments) {
|
|
fail("key path exceeds max_depth",
|
|
path.back().origin);
|
|
}
|
|
skip_ws();
|
|
if (pos_ < input_.size() && input_[pos_] == '.') {
|
|
(void)advance_byte();
|
|
skip_ws();
|
|
path.push_back(parse_simple_key());
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
return path;
|
|
}
|
|
|
|
/// A dotted key of N segments nests its value N-1 levels below the
|
|
/// current base depth, so it may hold one more segment than a table
|
|
/// header at the same limit.
|
|
[[nodiscard]] std::size_t
|
|
key_path_budget(std::size_t depth) const noexcept
|
|
{
|
|
if (depth > options_.max_depth) {
|
|
return 0;
|
|
}
|
|
const std::size_t remaining = options_.max_depth - depth;
|
|
if (remaining == std::numeric_limits<std::size_t>::max()) {
|
|
return remaining;
|
|
}
|
|
return remaining + 1U;
|
|
}
|
|
|
|
void note_node()
|
|
{
|
|
++node_count_;
|
|
if (options_.max_nodes != 0 &&
|
|
node_count_ > options_.max_nodes) {
|
|
fail(std::format("TOML document exceeds max_nodes ({})",
|
|
options_.max_nodes));
|
|
}
|
|
}
|
|
|
|
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(options_.max_depth);
|
|
table_depth_ = path.size();
|
|
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<void>(ok);
|
|
auto meta_ptr = std::make_unique<MetaNode>();
|
|
meta_ptr->state = NodeState::ImplicitTable;
|
|
auto [mit, mok] = cur_meta->children.emplace(
|
|
seg.name, std::move(meta_ptr));
|
|
static_cast<void>(mok);
|
|
note_node();
|
|
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<void>(ok);
|
|
auto meta_ptr = std::make_unique<MetaNode>();
|
|
meta_ptr->state = NodeState::ExplicitTable;
|
|
auto [mit, mok] = cur_meta->children.emplace(
|
|
leaf.name, std::move(meta_ptr));
|
|
static_cast<void>(mok);
|
|
note_node();
|
|
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<void>(ok);
|
|
auto meta_ptr = std::make_unique<MetaNode>();
|
|
meta_ptr->state = NodeState::ArrayOfTables;
|
|
auto elem_meta = std::make_unique<MetaNode>();
|
|
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));
|
|
note_node(); // the array-of-tables value
|
|
note_node(); // its first table
|
|
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{});
|
|
note_node();
|
|
auto elem_meta = std::make_unique<MetaNode>();
|
|
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(key_path_budget(depth));
|
|
const std::size_t value_depth = depth + path.size() - 1U;
|
|
skip_ws();
|
|
if (pos_ >= input_.size() || input_[pos_] != '=') {
|
|
fail("expected '=' after key");
|
|
}
|
|
(void)advance_byte();
|
|
skip_ws();
|
|
Value val = parse_value(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<void>(ok);
|
|
auto meta_ptr = std::make_unique<MetaNode>();
|
|
meta_ptr->state = NodeState::DottedTable;
|
|
auto [mit, mok] = cur_meta->children.emplace(
|
|
seg.name, std::move(meta_ptr));
|
|
static_cast<void>(mok);
|
|
note_node();
|
|
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<MetaNode>();
|
|
meta_ptr->state = val_state;
|
|
cur_meta->children.emplace(leaf.name, std::move(meta_ptr));
|
|
cur_tbl->entries.emplace(leaf.name, std::move(val));
|
|
note_node();
|
|
}
|
|
|
|
[[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));
|
|
note_node();
|
|
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<std::uint32_t>(sv[idx] - '0') *
|
|
scale;
|
|
scale /= 10U;
|
|
++digits;
|
|
}
|
|
++idx;
|
|
}
|
|
}
|
|
t = Time{hh, mm, ss, ns};
|
|
consumed = idx;
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] std::optional<DateTime>
|
|
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<double>::infinity(),
|
|
start};
|
|
}
|
|
if (tok == "-inf") {
|
|
return Value{-std::numeric_limits<double>::infinity(),
|
|
start};
|
|
}
|
|
if (tok == "nan" || tok == "+nan") {
|
|
return Value{std::numeric_limits<double>::quiet_NaN(),
|
|
start};
|
|
}
|
|
if (tok == "-nan") {
|
|
return Value{-std::numeric_limits<double>::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::uint64_t>(
|
|
std::numeric_limits<std::int64_t>::max())) {
|
|
fail("integer literal out of 64-bit signed range",
|
|
start);
|
|
}
|
|
return Value{static_cast<std::int64_t>(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};
|
|
std::size_t table_depth_{0};
|
|
std::size_t node_count_{0};
|
|
};
|
|
|
|
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<unsigned char>(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<char, 32> buf{};
|
|
const auto [ptr, ec] = std::to_chars(
|
|
buf.data(), buf.data() + buf.size(), *v.as_integer());
|
|
static_cast<void>(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<char, 64> buf{};
|
|
const auto [ptr, ec] = std::to_chars(
|
|
buf.data(), buf.data() + buf.size(), d,
|
|
std::chars_format::general);
|
|
static_cast<void>(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<std::string>& 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<std::string>& 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<Document, ParseError>
|
|
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<std::string> 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
|