v0.4.0
Data formats · Lesson 21.4

TOML

Source
Parse a TOML document, read integers, floats, dates and arrays from its tables, and see a bad document refused by line and column.

TOML is a configuration format — the one every Rux.toml in this course is written in. It is made for people to write by hand: one key = value per line, comments with #, and [name] to open a section. And unlike JSON, its values have real types. An integer is not a float even when the float is whole, and a date is a date, not a string that happens to look like one.

This lesson reads a small settings document with the Toml package. Reading the result works the same way as in JSON: find a key, ask what kind of value it holds, take it out.

import Text::{ String, StringBuilder, StringView };
import Toml::{ TomlParse, TomlValue };

The document

TOML is line-based, so the program writes the document as one literal per line:

let good: char8[..][8] = [
    "name = \"Rux\"",
    "released = 2026-10-04",
    "",
    "[server]",
    "port = 8080",
    "ratio = 0.75",
    "tags = [\"web\", \"api\"]",
    "# A comment, which the parser skips."
];
let document = Lines(allocator, good);

and Lines joins them, each followed by a newline, with a StringBuilder. Unescaped, the text it builds is:

name = "Rux"
released = 2026-10-04

[server]
port = 8080
ratio = 0.75
tags = ["web", "api"]
# A comment, which the parser skips.

name and released belong to the top-level table; [server] opens a nested table that holds the rest.

Parsing

TomlParse(allocator, text) -> TomlValue throws TomlParseFailure

The result is the top-level table as a TomlValue tree, or no tree at all: TomlParse throws the reason, and where it was found. Load parses in a try block and prints the reason from its catch arm:

func Load(allocator: Allocator, text: char8[..]) {
    try {
        let root = TomlParse(allocator, text);
        Inspect(root);
    } catch {
        failure => PrintLine("refused at line {}, column {}: {}", failure.line, failure.column, failure)
    }
}

A TOML document is written in lines, so a TomlParseFailure reports a line and a column rather than only a byte — the place a person would look in an editor. Load takes a char8[..], so the String from Lines is passed as document.View().Bytes().

Reading values

Key looks a key up in a table. Like the Member method of the JSON lesson, it answers an optional reference, none when the key is missing — and like Member, it is a method, because a reference it returns borrows from its receiver:

extend TomlValue {
    func Key(&self, key: char8[..]) -> &TomlValue? {
        return self.Find(StringView::FromValidated(key));
    }
}

Inspect cannot do anything more without the [server] table, so it leaves at once when there is none:

let server = root.Key("server") ?? return;

After that line server is a plain &TomlValue. Each kind has its own question, and each answers none for any other kind:

if server.Key("port") is .Some(port) {
    let number = port.AsInteger();
    PrintLine("port      {} (integer: {}, float: {})", number ?? 0, number is .Some(_),
        port.AsFloat() is .Some(_));
}

8080 is an integer, so AsInteger answers it and AsFloat answers none. In JSON both would be "a number"; in TOML the spelling decides the type, and 8080.0 would be a float.

TOML valueKindRead with
"Rux", 'Rux'textAsText(), a StringView
8080, 0x1F90integerAsInteger(), an int64
0.75, 8080.0floatAsFloat(), a float64
truebooleanAsBoolean()
2026-10-04local dateAsDate(), a Date
["web", "api"]arrayLength(), At(i)
[server], { … }tableFind(key), Length()

A date comes out as the Date from the Date lesson, ready to compare or do arithmetic on:

if root.Key("released") is .Some(released) && released.AsDate() is .Some(date) {
    PrintLine("released  {}", date);
}

Arrays are walked by index, and a key that is not there is simply none:

if server.Key("tags") is .Some(tags) {
    for i in 0..(tags.Length() ?? 0) {
        if tags.At(i) is .Some(tag) && tag.AsText() is .Some(text) {
            PrintLine("tags[{}]   {}", i, text);
        }
    }
}
PrintLine("debug     present: {}", server.Key("debug") is .Some(_));

Refusals

let twice: char8[..][3] = ["[server]", "port = 8080", "port = 9090"];
let repeated = Lines(allocator, twice);
Load(allocator, repeated.View().Bytes());
Load(allocator, "released = 2026-13-04");

In TOML a key given twice in one table is an error, not a quiet overwrite — two values for one setting is almost always a mistake, and refusing it is the only way to make sure nobody acts on the wrong one. And a value must be spelled the way its type is: 2026-13-04 is shaped like a date, but there is no thirteenth month, so it is not the shape TOML defines for any value.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// TOML is a configuration format — the one every `Rux.toml` in this course is written in. A
// document is a table of keys and values, `[name]` opens a nested table, and unlike JSON the
// values have real types: an integer is not a float even when the float is whole, and a date is
// a date rather than a string that looks like one.
//
//     TomlParse(allocator, text) -> TomlValue throws TomlParseFailure
//
// The result is a `TomlValue` tree, read the same way as a JSON one: `Find` answers `none` when
// the key is missing, and `AsInteger`, `AsFloat`, `AsDate` and the rest answer `none` when the
// value is some other kind. A refused document gives no tree at all: `TomlParse` throws the
// reason and where it was found, by line and column.
import Allocator::{ Allocator, SystemAllocator };
import Io::PrintLine;
import Text::{ String, StringBuilder, StringView };
import Toml::{ TomlParse, TomlValue };

// A TOML document is lines, so it is written here one literal per line and joined.
func Lines(allocator: Allocator, lines: char8[..][..]) -> String {
    var builder = StringBuilder(allocator);
    for i in 0..lines.length {
        builder.Append(lines[i]);
        builder.Append("\n");
    }
    return builder.TakeString();
}

// Keys are compared as text, so `Find` takes a `StringView`. The answer borrows from the table it
// was found in, so it is an optional reference, and the helper is a method: a reference result
// borrows from the receiver.
extend TomlValue {
    func Key(&self, key: char8[..]) -> &TomlValue? {
        return self.Find(StringView::FromValidated(key));
    }
}

func Inspect(root: &TomlValue) {
    if root.Key("name") is .Some(name) && name.AsText() is .Some(text) {
        PrintLine("name      {}", text);
    }

    // A document without a `[server]` table has nothing more to show.
    let server = root.Key("server") ?? return;

    // The same question asked of an integer and a float. Each answers only its own kind.
    if server.Key("port") is .Some(port) {
        let number = port.AsInteger();
        PrintLine("port      {} (integer: {}, float: {})", number ?? 0, number is .Some(_),
            port.AsFloat() is .Some(_));
    }
    if server.Key("ratio") is .Some(ratio) && ratio.AsFloat() is .Some(value) {
        PrintLine("ratio     {}", value);
    }

    if root.Key("released") is .Some(released) && released.AsDate() is .Some(date) {
        PrintLine("released  {}", date);
    }

    if server.Key("tags") is .Some(tags) {
        for i in 0..(tags.Length() ?? 0) {
            if tags.At(i) is .Some(tag) && tag.AsText() is .Some(text) {
                PrintLine("tags[{}]   {}", i, text);
            }
        }
    }
    PrintLine("debug     present: {}", server.Key("debug") is .Some(_));
}

func Load(allocator: Allocator, text: char8[..]) {
    try {
        let root = TomlParse(allocator, text);
        Inspect(root);
    } catch {
        failure => PrintLine("refused at line {}, column {}: {}", failure.line, failure.column, failure)
    }
}

func Main() {
    let allocator = SystemAllocator();

    let good: char8[..][8] = [
        "name = \"Rux\"",
        "released = 2026-10-04",
        "",
        "[server]",
        "port = 8080",
        "ratio = 0.75",
        "tags = [\"web\", \"api\"]",
        "# A comment, which the parser skips."
    ];
    let document = Lines(allocator, good);
    Load(allocator, document.View().Bytes());

    // Two refusals. A key given twice in one table is an error in TOML, not a quiet overwrite,
    // and a value must be spelled the way its type is: there is no thirteenth month.
    PrintLine("");
    let twice: char8[..][3] = ["[server]", "port = 8080", "port = 9090"];
    let repeated = Lines(allocator, twice);
    Load(allocator, repeated.View().Bytes());
    Load(allocator, "released = 2026-13-04");
}

Besides Io, its Rux.toml lists Allocator, Text and Toml under [Dependencies].

Run it

cd Examples/DataFormats/Toml
rux run
name      Rux
port      8080 (integer: true, float: false)
ratio     0.75
released  2026-10-04
tags[0]   web
tags[1]   api
debug     present: false

refused at line 3, column 12: key given a value twice in the same table
refused at line 1, column 17: not the shape TOML defines

Common mistakes

Try it yourself

  1. Write the port in hexadecimal, port = 0x1F90. What does AsInteger read?
  2. Add debug = true to the [server] table and read it with AsBoolean. (The array's length, [8], has to grow too.)
  3. Open [server] a second time further down the document. Is that refused like a repeated key?
  4. Add a key with a value of your own and read it back. Then change the spelling of its value so the parser refuses it, and read the line and column.

Learn more

  • JSON — the same way of reading a tree, for a format without types
  • TOML write — changing the tree and writing it back
  • Date — the type AsDate answers
  • Coalesce exit — leaving with ?? return when a value is missing
  • Manifest — the Rux.toml file, the TOML you write most often