toml
Parse TOML documents into typed silt values and serialize values to TOML.
Summary
| Function | Signature | Description |
|---|---|---|
parse | (String, type a) -> Result(a, TomlError) where a: json.Decode | Parse a TOML document (top-level table) into a record, an enum that has a variant with fields, a json.Value or a type with a json.Decode impl |
parse_list | (String, type a) -> Result(List(a), TomlError) where a: json.Decode | Parse the one array of a document (such as a [[items]] section) into a list |
parse_map | (String, type a) -> Result(Map(String, a), TomlError) where a: json.Decode | Parse a top-level table into a map |
parse_with | (String, Map(String, String), type a) -> Result(a, TomlError) where a: json.Decode | As toml.parse, each field the map names (by its path, a.b) read from the key the map gives for it |
pretty | (a) -> Result(String, TomlError) where a: json.Encode | Pretty-print a value as TOML |
stringify | (a) -> Result(String, TomlError) where a: json.Encode | Serialize a value as TOML |
Errors
Every fallible toml.* call returns Result(T, TomlError). The TomlError
enum has five variants you can pattern-match on, or fall back to
show it with "{e}" when you just want a rendered string:
| Variant | Fields | Meaning |
|---|---|---|
Syntax(msg, offset, line, column) | String, Int, Int, Int | Malformed TOML at the byte offset. A number beyond its range is one too (x = 1e400: invalid floating-point number; x = 9223372036854775808: number too large): the TOML reader refuses it before any type is known, where json.parse gives the field’s TypeMismatch |
TypeMismatch(expected, actual, offset, line, column) | String, String, Int, Int, Int | A value’s TOML type did not match the type it decodes into; actual ends with the value’s path, offset is the byte where the value starts |
MissingField(name, offset, line, column) | String, Int, Int, Int | A required (non-Option) field was absent; name is its path, offset the byte where its table’s header starts ([server], [[posts]], the { of an inline table), 0 for the top level |
Other(msg, offset, line, column) | String, Int, Int, Int | Anything else (a date that is none, serialization failures, document-shape violations); offset is the byte where the value starts; offset, line and column are 0 for one of no place in a text |
UnknownField(name, expected, offset, line, column) | String, List(String), Int, Int, Int | A key of a record’s table that no field names; name is its path, expected the keys the table takes (the record’s fields, in the order its type declares them), offset the byte where the key is written |
An error about a value of the document ends with the path of that value:
the fields of a record and the keys of a map by name (inner.a), a key
that is not made of ASCII letters, digits, _ and - as a JSON string in
brackets (tags["a b"]), and the elements of a list or a tuple by index
(xs[1]; the list that toml.parse_list reads is under its one key, so
its elements are points[2]).
TypeMismatch("Int", "string at inner.a", ..) reads toml type mismatch at line <line>, column <column>: expected Int, got string at inner.a; a missing field is MissingField("inner.a", ..);
an Other about a value (a tuple of the wrong length, a date that is none)
ends with at <path>. An error about the document itself, such as a
Syntax error or a document toml.parse_list finds no one array in, has
no path.
Every error says where in the text its value is, in its last three
fields, as Syntax does: the 0-based byte offset, and its line and
column, both counted from 1, the column in characters (as silt’s own
errors count them; a byte order mark is no column). The place is where the
value starts; for a MissingField, where the header of the table it is
missing from starts, the { of an inline table, or the top of the text
(line 1, column 1) for the top level; for a table written by dotted keys
(server.port = 1), the key; for an UnknownField, the key. Every error
but an Other shows its line and column (toml type mismatch at line 2, column 8: expected List, got integer at tags), and an UnknownField
the keys its table takes (toml unknown field at line 10, column 1: rules[0].macth, expected match or account); an Other shows its message
alone. The byte is for a program that cuts the text. toml.stringify and
toml.pretty read no text: their errors’ offset, line and column are 0.
A json.Decode impl’s error is placed at the part the impl was given,
whatever place the impl wrote (write 0, 0, 0).
import toml
type Meta {
title: String,
tags: List(String),
}
fn main() {
let text = "title = \"T\"\ntags = 3\n"
match toml.parse(text, Meta) {
Ok(meta) -> println(meta.title)
Err(toml.TypeMismatch(expected, actual, _, line, column)) ->
println("a.toml:{line}:{column}: expected {expected}, got {actual}") -- a.toml:2:8: expected List, got integer at tags
Err(e) -> println("a.toml: {e}")
}
}open in playgroundSee stdlib errors for how every error enum is shown.
Decodable types
The type argument of toml.parse, toml.parse_with, toml.parse_list and
toml.parse_map names the type to decode into:
| Function | Type argument |
|---|---|
toml.parse | a record type, json.Value, an enum type that has a variant with fields, or a type with a json.Decode impl |
toml.parse_list | Int, Float, String, Bool, json.Value, a record type, an enum type, a type with a json.Decode impl, or List(T), Option(T), Map(String, T) or a tuple of decodable types |
toml.parse_map | Int, Float, String, Bool, json.Value, a record type, an enum type, a type with a json.Decode impl, or List(T), Option(T), Map(String, T) or a tuple of decodable types |
toml.parse_with | a record type, json.Value, an enum type that has a variant with fields, or a type with a json.Decode impl |
A type argument is written in full (toml.parse_list(text, List(Int)),
toml.parse_map(text, (Int, String))). An alias of one of these is the
type it names.
The fields of a record type, and of each variant of an enum type (and of every record and enum type nested in them), may have these types:
Int,Float,String,Booltime.Date,time.Time,time.DateTimeurl.Url, a string thaturl.parsereads (an error names what is wrong, not the text)time.Instantandtime.Duration, astoml.stringifywrites them:{ epoch_ns = n },{ ns = n }json.Value, which keeps that part of the document as it is (see below)List(T),Option(T),Map(String, T)- tuples, such as
(Int, String) - record types, a generic one with its type arguments (
Box(Int)) - enum types, a generic one with its type arguments (see Enums)
- type aliases of any of these
where T is again one of these types. Anything else (a Set, a generic
record or enum without its type arguments, a builtin enum such as time.Weekday, a function, a Map
whose key is not String, a type parameter) has no decoder.
An Option directly inside an Option (Option(Option(Int)), at any
depth) has no decoder either: None and Some(None) are both written by
leaving the key out, so Some(None) would never read back. Nor has a type
that grows with every level, or one with a record or enum type in a field
whose type arguments are nested more than 32 levels deep, or one that
holds more than 4,096 types at their arguments in all, as for
json.parse. The checker refuses such a type
where it is written at the call; one that reaches toml.parse through a
function or a bound is refused when the program decodes: toml.parse
returns Err(Other(..)) naming the field, its type and the limit, before
it reads the document. In the body of a generic json.Decode impl the
decoder there refuses it when the document reaches the impl’s part, as
for json.parse.
As for json.parse, the check follows a type into a trait
method also where the call goes through a bound: an impl that decodes its
type parameter inside an Option (a record field v: Option(t)), given
an Option that way, is refused where the use gives that Option.
A json.Value, as the type argument or in a field, holds its part of the
document as a json.Decode impl is given
it: a table is a json.Object, an array a json.Array, an integer a
json.Int, a float a json.Float, a date or a time a json.String of its
text. toml.parse(text, json.Value) reads any document, for a tool that
looks at a file whose shape it does not know.
A TOML integer goes into an Int, and into a Float where one is
expected. A TOML float goes into a Float only: x = 1.0 for an Int
field is Err(TypeMismatch("Int", "float at x", ..)), because TOML says
which kind a number is. In the same way a datetime literal (1990-01-01,
07:32:00) goes into a Date, Time or DateTime field only: for a
String field s it is Err(TypeMismatch("String", "datetime at s", ..)), and the
text in quotes ("1990-01-01") is a string. A value that is neither a
datetime literal nor a string, for a Date field d, is
Err(TypeMismatch("time.Date", "integer at d", ..)) (time.Time, time.DateTime likewise).
The type a decoder is given is checked where it is known, as for
json.parse: written at the call (toml.parse(text, Config)), held in a
variable, given to a decoder used as a value, or given to a function or
method that passes it on to the decoder (each call of it is checked, a
trait method’s on a value whose type is a type variable too). A
record with a field no decoder exists for is a compile error that names the
field and its type (or the field of a record type it names that has none);
so is an enum with a variant whose field has none (the error names the
variant), or a type the function does not take (such as
toml.parse(text, Int), or toml.parse(text, List(Int)), whose error points to
toml.parse_list). The check applies equally to a
decoder imported by name (import toml.{ parse }) and to one called through
a module alias, and a type is refused whatever a document would hold (an
Option field whose key is left out, an empty list or map too).
The decoders ask json.Decode of their type argument, as json.parse
does. A function with a type a parameter (any annotation names the variable) that hands it to
a decoder writes where a: json.Decode; only a function with no annotation at all
(fn load(text, t) { toml.parse(text, t) }) is inferred to need it. Without the where
clause the definition is an error:
type variable `a` is not known to implement trait 'json.Decode', which 'toml.parse' needs
A record or enum type with a written json.Decode
impl is decoded by the impl, as json.parse decodes it: one data layer,
one override. See Types with a json.Decode impl.
Types with a json.Decode impl
A type with a written trait json.Decode for T impl is decoded by its
decode wherever a value of the type is in the document: at the top, as an
element of toml.parse_list, as a value of toml.parse_map, in a record’s
or a variant’s field, in a list or a map in one. The impl gets its part of
the document as a json.Value: a table is a json.Object, an array a
json.Array, an integer a json.Int, a float a json.Float, and a date or
time literal a json.String of its text as TOML writes it, offset kept
(1979-05-27, 07:32:00.25, 1979-05-27T07:32:00,
1979-05-27T07:32:00Z, 1979-05-27T00:32:00-07:00), which json.decode
reads back as a Date, Time or DateTime. A float that is no number
(nan, inf) has no json.Value: in such a part it is
Err(TypeMismatch("json.Value", "a non-finite float at readings[1]", ..)).
The fields of T are not looked into, so T may hold a type no decoder
has (a Set). An Option around it stays structural (a key left out is
None). The JsonError the impl returns is the TomlError of the same
variant, with the path of its part appended as to the decoder’s own
errors: Other("bad tags", ..) at posts[1].tags is Other("bad tags at posts[1].tags", ..), MissingField("name", ..) there is
MissingField("posts[1].tags.name", ..); a message is the impl’s text with
the path appended as it is (TypeMismatch("Int", "string at k at posts[1].tags", ..) for one the impl got from json.decode). A Syntax error (an impl that
parses a JSON text of its own) is an Other of json’s message of it,
Other("json syntax error at line 1, column 4: ... at posts[1].tags", ..), since its
place is in that text and not in the TOML document. The first error
counts, the impl’s or the decoder’s own: a record’s errors in the order
its type declares the fields, a map’s in the sorted order of its keys; a
syntax error anywhere in the text wins.
Enums
An enum type the program declares, without type parameters, is decoded from
what toml.stringify writes of a variant, as json.parse decodes one (see
json): a variant without fields is the string of its name,
and a variant with fields is a table whose variant names it and whose
fields array lists its fields.
status = "Active"
history = ["Active", { fields = [2], variant = "Paused" }]
[next]
fields = [1]
variant = "Paused"
An enum type may be the type argument (at the top of toml.parse only a
variant with fields is a table: an enum none of whose variants has fields,
and that has no json.Decode impl, is a compile error, “toml.parse cannot
decode Status: a toml document is a table, and no variant of Status has
fields”), the elements of toml.parse_list, the
values of toml.parse_map, and the type of a field anywhere in a record or
in another enum’s variant. A document that is no variant of the enum is an
Err with the texts of json.parse, toml’s names of the kinds of values and
the path: status = "Gone" is Other("`Status` has no variant `Gone` at status"), status = 1 is TypeMismatch("String or table", "integer at status"), and status = { variant = "Active" } is TypeMismatch("String", "table at status").
Nesting limits
toml.stringify and toml.pretty write a value nested up to 1,000 levels
deep (the same bound as json.stringify). The element of a list or of a
tuple, the field of a record or of an enum variant and the value of a map are
each one level further in than what holds them; the content of a Some is
not (it is written in the Some’s place). A value nested deeper is an
Err(Other(msg, ..)):
toml.stringify: the value is nested more than 1000 levels deep
The parsers stop sooner: toml.parse, toml.parse_list and
toml.parse_map read a document whose arrays and tables are nested up to
79 levels deep, and give a Syntax error (recursion limit exceeded) for
one nested deeper. A value written at more levels than that is valid TOML
that silt itself does not read back.
toml.parse
toml.parse(s: String, type a) -> Result(a, TomlError) where a: json.Decode
Parses a TOML document into a value of type a: a record, an enum that has
a variant with fields (see Enums), a json.Value, or a type with a
json.Decode impl. The type is passed as a
type parameter (see Generics — not a string).
Fields are matched by name; Option fields default to None if missing
from the document. A key that no field names is an error, in a table at any
depth: Err(UnknownField(path, expected, offset, line, column)), the key’s
path, the keys the table takes and where the key is written, so a misspelled key in a file a person wrote is never
lost. (json.parse and csv.parse skip such a key: their documents come
from other programs, which add fields over time.) The first such key in
the text is the table’s error, before the errors of its fields. The table
of a variant with fields takes the keys variant and fields alone. To
allow other keys, read the table into a Map (toml.parse_map) or a
json.Value, which take every key. A key no field can be named after
(default-features) is read by toml.parse_with.
import toml
type Meta {
title: String,
draft: Option(Bool),
}
fn main() {
-- "drafts" for "draft": an error at the key
println(toml.parse("title = \"T\"\ndrafts = true\n", Meta)) -- Err(toml unknown field at line 2, column 1: drafts, expected title or draft)
println(toml.parse("titel = \"T\"\n", Meta)) -- Err(toml unknown field at line 1, column 1: titel, expected title or draft)
println(toml.parse("draft = true\n", Meta)) -- Err(toml missing field at line 1, column 1: title)
}open in playgroundFields of type Date, Time, and DateTime (from the time module) accept
either a TOML native datetime literal or an ISO 8601 string — the same formats
that json.parse accepts for each of those field types:
| Field type | Accepted formats | Example |
|---|---|---|
Date | YYYY-MM-DD, a year of more digits or with a sign as silt shows it (12026-01-01, -001-01-01) | 1979-05-27 or "1979-05-27" |
Time | HH:MM:SS, HH:MM, HH:MM:SS.fffffffff | 07:32:00 or "07:32:00.5" |
DateTime | RFC 3339 / ISO 8601 (YYYY-MM-DDTHH:MM:SS, YYYY-MM-DDTHH:MM, a fractional second), with optional Z or ±HH:MM offset; the year as for Date | 1979-05-27T07:32:00Z |
A time without seconds (HH:MM, and a DateTime written so) is read only
from a string: as a literal (t = 07:32) it is no TOML, a Syntax error.
A DateTime with an offset is turned into the time in UTC, and the offset
is not kept: 1979-05-27T07:32:00+05:30 reads as 1979-05-27T02:02:00.
A fractional second is read to the nanosecond; further digits are cut. A
second 60, a leap second, is no time silt holds: it is refused with an Other
that names the text, from a string and from a literal alike:
invalid time '23:59:60': a leap second (second 60) is not read; a field
out of its range is named as for json.parse (invalid date '1979-02-30': the day is out of range: February 1979 has 28 days).
A date or a time that is none has one message whether it is written in
quotes or as a literal: d = 07:32:00 for a Date field d is
invalid date '07:32:00' (expected YYYY-MM-DD): input contains invalid characters at d.
import toml
type User {
name: String,
age: Int,
active: Bool,
}
fn main() {
let input = "name = \"Alice\"\nage = 30\nactive = true\n"
match toml.parse(input, User) {
Ok(user) -> println(user.name)
Err(e) -> println("Error: {e}")
}
}open in playgroundtoml.parse_with
toml.parse_with(s: String, keys: Map(String, String), type a) -> Result(a, TomlError) where a: json.Decode
Parses a TOML document as toml.parse does, but each field that keys
names is read from the key the map gives for it, as
json.parse_with reads a JSON document: a field
of a nested record by its path of fields (package.default_features), a
list, an Option, a map, a tuple or a variant on the way adding nothing to
it, and an entry holding at every depth below it where the same type comes
again inside itself, the field’s record or one above it (label reads the key in every node of a tree; a
longer entry of the field, kids.label, wins below its own path). An entry whose path goes
into a type with a json.Decode impl, which decodes its part itself, is a
runtime error. This reads a key with a - (default-features) or a capital letter,
which no field can be named. A key that no field reads is still an error,
and UnknownField lists the keys the table takes as the document writes
them. A key of the map that is no path of a field of the type, and a map
that gives one key to two fields of a record, are runtime errors, as for
json.parse_with.
import toml
type Package {
name: String,
default_features: Bool,
}
type Manifest {
package: Package,
}
fn main() {
let text = "[package]\nname = \"x\"\ndefault-features = false\n"
let keys = #{ "package.default_features": "default-features" }
println(toml.parse_with(text, keys, Manifest)) -- Ok(Manifest { package: Package { name: "x", default_features: false } })
println(toml.parse(text, Manifest)) -- Err(toml unknown field at line 3, column 1: package.default-features, expected name or default_features)
}open in playgroundtoml.parse_list
toml.parse_list(s: String, type a) -> Result(List(a), TomlError) where a: json.Decode
TOML’s spec requires the top level of every document to be a table, so there is
no direct equivalent of a JSON top-level array. toml.parse_list therefore
accepts a document whose top-level table contains exactly one key, an array,
and returns the list of values under that key, each decoded into a. The type
is passed as a type parameter (Int, Float, String, Bool, a record
type, an enum type, or a type with a json.Decode impl), as for
toml.parse_map. For a record type the array is the natural
shape of [[items]] sections:
import list
import toml
type Point {
x: Int,
y: Int,
}
fn main() {
let input = "[[points]]\nx = 1\ny = 2\n\n[[points]]\nx = 3\ny = 4\n"
match toml.parse_list(input, Point) {
Ok(points) -> list.each(points) { p -> println("{p.x}, {p.y}") }
Err(e) -> println("Error: {e}")
}
}open in playgroundThe key name (points in the example above) is not checked: any single
top-level key works, xs = [1, 2, 3] for toml.parse_list(text, Int) too.
toml.parse_map
toml.parse_map(s: String, type a) -> Result(Map(String, a), TomlError) where a: json.Decode
Parses a top-level TOML table into a Map(String, v). The type is passed as
a type parameter (Int, Float, String, Bool, a record type, or an
enum type).
import map
import toml
fn main() {
let input = "x = 10\ny = 20\n"
match toml.parse_map(input, Int) {
Ok(m) -> println(map.get(m, "x")) -- Some(10)
Err(e) -> println("Error: {e}")
}
}open in playgroundtoml.pretty
toml.pretty(value: a) -> Result(String, TomlError) where a: json.Encode
Serialises a silt record or map to a multi-line, human-friendly TOML document.
TOML’s default output is already readable (one key per line, nested tables as
[section] headers, arrays of tables as [[section]] blocks), so
toml.pretty differs from toml.stringify only in writing an array of two or
more plain values one element per line, an array inside it one level deeper:
p = [
1,
2,
]
nested = [
[1],
[
2,
3,
],
]
An array inside an inline table stays on its line: TOML writes an inline table on one line.
Note: the top-level value must be a record, a map or a variant with fields; TOML cannot represent a bare scalar or array at top level (nor a variant without fields, which is a string).
toml.pretty and toml.stringify ask json.Encode of the value, as
json.stringify does: Bytes, a set, a function, a channel and a handle have none, so a value
that holds one, wherever in it, is a compile error. A function that hands a value of a type
variable to them says so with where a: json.Encode; without it the definition is an error:
type variable `a` is not known to implement trait 'json.Encode', which 'toml.pretty' needs
import toml
fn main() {
let data = #{ "name": "silt", "version": "1.0" }
match toml.pretty(data) {
Ok(s) -> println(s)
Err(e) -> println("Error: {e}")
}
}open in playgroundtoml.stringify
toml.stringify(value: a) -> Result(String, TomlError) where a: json.Encode
Serialises a silt record, map or variant with fields to a TOML document. Like toml.pretty, the
top-level value must be table-shaped. Each kind of value is written as
follows:
| Value | Written as |
|---|---|
Int, Float, String, Bool | an integer, a float, a string, true or false; a Float with the digits json.stringify writes (1e+300, 1e-7, 0.5) |
List(a), a tuple | an array: (1, "a") is [1, "a"] |
Map(k, v) | a table; a key that is no String is written as its shown text (the Float key 1.0 reads "1.0"); a string inside a key is quoted (["a", "b"] reads '["a", "b"]'); two keys shown as one text (two Bytes longer than the 32 bytes their text shows, alike in those) are Err(Other("toml.stringify: two keys of a map show as the same text: bytes(...)", ..)); a key whose value is None is left out (TOML has no null), so a round trip loses the key: the map read back has no such key |
| a record | a table of its fields, in the order the type declares them; a field that is None is left out (TOML has no null), and reads back as None |
Some(x) | x, as x is written |
None in an array (a list, a tuple, the fields of a variant) | nothing: Err(Other("toml.stringify: TOML has no null: a None in an array", ..)) |
a json.Value | the TOML value it holds: json.Int(1) as 1, json.Array as an array, json.Object as a table (its keys sorted); json.Null as None is |
a value of a type with a written json.Encode impl | the json.Value its encode gives, as a json.Value is written, wherever the value is |
any other variant (of Result too) | a table with the keys fields (an array) and variant (its name); a variant without fields is the string of its name |
Date, Time, DateTime | TOML’s own literals: 2026-10-19, 12:30:00 (with a fractional second only when the value has one: 12:30:00.25) and 2026-10-19T12:30:00 |
Duration, Instant | as the records they are: a table with ns or epoch_ns |
() | nothing: Err(Other("toml.stringify: TOML cannot represent ()", ..)) |
The keys of a map are written in sorted order, the fields of a record in the
order its type declares them; either way the plain keys of a table come
before its sub-tables ([name], [[name]]), as TOML requires. toml.parse
reads a Date, a Time, a DateTime, an Instant and a Duration back
into a field of the same type.
A date whose year has no literal (one before the year 0 or past 9999) is
written as a string of the text silt shows of it, which toml.parse reads
back as well. A variant is read back into its enum type when the program
declares it (see Enums); a variant of a builtin enum is written but
not read back.
import toml
type Package {
name: String,
version: String,
}
fn main() {
let data = Package { name: "silt", version: "1.0" }
match toml.stringify(data) {
Ok(s) -> println(s)
Err(e) -> println("Error: {e}")
}
}open in playground