Module encoding/toml

encoding/toml
Stability: unstable — this replaced the line-based subset parser (which returned `.Ok` with a corrupted document for twelve inputs), so the value model gained `Float`, `Datetime` and `Array`, `insert` returns the value it replaced, and the error type changed from `String` to `TomlError`. The API may still change until the next release; drop this section to freeze it. — stable modules only change additively; this one may still change.

TOML v1.0.0 parsing and serialization.

toml.parse scans a whole document with a byte scanner and returns a TomlValue tree; toml.stringify writes one back out. The value model is the Rust toml crate's Value: string, integer, float, boolean, date-time, array, table.

Everything TOML v1.0.0 admits is accepted: comments, bare / quoted / dotted keys, basic and literal strings (single and multi-line, with escapes), decimal / hex / octal / binary integers, floats including inf and nan, the four date-time forms, arrays (heterogeneous, nested, trailing comma, newlines inside the brackets), inline tables, [table] headers and [[array of tables]]. Everything it does not admit is an .Err with a byte offset — a document that parses is the document that was written.

Example

toml :: import("std/encoding/toml");
{ TomlValue } :: import("std/encoding/toml");

doc := toml.parse(`title = "yo"
[server]
port = 8080
`).unwrap();
println(doc.get(`server`).unwrap().get(`port`).unwrap().as_int().unwrap());
println(toml.stringify(doc));

Stability

unstable — this replaced the line-based subset parser (which returned .Ok with a corrupted document for twelve inputs), so the value model gained Float, Datetime and Array, insert returns the value it replaced, and the error type changed from String to TomlError. The API may still change until the next release; drop this section to freeze it.

Types

TomlError enum
TomlError

A TOML parse failure. Every variant carries a BYTE OFFSET into the input, the same contract EncodingError and CsvError have: a caller decoding a 4 KiB config learns WHERE the document is wrong, not merely that it is.

Variants

VariantFieldsDescription
UnexpectedCharch: u8, pos: usize

A byte that cannot appear here — a garbage line, a missing =, a second value where a separator belongs, a control character in a comment.

UnexpectedEndpos: usize

The input ended inside a construct (a header, an array, an inline table, a key/value pair). pos is the end of the input.

UnterminatedStringstart: usize

A string ran to the end of its line (single-line forms) or to the end of the input without its closing delimiter. start is the opening quote.

InvalidEscapepos: usize

A backslash escape that is not one of TOML's (\b \t \n \f \r \" \\ \uXXXX \UXXXXXXXX, plus the multi-line line-ending backslash).

InvalidUnicodepos: usize

A \u / \U escape whose digits are not hex, or whose value is not a Unicode scalar (a surrogate, or above U+10FFFF).

InvalidNumberpos: usize

A numeric literal outside TOML's integer/float grammar, or an integer outside i64. TOML rejects 01, 1., 1_, _1, 0x1p3 and -0xff, and this is how it says so.

InvalidDatetimepos: usize

A date-time literal that is not one of RFC 3339's forms TOML admits, or whose components are outside the calendar.

DuplicateKeykey: String, pos: usize

A key defined twice in the same table.

RedefinedTablekey: String, pos: usize

A table header that reopens a table already closed — defined by an earlier header, by a dotted key, or as an inline-table value — or an [[array]] header on a key that is not an array of tables.

ExpectedTablekey: String, pos: usize

A dotted key or header path that runs THROUGH a value which is not a table (a = 1 then a.b = 2).

Trait Implementations

impl(generic(T : Type), where(T <: ToString), T : (ToString))
impl(generic(T : Type), where(T <: ToString), T : (ToString), Format)
format : fn(self : Self, spec : str) -> String

Render self under spec. An unrecognised spec degrades to the plain to_string() rendering rather than failing.

Parameters

NameTypeNotes
selfSelf
specstr

Returns: String

impl(TomlError, ...)
pos : (TomlError) fn(self : TomlError) -> usize

The byte offset the fault was found at. Unlike EncodingError.pos this is total: every TOML failure has a position, because the scanner always knows where it is.

Parameters

NameTypeNotes
selfTomlError

Returns: usize

Methods
to_string : (TomlError) fn(self : TomlError) -> String

Parameters

NameTypeNotes
selfTomlError

Returns: String

source : (TomlError) fn(self : TomlError) -> Option(dyn( + ToString))

The error that caused this one, or .None at the root of the chain.

Rust's Error::source. Defaulted to .None, so an error with nothing underneath it implements the trait by saying only what it is; a wrapper overrides it to hand back what it wrapped. Walking the chain to the root cause is not expressible yet — the returned Dyn loses the Error trait on an erased receiver, so a caller can print one link but cannot follow it (#521, issues/self-trait-in-a-return-type-loses-the-trait-on-an-erased-receiver.md).

Parameters

NameTypeNotes
selfTomlError

Returns: Option(dyn( + ToString))

TomlDateTimeKind

Which of TOML's four date-time forms a TomlDateTime holds. The tag is what DateTime alone cannot supply, and every form needs it: 1979-05-27T07:32:00Z and 1979-05-27T07:32:00 are DIFFERENT TOML values (one names an instant, one a wall-clock reading with no zone), and a local date has no time while a local time has no date. Without the tag a parse would have to invent a zone or a date and the serializer could not write back what it read.

Variants

VariantFieldsDescription
OffsetDateTime

1979-05-27T07:32:00Z, 1979-05-27T00:32:00-07:00 — a real instant.

LocalDateTime

1979-05-27T07:32:00 — a wall-clock reading with no zone.

LocalDate

1979-05-27 — no time, no zone.

LocalTime

07:32:00.999999 — no date, no zone.

Trait Implementations

Eq
Methods
== : (TomlDateTimeKind) fn(lhs : TomlDateTimeKind, rhs : TomlDateTimeKind) -> bool

Parameters

NameTypeNotes
lhsTomlDateTimeKind
rhsTomlDateTimeKind

Returns: bool

!= : (TomlDateTimeKind) fn(lhs : TomlDateTimeKind, rhs : TomlDateTimeKind) -> bool

Parameters

NameTypeNotes
lhsTomlDateTimeKind
rhsTomlDateTimeKind

Returns: bool

TomlDateTime struct
TomlDateTime

A TOML date-time: std/time/datetime's DateTime for the components, plus the tag saying which of them are significant.

The components are REUSED rather than redeclared so the calendar rules live in one place — DateTime.new is what validates a leap day, and this module would otherwise carry a second copy of the leap-year table. What DateTime cannot do is distinguish TOML's four forms (it has no "no offset" state and no date-less or time-less form), which is why kind exists; the components the tag calls absent are set to the epoch's (1970-01-01 for a local time, 00:00:00 for a local date) and must not be read.

Fields

NameTypeDescription
kindTomlDateTimeKind

Which form this is — and therefore which components mean anything.

valueDateTime

The components. utc_offset_secs is meaningful only for .OffsetDateTime.

Trait Implementations

impl(generic(T : Type), where(T <: ToString), T : (ToString))
impl(generic(T : Type), where(T <: ToString), T : (ToString), Format)
format : fn(self : Self, spec : str) -> String

Render self under spec. An unrecognised spec degrades to the plain to_string() rendering rather than failing.

Parameters

NameTypeNotes
selfSelf
specstr

Returns: String

impl(TomlDateTime, ToString(...))
to_string : (TomlDateTime) fn(self : TomlDateTime) -> String

Render self as the text a USER should read — Rust's Display::fmt, not its Debug. Hand-written (or generated by derive(Error) from a per-variant format string) whenever the structural form would be wrong.

Parameters

NameTypeNotes
selfTomlDateTime

Returns: String

TomlValue enum
TomlValue

TOML value type — the result of parsing a TOML document. The variants are the Rust toml crate's Value, in its order.

Variants

VariantFieldsDescription
Strvalue: String

A TOML string value.

Intvalue: i64

A TOML integer value (64-bit signed, as TOML requires).

Floatvalue: f64

A TOML float value (IEEE 754 double, as TOML requires).

Boolvalue: bool

A TOML boolean value.

Datetimevalue: TomlDateTime

A TOML offset/local date-time, local date, or local time.

Arrayitems: ArrayList(<enum:enum_decl_505353_file____home_runner_work_Yo_Yo_std_encoding_toml_yo__self_shell>)

A TOML array. TOML v1.0.0 allows mixed element types.

Tablekeys: ArrayList(String), values: ArrayList(<enum:enum_decl_505353_file____home_runner_work_Yo_Yo_std_encoding_toml_yo__self_shell>)

A TOML table, keys in insertion order.

Trait Implementations

impl(generic(T : Type), where(T <: ToString), T : (ToString))
impl(generic(T : Type), where(T <: ToString), T : (ToString), Format)
format : fn(self : Self, spec : str) -> String

Render self under spec. An unrecognised spec degrades to the plain to_string() rendering rather than failing.

Parameters

NameTypeNotes
selfSelf
specstr

Returns: String

impl(TomlValue, ...)
new_table : (TomlValue) fn() -> TomlValue

Create a new empty table.

Returns: TomlValue

new_array : (TomlValue) fn() -> TomlValue

Create a new empty array.

Returns: TomlValue

get : (TomlValue) fn(self : TomlValue, key : String) -> Option(TomlValue)

Look up a value by key in a table. Returns .None if not a table or key is missing.

Parameters

NameTypeNotes
selfTomlValue
keyString

Returns: Option(TomlValue)

has_key : (TomlValue) fn(self : TomlValue, key : String) -> bool

Check whether the table contains the given key.

Parameters

NameTypeNotes
selfTomlValue
keyString

Returns: bool

insert : (TomlValue) fn(self : TomlValue, key : String, value : TomlValue) -> Option(TomlValue)

Set key to value, returning the value it REPLACED (.None when the key is new) — the D2 shape for a map insert, matching JsonValue.insert. Insertion order is preserved and a replacement keeps the key's original position. A non-table receiver is a no-op returning .None.

Parameters

NameTypeNotesDescription
selfTomlValue
keyString
valueTomlValue

The components. utc_offset_secs is meaningful only for .OffsetDateTime.

Returns: Option(TomlValue)

table_len : (TomlValue) fn(self : TomlValue) -> usize

Return the number of keys in the table, or 0 if not a table.

Parameters

NameTypeNotes
selfTomlValue

Returns: usize

array_len : (TomlValue) fn(self : TomlValue) -> usize

Return the number of elements in the array, or 0 if not an array.

Parameters

NameTypeNotes
selfTomlValue

Returns: usize

at : (TomlValue) fn(self : TomlValue, index : usize) -> Option(TomlValue)

The byte off past the cursor, or 0 at/after the end of input. No TOML construct admits a NUL — _is_forbidden_control rejects it inside every string, key and comment — so 0 is an unambiguous end marker for the lookahead tests below.

Parameters

NameTypeNotes
selfTomlValue
indexusize

Returns: Option(TomlValue)

as_string : (TomlValue) fn(self : TomlValue) -> Option(String)

Extract the string value, or .None if not a Str.

Parameters

NameTypeNotes
selfTomlValue

Returns: Option(String)

as_int : (TomlValue) fn(self : TomlValue) -> Option(i64)

Extract the integer value, or .None if not an Int.

Parameters

NameTypeNotes
selfTomlValue

Returns: Option(i64)

as_float : (TomlValue) fn(self : TomlValue) -> Option(f64)

Extract the float value, or .None if not a Float.

Parameters

NameTypeNotes
selfTomlValue

Returns: Option(f64)

as_bool : (TomlValue) fn(self : TomlValue) -> Option(bool)

Extract the boolean value, or .None if not a Bool.

Parameters

NameTypeNotes
selfTomlValue

Returns: Option(bool)

as_datetime : (TomlValue) fn(self : TomlValue) -> Option(TomlDateTime)

Extract the date-time value, or .None if not a Datetime.

Parameters

NameTypeNotes
selfTomlValue

Returns: Option(TomlDateTime)

as_array : (TomlValue) fn(self : TomlValue) -> Option(ArrayList(<enum:enum_decl_505353_file____home_runner_work_Yo_Yo_std_encoding_toml_yo__self_shell>))

Extract the array items, or .None if not an Array.

Parameters

NameTypeNotes
selfTomlValue

Returns: Option(ArrayList(<enum:enum_decl_505353_file____home_runner_work_Yo_Yo_std_encoding_toml_yo__self_shell>))

is_string : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML string.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

is_int : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML integer.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

is_float : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML float.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

is_bool : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML boolean.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

is_datetime : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML date-time of any of the four forms.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

is_array : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML array.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

is_table : (TomlValue) fn(self : TomlValue) -> bool

True for a TOML table.

Parameters

NameTypeNotes
selfTomlValue

Returns: bool

impl(TomlValue, ToString(...))
to_string : (TomlValue) fn(self : TomlValue) -> String

Render self as the text a USER should read — Rust's Display::fmt, not its Debug. Hand-written (or generated by derive(Error) from a per-variant format string) whenever the structural form would be wrong.

Parameters

NameTypeNotes
selfTomlValue

Returns: String

impl(TomlValue, Eq(TomlValue)(...))
Methods
== : (TomlValue) fn(lhs : TomlValue, rhs : TomlValue) -> bool

Parameters

NameTypeNotes
lhsTomlValue
rhsTomlValue

Returns: bool

!= : (TomlValue) fn(lhs : TomlValue, rhs : TomlValue) -> bool

Parameters

NameTypeNotes
lhsTomlValue
rhsTomlValue

Returns: bool

Functions

parse function
fn(input : String) -> Result(TomlValue, TomlError)

Parse a TOML document into a TomlValue tree (D13 — a pure transform returns a Result). The root is always a .Table; .Err carries the byte offset of the fault.

Parameters

NameTypeNotes
inputString

Returns: Result(TomlValue, TomlError)

stringify function
fn(value : TomlValue) -> String

Serialize a TomlValue to TOML text. A table renders as a document (toml.parse(toml.stringify(v)) gives v back for every value the parser produces); any other value renders in its inline form, which is what a caller stringifying one field wants.

Parameters

NameTypeNotesDescription
valueTomlValue

The components. utc_offset_secs is meaningful only for .OffsetDateTime.

Returns: String

toml_parse function
fn(input : String) -> Result(TomlValue, TomlError)

DEPRECATED, removed in v0.2.32: call toml.parse.

Parameters

NameTypeNotes
inputString

Returns: Result(TomlValue, TomlError)

toml_stringify function
fn(value : TomlValue) -> String

DEPRECATED, removed in v0.2.32: call toml.stringify.

Parameters

NameTypeNotesDescription
valueTomlValue

The components. utc_offset_secs is meaningful only for .OffsetDateTime.

Returns: String