docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#NABION

On this page

This chapter shows how to read and write configuration files in NABION (Nabi Object Notation), Nabi's data format. There is no new syntax to learn: a NABION file uses the same literal syntax you write values with in Nabi source. The package manifest nabi.nabion uses this format too.

#The format at a glance

A file holds one value, usually a single struct.

app.nabion
// app.nabion
Config {
    name: "demo",
    retries: 3,
    ratio: 0.75,
    tags: ["a", "b"],
    limits: { "cpu": 2, "mem": 512 },
    mode: Mode::Fast,
    proxy: none,
}
FormExample
Basic valuesnone, true, 42, 0xff, 3.14, 'a', "text"
List / tuple[1, 2, 3], ("x", 1)
dict{ "k": 1, "j": 2 } (keys are values)
structPoint { x: 1, y: 2 }, Pair(1, 2)
enum variantMode::Fast, Shape::Circle(1.0), Shape::Rect { w: 2, h: 3 }

// comments and trailing commas are allowed. "Code" such as variables, operators, function calls, and f-strings is not. NABION is pure data that never executes.

##[derive(Nabion)] with from_str / to_str

Put #[derive(Nabion)] on a struct or enum and you can read it with from_str and write it with to_str from std::nabion. The variable's type annotation decides which type is read.

Nested structs, lists, and enums are all read the same way. When a field is missing, as in the second server, these rules apply:

  • If the field has a = default, that value (port: u16 = 80).
  • If the type is T | none, none (tls).
  • Otherwise, an error.

to_str writes the canonical form: 4-space indentation, one line if it fits in 100 columns, otherwise one element per line with a trailing comma. Reading the canonical form back yields the same value. to_str_flat writes the same text on one line, whatever its width. Both throw a NabionError for a value with no NABION form, such as a NaN float.

#Enums, tuple structs, Dict

Enum variants are always written with their full path, like Enum::Variant. Tuple structs are written Name(a, b). Standard collections and tuples are read directly, without a derive.

Tip

Dict and Set keep insertion order, so to_str writes their entries in the order they were added, the same on every run.

#Bad input and errors

from_str throws NabionError when something is wrong. Messages have the form line:column: description, so a person can find the spot in the file right away.

nabi
use std::nabion;

#[derive(Nabion)]
struct Server { host: str; port: u16; }

fn check(text: str) {
    let s: Server = try nabion::from_str(text) catch e {
        println(f"error: {e}");
        return;
    };
    println(f"ok: {s.host}:{s.port}");
}

check(r#"Server { host: "h", port: 22 }"#);
check(r#"Server { host: "h" }"#);
check(r#"Server { host: "h", port: 70000 }"#);
check(r#"Server { host: h, port: 22 }"#);
check(r#"Server { host: "h", port: 22, user: "me" }"#);
check(r#"Client { host: "h", port: 22 }"#);
ok: h:22
error: 1:1: missing field `port` in Server
error: 1:27: integer 70000 is out of range for u16
error: 1:16: bare identifier `h` is not allowed in NABION (strings are quoted, variants are written `Enum::h`)
ok: h:22
error: 1:1: expected Server, found `Client { .. }`

A field the type does not have (user) is skipped, so a file written for a newer version of the program still reads. To make such a field an error, for example to catch a misspelled key, put #[nabion(deny_unknown_fields)] on the type.

#Reading without a type: Value

Data whose structure you don't know in advance can be read into the Value enum with nabion::parse. Value has variants such as None, Int, Str, List, Dict, Struct, and Variant, and kind_name() returns the name of the kind. Later releases may add variants, so a match on a Value needs a _ arm.

nabi
use std::nabion;
use std::nabion::Value;

let v = try! nabion::parse(r#"Site { title: "nabi", pages: 12, draft: false }"#);
match v {
    Value::Struct { name, fields } => {
        println(f"struct {name ?? "(anonymous)"}");
        for (k, x) in fields {
            println(f"  {k}: {x.kind_name()} = {x}");
        }
    },
    _ => println(f"not a struct: {v.kind_name()}"),
}
struct Site
  title: string = "nabi"
  pages: integer = 12
  draft: bool = false

#Reading and writing configuration files

Combined with fs from chapter 13, this handles configuration files. The program that builds this site does exactly that: it reads site.nabion from the site repository into a #[derive(Nabion)] struct Site, and fields with defaults can be omitted from the file.

The example below writes a configuration to a temporary file, reads it, modifies it, and writes it back. load can throw both IoError and NabionError, and the caller catches each kind separately.

Rewriting with to_str drops comments. Files that people edit are better left for programs not to overwrite. nabi fmt only fixes indentation in .nabion files and leaves comments and layout alone.

#Summary

  • NABION is a data format that uses Nabi literal syntax as is; the file extension is .nabion.
  • Add #[derive(Nabion)], read with nabion::from_str, write with nabion::to_str (or to_str_flat for one line).
  • A missing field takes its = default, or none if its type is T | none; otherwise it is an error. Unknown fields are skipped unless the type says #[nabion(deny_unknown_fields)].
  • Error messages have the form line:column: description.
  • If you don't know the structure, use nabion::parse to get a Value.
  • Dict keeps insertion order, so a map is written back in the order it was read.

#Further reading

Found a mistake? Edit this page on GitHub. Last updated