silk.toml.value.
Parse a TOML document into an owned tree of values, and read fields from it.
When to use#
Use Toml.parse to read a configuration file or any other complete TOML document. Read
members with Toml.field and Toml.fieldAt, array elements with Toml.item, and text
with Toml.asString. Use silk.toml.codec to convert a value to a number, a boolean, or an
owned string, and silk.toml.output to write a tree back as TOML.
Details#
The parser follows TOML 1.1.0. Tables keep the order of the source. Integers, floats, dates, and
times keep their validated source text, so no precision is lost. Strings are decoded to UTF-8
text when the document is parsed. The root of a parsed document is always a Value.Table. If
parsing fails, everything that was built is released.
Errors#
TomlErrorif the input is not valid TOML, defines a key two times, defines a table that conflicts with an earlier value, or nests more thanMAX_DEPTH(64) arrays or inline tables.offsetgives the byte position of the problem.OutOfMemoryErrorif theAllocatorcannot supply the tree.
Gotchas#
A borrowed field or string cannot live longer than the Value that owns it. The read
functions return None for a missing key and for a value of a different kind. They do not tell
you which case occurred.
Examples#
Read a nested string and an array element#
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.core.option { Option }
import silk.toml.scanner { TomlError }
import silk.toml.value { Toml, Value }
pub effect fn main() -> i32
! TomlError | OutOfMemoryError {
let mut allocator = Allocator.systemAllocatorProvider()
let source = b"tags = [\"fast\", \"small\"]\n\n[owner]\nname = \"Ada\"\n"
let document = run Toml.parse(source) |> Effect.provideMut<Allocator>(&mut allocator)
let name = Toml.field(&document, "owner") |> Toml.fieldAt("name") |> Toml.asString
|> Option<string>.unwrapOr("")
let tags = Toml.field(&document, "tags")
let second = match move tags {
Option<&Value>.Some { value } => Toml.item(value, 1) |> Toml.asString
|> Option<string>.unwrapOr("")
Option<&Value>.None => ""
}
if name != "Ada" || second != "small" {
return 1
}
return 0
}Report the position of a syntax error#
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.toml.scanner { TomlError, TomlReason }
import silk.toml.value { Toml }
effect fn load() -> usize
! TomlError | OutOfMemoryError {
let mut allocator = Allocator.systemAllocatorProvider()
let document = run Toml.parse(b"name = \"Ada\"\nname = \"Grace\"\n")
|> Effect.provideMut<Allocator>(&mut allocator)
return 0
}
effect fn offsetOf(error: TomlError | OutOfMemoryError) -> usize {
return match move error {
TomlError { reason: TomlReason.DuplicateKey, offset } => offset
_ => 0
}
}
pub fn main() -> i32 {
// The second `name` starts at byte 13.
let offset = run Effect.catchAll(load(), offsetOf)
if offset != 13 {
return 1
}
return 0
}Import as Toml with import silk.toml.value { Toml }.
Public declarations: 5.
TableKind#
pub enum TableKindHow a table got its first definition. The parser uses it to reject a later definition that TOML does not allow.
Implicit#
ImplicitA table that exists only because a header named a table inside it, such as a for [a.b]. A
later [a] header can still define it.
Dotted#
DottedA table that a dotted key made, such as a for a.b = 1.
Explicit#
ExplicitA table that a [header] defined. The root table also has this kind.
Inline#
InlineA table written inside braces, such as { x = 1 }. It is closed: no later line can add
members to it.
TomlEntry#
pub struct TomlEntryOne member of a table: a key and its value.
Field key#
pub key: StringThe decoded key. Quotes and escapes are removed.
Field value#
pub value: ValueThe value of the member.
TomlChild#
pub union TomlChildOne element of the child list of an array or a table. Arrays hold TomlChild.Item and tables
hold TomlChild.Member.
Item#
ItemAn array element. It has no key.
Field value#
pub value: ValueThe element.
Member#
MemberA table member.
Field entry#
pub entry: TomlEntryThe key and value of the member.
Value#
pub union ValueAn owned TOML value.
Integers, floats, dates, and times hold their source text, which the parser validated. Convert
them with silk.toml.codec, or copy the text to keep the full precision. Strings are decoded to
UTF-8 text when the document is parsed. Tables keep the order of the source.
Gotchas#
A borrowed field or string cannot live longer than the Value that owns it.
Integer#
IntegerAn integer, such as 42, -17, 1_000, or 0xff.
Field text#
pub text: StringThe source text of the integer, with signs, prefixes, and underscores.
Float#
FloatA float, such as 3.14, 6e-3, inf, or nan.
Field text#
pub text: StringThe source text of the float.
Boolean#
Booleantrue or false.
Field value#
pub value: boolThe boolean.
OffsetDateTime#
OffsetDateTimeA date and time with a UTC offset, such as 1979-05-27T07:32:00Z.
Field text#
pub text: StringThe source text, with all fractional seconds.
LocalDateTime#
LocalDateTimeA date and time without an offset, such as 1979-05-27T07:32:00.
Field text#
pub text: StringThe source text, with all fractional seconds.
LocalDate#
LocalDateA calendar date, such as 1979-05-27.
Field text#
pub text: StringThe source text.
LocalTime#
LocalTimeA time of day without a date, such as 07:32:00.
Field text#
pub text: StringThe source text, with all fractional seconds.
String#
StringA string. Escapes are decoded and the delimiters are removed.
Field text#
pub text: StringThe decoded UTF-8 text.
Array#
ArrayAn array of values, or an array of tables that [[header]] lines made.
Field values#
pub values: Box<List<TomlChild>>The elements in source order. Each one is a TomlChild.Item.
Field tables#
pub tables: booltrue if [[header]] lines made the array. Such an array holds only tables, and a later
key = [...] cannot replace it.
Table#
TableA table of key and value members.
Field entries#
pub entries: Box<List<TomlChild>>The members in source order. Each one is a TomlChild.Member.
Field kind#
pub kind: TableKindHow the table got its first definition.
Toml#
pub struct TomlFunctions that parse and read TOML documents.
When to use#
Use Toml.parse to read a configuration file or any other complete TOML document. Read
members with Toml.field and Toml.fieldAt, array elements with Toml.item, and text
with Toml.asString. Use silk.toml.codec to convert a value to a number, a boolean, or an
owned string, and silk.toml.output to write a tree back as TOML.
Gotchas#
The read functions return None for a missing key and for a value of a different kind. They do
not tell you which case occurred.
Implementation Toml#
impl TomlAssociated function parse#
pub effect fn parse(bytes: &[u8]) -> Value ! TomlError | OutOfMemoryError ? &mut AllocatorParses a complete UTF-8 TOML document and returns its root table.
The parser first validates the full input with TomlScanner.validate, and then builds the
tree.
Errors#
TomlErrorif the input is not valid TOML 1.1.0, or if a key or table is defined in a way that TOML does not allow.offsetis the byte position of the problem.OutOfMemoryErrorif theAllocatorcannot supply the tree. Everything that was built is released.
Method field#
pub fn field<'a>(self: &'a Value, name: string) -> Option<&'a Value>Returns the member name of the table self.
Returns None if the table has no member with that key, or if self is not a table. name
is the decoded key, without quotes.
Method fieldAt#
pub fn fieldAt<'a>(self: Option<&'a Value>, name: string) -> Option<&'a Value>Returns the member name of an optional table. Use it to chain lookups with |>.
Returns None if self is None, or for the same cases as Toml.field.
Method item#
pub fn item<'a>(self: &'a Value, index: usize) -> Option<&'a Value>Returns the element at index of the array self. The first element has index 0.
Returns None if index is out of range, or if self is not an array. In an array of
tables, each element is a Value.Table.
Method asString#
pub fn asString<'a>(self: Option<&'a Value>) -> Option<string<'a>>Returns the decoded text of an optional string value.
Returns None if self is None or is not a Value.String. The text borrows from the
value.
Category: Data formats.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2.