Skip to content

18. Typed literals and keyword declarations

Taught in Typed Literals.

A typed literal is a type name written directly against a string literal: Date"2026-05-04", Regex`\d+` . Its surface forms are in §3 Typed literal forms. This section says what one means.

A type backs its literals by implementing Literal, from std::literals:

pub interface Literal<I, R>
    fn from_fragments(fragments: List<Fragment<I>>) -> R
end

pub enum Fragment<T>
    Static String
    Dynamic T
end

The impl chooses I, what each ${...} slot’s value must be, and R, the literal’s result. I may be an interface, such as Display, whose slot values each implement it in their own way, or a concrete type: Fragment<String> accepts only String slots. from_fragments is an ordinary function body.

import
    std::io
    std::literals.{Fragment, Literal}
end

pub struct Box
    contents: String
end

impl Literal for Box
    fn from_fragments(fragments: List<Fragment<String>>) -> Box
        body = Iter.reduce(fragments, "", fn acc, frag ->
            case frag
                .Static(s)  -> acc + s
                .Dynamic(v) -> acc + v
            end
        end)

        Box{contents: body}
    end
end

fn main()
    name = "world"
    b = Box"hello ${name}"
    io.print(b.contents) // hello world
end

Neither Literal, Fragment nor Fragment’s variants are in the prelude. Only a handler’s author names them, so they are not reserved names.

The prefix is a type, found by ordinary name lookup, and its Literal or CheckedLiteral impl supplies the handler. Importing the type brings its impl, as it brings a Display impl. A domain type makes the literal read as a constructor (Date"2026-05-04"), and a zero-sized type gives a DSL a stateless prefix (type Sql, then Sql"SELECT ...").

  • A prefix that is not a type in scope is the error tag 'Nope' is not in scope — a typed literal `Nope"..."` requires `Nope` to be a type with an `impl Literal for Nope` block.
  • A type with no Literal impl is type 'Plain' has no typed-literal handler — write `impl Literal for Plain { fn from_fragments(fragments: List<Fragment<I>>) -> R }` .
  • A slot whose type does not implement I, or is not I, is an error at the slot: slot expression of type 'Int' does not match required type 'String' (required by tag 'Joiner').

Html is a prefix the compiler knows. std::html’s Html has no Literal handler: the compiler reads an Html literal’s text as an HTML template (§18 HTML templates), and the literal is an Html, never a Result. A type named Html declared anywhere else is an ordinary prefix, since a type’s identity is its declaring file and name.

One from_fragments per prefix. A typed literal names no interface, so its prefix type may declare from_fragments only once. When another of its impls, or its inherent block, also declares from_fragments, the literal is an error at the prefix that names the rival declaration:

typed literal 'Pick"..."' is ambiguous: `impl Other for Pick` also declares `from_fragments`, at line 16, and a typed literal has no way to say which one it means — rename one of them, or drop `impl Other for Pick`

The error is about the literal: two impls that both declare from_fragments are legal while nothing writes Pick"...". An inherent from_fragments beside the impl is also an error at its own declaration, since a type’s own function may not share a name with one of its impls’ functions (§12 Function Name Collisions). The rule matches the call the literal stands for, which §12’s ambiguity check already rejects.

A typed literal is a call of its prefix type’s handler:

<Type>.from_fragments(fragments: List<Fragment<I>>): R

Each ${expr} slot becomes a Dynamic(value), and the text between slots a Static(text). The list always alternates Static, Dynamic, ..., Static: the first and last Static are present even when empty. Joiner"name: ${name}, age: ${age}" is:

Joiner.from_fragments(
    [Static("name: "), Dynamic(name), Static(", age: "), Dynamic(age), Static("")]
)

A triple-quoted typed literal strips its leading newline, common indentation and trailing newline as a triple-quoted string does, and the ${...} and \${ rules of strings apply inside a non-raw body (§3 String Literals). A raw (backtick) body has no slots: it is one Static holding the text as written.

The type of a typed literal with a ${...} slot is R: Date"2026-${month}-04" is a Result<Date, Error>, built when the program runs. A literal without slots is checked at compile time, and when its handler returns Result<T, E> its type is T (below): Date"2026-05-04" is a Date. A checked literal’s type is its build’s result with or without slots (§18 Checked literals), and an Html literal is always an Html. A Regex literal is the one whose type depends on its text: with no ${...}, Regex"(\\d+)" is a Regex<String>, while Regex"room ${n}" is Result<Regex<List<Maybe<String>>>, String> (std::regex).

A literal without slots is checked at compile time

Section titled “A literal without slots is checked at compile time”

Taught in Typed Literals.

A typed literal with no ${...} slot, written with double quotes, triple quotes or backticks, gives its handler fixed text. The compiler runs the handler while it checks the program. When the handler returns Result<T, E>, the literal’s type is T:

  • Ok(v): the literal is that T. Date"2026-05-04" is a Date and Regex`\d+` is a Regex<Unit>; neither needs a ?, and once letters = Regex`[A-Za-z]+` works at the top level of a file.
  • Err(e): the literal is a compile error carrying the handler’s message (e’s Display, or its Debug when it has none): typed literal Regex`[` is invalid: error parsing regexp: missing closing ]: `[` .

A handler that returns T itself gives the type T, and it runs at compile time too. Any handler that reaches an effect (§19 Effects), traps, or does not finish within the compiler’s step limit cannot be run at compile time, and the literal is an error that says so: typed literal Loud"x" cannot be checked at compile time: its handler has effects (Loud.from_fragments calls io.print), with the help a typed literal without `${...}` slots is checked at compile time; to build the value when the program runs, call one of `Loud`'s functions instead, such as its `parse`, and handle its result. A text known only when the program runs goes through such a function, Date.parse(text), or into a slot.

A ? on a literal without slots is the ordinary error `?` requires a Result or Maybe, got Regex<Unit>, whose hint says to remove the ?.

import
    std::calendar.Date
    std::io
    std::regex.Regex
end

once letters = Regex"[A-Za-z]+"

fn main()
    digits: Regex<Unit> = Regex`\d+`
    io.print(String.find_all("order 66, aisle 7", digits)) // [66, 7]
    io.print(String.find_all("ab 12 cd", letters))         // [ab, cd]
    io.print(Date.year(Date"2026-05-04"))                  // 2026
end

When the program runs, a literal without slots still calls its handler, once per literal site: the first evaluation builds the value and later ones reuse it. The handler is pure and its input fixed, so the run gets the value the compiler got.

A type may implement CheckedLiteral<I, T> from std::literals instead of Literal:

pub interface CheckedLiteral<I, T>
    fn check(statics: List<String>) -> Result<Unit, LiteralError>

    open fn check_type(statics: List<String>, arguments: List<String>) -> Result<Unit, LiteralError>
        _ = arguments
        check(statics)
    end
    fn build(fragments: List<Fragment<I>>) -> T
end

Its literals are checked literals. A checked literal’s type is T in every quote style, with or without slots; it is never a Result:

  • check runs while the program is checked, once per literal, on the literal’s static text: the n + 1 pieces around its n slots, in order, empty ones included. It follows the rules of a handler run at compile time: a check that reaches an effect (§19 Effects) is one error at the check, Url.check has effects (...); a checked literal's check runs when the program is checked, and one that does not finish within the step limit is an error at the literal.
  • What the compiler runs is check_type, whose default is check. It gets the statics and a description of the literal’s type: each of its type arguments as Nomi spells it, in order, after the expected type solved them (§18 Literals typed by their position). A Route<{id: Uuid}> literal gets ["{id: Uuid}"], a Url literal []. The description is text, not the types; nothing in it is a value of the type. A type whose text must agree with its type arguments, as a route’s wildcards agree with its parameters, writes check_type; it follows check’s rules, and an effect in it is reported as Route.check_type has effects (...).
  • A generic type’s impl, impl CheckedLiteral<String, Route<P>> for Route<P>, gives each literal fresh type arguments, which the expected type solves as it solves a generic call’s.
  • std::http’s Route<P> is the one checked literal whose type follows from its text when nothing else gives it, as a Regex literal’s captures do: with no expected type, or one that leaves P open once the arguments that solve it on their own are checked (§18 Literals typed by their position), Route"GET /users/{id}" is a Route<{id: String}>, a String field per wildcard ({rest...} included), and a route with none is a Route<Unit>. Its check_type holds the wildcards to P’s fields, the pattern has `{id}`, but `{post_id: Uuid}` has no field `id` at the wildcard, and the checker holds each field’s type to Parse and Display: a route's parameters are read from its path and written into links as text: each field's type implements `Parse` and `Display`, and `Bool`, the type of `id`, does not implement `Parse` .
  • An Err(LiteralError{fragment:, offset:, message:}) is a compile error carrying message at the character offset code points into static fragment, counted in the text as check received it. An offset at a static’s end points at the ${ of the slot after it; fragment 0 and offset 0 point at the literal.
  • build runs when the program runs, gets the fragments from_fragments would get, and cannot fail: once check accepts the text, every slot value must build. A build that traps anyway traps where it runs.

A type implements Literal or CheckedLiteral, not both: type `Twice` implements both `Literal` and `CheckedLiteral`; a typed literal has one handler. The orphan rule below applies to both.

std::url’s Url is a checked literal, and its slot interface is Display: a slot’s value is its Display text, escaped for where it stands, as one segment in the path, one key or value in the query, or the fragment. A . or .. in the path is escaped too. A Query or a Url in a slot is its text like any other value, one segment or one value; Url.with_query and Url.join_path add pairs and segments. A slot in its scheme, user or host is a compile error at the slot, whatever its type: typed literal Url"https://${host}/greet" is invalid: a slot in the scheme, user or host cannot be escaped.

import
    std::io
    std::url.Url
end

fn main()
    name = "ann b"
    u = Url"https://api.example.com/greet/${name}"
    io.print(u) // https://api.example.com/greet/ann%20b
end

std::toml’s Toml is a checked literal too. Its text, with a stand-in for each slot, must be TOML. A slot in value position (after =, or as an array item) is its value’s TOML. The slot interface ToToml turns the value into a Toml.Value (a string, number, boolean, date or time, an array, or an inline table), and the literal writes that itself: a String quoted and escaped, a List as an array, a Map<String, V> as an inline table with quoted keys. No impl writes TOML text, so no slot can add a key. A slot in key position (at the start of a line, after a . in a dotted key, in a table header, or as an inline table’s key) is one quoted key. A slot anywhere else is a compile error at the slot: typed literal Toml"user = \"${name}\"" is invalid: a slot cannot go inside a TOML string; write it where the whole value goes, as in `key = ${value}` .

import
    std::io
    std::toml.Toml
end

fn main()
    user = "x\"\nadmin = true"
    io.print(Toml.text(Toml"user = ${user}")) // user = "x\"\nadmin = true"
end

A ? or ! on a checked literal is the ordinary error for a value that is not a Result, and a ?’s hint says the literal is already its type: a `Url` literal is checked when the program is checked, so this one is already a Url: remove the `?`. std::literals::testing’s build_each runs a type’s check and then its build over test values, so a library’s tests can hold build to its contract.

A string literal with no tag, written where the expected type is a type with a CheckedLiteral impl, is that type’s checked literal, as if the type’s name were written before it. It is the rule a dot-variant follows (§4 Variant Resolution): the expected type the checker’s outside-in walk finds names the type, and the literal is read as that type’s. So an annotated binding, an argument, a struct field, a returned value, a list element and a case or if arm in one of those all give it.

import
    std::io
    std::url.Url
end

struct Link
    label: String
    to:    Url
end

fn home() -> Url
    "https://example.com/"
end

fn main()
    name = "ann b"
    profile: Url = "https://example.com/users/${name}"
    links = [Link{label: "home", to: home()}, Link{label: "me", to: profile}]

    io.print(
        links
        |> Iter.map(fn l -> "${l.label}: ${l.to}")
        |> Iter.to_list()
    )
end
  • The literal is checked as the tagged one is: its slots take the impl’s slot type, check runs when the program is checked, and a refusal is an error at the place it names, labelled with the type: a `Url` literal "https://${host}/a" is invalid: a slot in the scheme, user or host cannot be escaped.
  • Only a literal converts. A String value where a Url is expected is the ordinary mismatch, argument 1: expected Url, got String.
  • A checked literal, tagged or not, passed to a generic function where its parameter’s type holds a type parameter that another argument solves on its own is checked after that argument, against the solved type. An argument solves it on its own when its type does not depend on its slot: a name of a value or function that is not generic, a lambda whose parameters are all annotated, or a call of a named function on such arguments whose result names no type parameter its parameters leave out. With fn update(r: Request, p: {id: Int}) -> Response, Route.to_with("PATCH /todos/{id}", update) checks the route as a Route<{id: Int}>, and so does Route.to_with("PATCH /todos/{id}", auth(update)) with a middleware fn auth<P>(handler: (Request, P) -> Response) -> (Request, P) -> Response, through any number of layers. A lambda that leaves a parameter’s type to the call, fn r, p -> ..., takes it from the literal, which is checked first, as written. The arguments still run in the order they are written. A literal piped into such a stage, "PATCH /todos/{id}" |> Route.to_with(update), is typed the same way, though there only a name of a value or a call on such names counts, since the head is checked before the stage.
  • With no expected type, or one with no CheckedLiteral impl, the literal is a String, as always. A Literal impl does not make a literal typed by its position, since such a literal is its handler’s result, usually a Result built when the program runs.
  • The literal keeps the form it was written in; nomi fmt does not add or remove a tag.

A handler is an ordinary interface impl, so the impl rules apply (§12). There is at most one Literal or CheckedLiteral impl for a type in a program, and the orphan rule requires the interface or the prefix type to be declared in the implementing module. Unlike other impls (§12 Foreign Types), a Literal impl is not admitted by a type argument the module declares: impl Literal for List<Mine> is an orphan impl even when Mine is the module’s, since the handler is chosen by the prefix alone.

An Html literal, with std::html’s Html as its prefix, is a fragment of HTML that the compiler reads when it checks the program. It is zero or more nodes: text, elements and comments, with an optional <!DOCTYPE html> at its start. Every element opened in the literal is closed in it.

A small fragment is usually written on one line with double quotes, its attributes quoted with ', since a " ends the literal. Markup of several lines is triple-quoted:

import
    std::html.Html
    std::io
end

fn badge(count: Int) -> Html
    Html"<span class='badge'>${count}</span>"
end

fn comment(author: String, body: String, likes: Int) -> Html
    Html"""
    <article class="comment">
      <p>${author} ${badge(likes)}</p>
      <p>${body}</p>
    </article>
    """
end

fn main()
    io.print(Html.to_string(comment("Bo & Co", "<b>hi</b>", 2)))
end

The program prints the comment with its text escaped:

<article class="comment">
  <p>Bo &amp; Co <span class='badge'>2</span></p>
  <p>&lt;b&gt;hi&lt;/b&gt;</p>
</article>

The template language is HTML with stricter rules:

  • Every non-void element has an explicit end tag (</p>, </li>, </td>, which HTML lets a page leave out).
  • A /> closes only a void element (<input/>) or an element inside <svg> or <math>.
  • An element’s name is an HTML, SVG or MathML name, or a custom element’s name, which has a hyphen (el-dropdown). Attribute names are not checked.
  • An attribute value quoted with ' is read as one quoted with ": the same contexts, escaping and errors.

Each ${...} slot has the context of where it stands, which decides how its value is written and which type it must have:

ContextExampleThe value must beWritten as
Element content<p>${x}</p>ToHtml, or another Displaya ToHtml value by its to_html: String and numbers escaped as text, Html as it is, List<Html> joined, a Maybe of a ToHtml value as that value and None as nothing; another Display value’s text escaped
Text of <title> or <textarea><title>${t}</title>Display, or a Maybe of oneescaped text; an Html is refused, since its markup could end the element
Quoted attribute valueclass='a ${c}', data-reaction="${kind}"Display, or a Maybe of oneescaped for an attribute: &, <, >, " and '
URL attribute, the start of its valuehref="${link}"UrlValue (Url, SafeUrl, a Maybe of one)a Url whose scheme is not http, https, mailto or tel as about:invalid#unsafe-url; then escaped
URL attribute, after texthref="/posts/${id}", ?q=${q}, #${f}Display, or a Maybe of onepercent-encoded as a path segment (/ and : included), a query value or a fragment, then escaped
style attributestyle="width: ${pct}%"CssValue (Int, Float, Decimal, Css, a Maybe of one)a number as written; a Css as it is; escaped
A whole unquoted valuechecked=${on}, title=${tip}OptionalAttribute (Bool, Maybe<String>)True writes checked; False and None leave the attribute out; Some(s) writes title="..." escaped

The URL attributes are action, background, cite, formaction, href, icon, longdesc, manifest, poster, profile, src, usemap, xmlns, and data on <object>.

A value of the wrong type is an error at the slot that says what the slot takes: <title>${page}</title> with an Html is this slot takes a `Display`, and an `Html` is not one, with help for the context.

In element content, a type that implements ToHtml renders itself, even when it is also Display. Std’s Maybe, Result, collections and tuples are Display, but their text is not the value’s, Some(x) or [a, b], so element content refuses one that is not ToHtml: <p>${names}</p> with a List<String> is element content does not show a `List<String>` , with help to render the elements with Html.each. A value of a type parameter is taken as a ToHtml.

A slot shows a part of the page only when a condition holds by holding a Maybe: ${if active then Some("active") else None} is None when active is false (§8 if/else). A fragment over several lines is wrapped by a |> Some() on the line after its closing """, with else None below it. In a whole unquoted value a Maybe writes the attribute or leaves it out. In every other context it writes its value as that context writes one, or nothing for None, so a Maybe’s text, Some(...), is never written:

import
    std::html.Html
    std::io
end

fn inbox(unread: Int, active: Bool) -> Html
    count = if unread > 0 then Some(Html" <b>${unread}</b>") else None

    Html"<a class=${if active then Some("active") else None}>Inbox${count}</a>"
end

fn badge(label: String, urgent: Bool, count: Maybe<Int>) -> Html
    Html"<span class='badge ${if urgent then Some("urgent") else None}' data-count='${count}'>${label}</span>"
end

fn main()
    io.print(Html.to_string(inbox(2, True)))
    io.print(Html.to_string(inbox(0, False)))
    io.print(Html.to_string(badge("new", True, Some(3))))
    io.print(Html.to_string(badge("old", False, None)))
end
<a class="active">Inbox <b>2</b></a>
<a>Inbox</a>
<span class='badge urgent' data-count='3'>new</span>
<span class='badge ' data-count=''>old</span>

The rule goes by the slot’s type when the program is checked: a value whose type is a type parameter or Display writes its Display text, Some(...) included, when it holds a Maybe. In a context that takes a Display, a Maybe of a Maybe is an error at the slot, this slot does not show a `Maybe<Maybe<Int>>` , with help to flatten it with Maybe.flatten. None in a URL attribute’s value writes an empty value, href='', which is a link to the page itself.

A slot anywhere else is an error at the slot:

WhereError
A tag or attribute namea slot cannot name a tag or an attribute: `<${tag}>`
Part of an unquoted valuequote the attribute's value to put a slot in it: `class="...${...}..."`
An unquoted URL or style valuequote `href`'s value to put a slot in it: `href="${...}"`
An event handler attributea slot in `onclick` would be JavaScript; pass the value in a `data-` attribute and read it in a script
Inside <script> or <style>a slot in a `<script>` element would be JavaScript; pass the value in a `data-` attribute
Inside a commenta slot in an HTML comment is not rendered safely
In srcseta slot in `srcset` is not supported; build the attribute from `SafeUrl` values
A URL’s scheme or hosta slot in a URL's scheme or host cannot be escaped: `href="https://${host}/"`

Malformed markup is an error at the place it is noticed: `<div>` is not closed in this literal, `</span>` closes `<p>`, opened at line 4, a `/>` does not close `<div>` in HTML; write `</div>` , unknown element `<dvi>`; a custom element's name has a hyphen.

A raw body, Html`...` , is a template with no slots under the same rules.

The value. Static text is written exactly as it stands, after a triple-quoted literal’s indentation strip; no whitespace is collapsed. An Html built from templates, Html.text, Html.each and Html.concat is balanced markup, because each template was checked and each slot’s value was escaped or was itself such an Html. Html.trusted(markup) is the one way to insert markup unchecked, for HTML a trusted renderer produced, such as Markdown.

How it is built. The literal is read once, when the program is checked; nothing is parsed when it runs. It stands for a call of std::html’s assemble over the static text and one call per slot. The slot’s context picks that function, and in element content the value’s type does too (slot_text for a ToHtml, slot_text_display for another Display), as it does for a Maybe in a context that takes a Display (slot_attribute_maybe); the function’s parameter type is the slot’s type rule:

html.assemble(["<p class=\"", html.slot_attribute(c), "\">", html.slot_text(x), "</p>"])

The slot expressions are the program’s own, so hovering and errors inside a slot are at the source.

A top-level declaration that starts with a keyword and a name is a keyword declaration:

[pub] keyword name [(params)] [-> type] [raw body]

Each part after the name may be left out, and the body is a backtick string. Two identifiers in a row at the top level of a file always start a keyword declaration (foo bar is unknown declaration keyword `foo` ), and a line break between them ends a statement. The keyword decides what the declaration means: phrase and noun (Phrases below) and embed (Embedded files below) are the keywords Nomi knows.

ViolationError
Another keywordunknown declaration keyword `database`
messageunknown declaration keyword `message` , with a help naming phrase
A type name as the namethe name of a `phrase` is snake_case, not the type name `Hi`
A name before a type name`strct` declares nothing: a type is declared with `struct`, `enum` or `type`
A tag on a phrase bodya `phrase` body is MessageFormat 2 text and takes no tag: remove `Mf2`
A result type on a phrasea `phrase` declaration returns a `Phrase`, so it is written with no `-> String`

Nomi has no macros. Code a library would generate from data, such as functions from SQL queries, is written by a tool the library ships into ordinary .nomi files that a program imports and commits (nomi tool, tooling reference; taught in Generating Code).

Taught in Translating Text.

Text a person reads is declared once, in the program’s source language, with phrase, and translated in catalogs, one TOML file per locale and Nomi file. The text is MessageFormat 2 (MF2). Catalogs and [i18n] are in the tooling reference.

/// How many items the cart holds.
pub phrase cart_items(count: Int) `
    .input {$count :integer}
    .match $count
    one {{{$count} item in your cart}}
    * {{{$count} items in your cart}}
    `

A phrase declares a function of the same name whose parameters are the phrase’s and whose result is a Phrase (std::phrase). It is called like any function of its file (cart.cart_items(3)) and takes a doc comment and pub. It writes no result type. Its body is the text in the source locale, [i18n].source_locale, English unless the manifest says otherwise.

A Phrase holds which phrase and its arguments, and no locale; Phrase.format(phrase, locale) writes it in one. Two phrases are equal when they are the same declaration with equal arguments, Debug shows cart.cart_items(3), and Phrase implements Localize, so a phrase passed to another phrase is formatted in the same locale.

MF2 text formats with the stable functions :string, :number, :integer, :percent and :currency, the draft :date, :time and :datetime, and Nomi’s own :nomi:noun, :nomi:gender, :nomi:list and :nomi:weekday. Each takes a parameter of the types and the options std::phrase lists, and anything else is a compile error at the placeholder:

  • A field the value lacks is an error at the option, en: `hour` names a time of day, and `$day` is a `Date`, which has none, and so are styles beside fields. :date, :time and :datetime select nothing: en: `:date` writes a calendar value and selects nothing, whose help points to :nomi:weekday.
  • :nomi:weekday only selects. A selector that names one day needs all seven, and a placeholder that writes it is en: `:nomi:weekday` selects by the day of the week and writes nothing.
  • A placeholder with no function, {$name}, writes its value with Localize, so its type must implement Localize (Int, Float, Decimal, String and Phrase do).
  • An enum selected or written with :string reads as its variant’s name (Shipped), whatever its Debug says.
  • :offset and :unit are each `:offset` is not supported yet.

Taught in Translating Text.

A sentence often agrees with a noun: in Polish, the possessive, auxiliary and participle of “Your book has shipped” follow the noun’s gender. A noun declaration names such a thing as a Noun, a prelude type:

pub noun book `.input {$count :integer} .match $count one {{book}} * {{books}}`

/// Sent when a parcel leaves the warehouse.
pub phrase has_shipped(product: Noun) `Your {$product :nomi:noun} has shipped.`

A noun takes no parameters and no result type. Its body is its form in the source locale, MF2 over one implicit $count: Int, how many things the text names. shop.book is the noun: a Noun a phrase takes as an argument and a struct may hold. Its catalog entry, in the catalog of the file’s phrases, gives the source it was translated from, its gender where the language’s nouns have one, and one form per grammatical case, each MF2 over $count:

[book]
source = '''.input {$count :integer} .match $count one {{book}} * {{books}}'''
gender = "feminine"
nominative = '''.input {$count :integer} .match $count one {{książka}} few {{książki}} many {{książek}} * {{książki}}'''
genitive = '''.input {$count :integer} .match $count one {{książki}} few {{książek}} many {{książek}} * {{książki}}'''

[has_shipped]
source = '''Your {$product :nomi:noun} has shipped.'''
text = '''
.input {$product :nomi:gender}
.match $product
feminine {{Twoja {$product :nomi:noun} została wysłana.}}
inanimate {{Twój {$product :nomi:noun} został wysłany.}}
* {{Twoja przesyłka została wysłana.}}
'''

A language’s genders and cases are CLDR’s grammatical features: Polish has animate, inanimate, personal, feminine and neuter, and seven cases. A language CLDR lists no cases for, English among them, has only the nominative, the form the declaration gives.

{$product :nomi:noun} writes the noun’s form for case and count in the locale of the phrase’s text, and .input {$product :nomi:gender} selects by its gender there. {$product} with no function, and Localize, write its nominative for one thing. A noun is formatted only through a phrase or Localize, never by Display. Two nouns are equal when they are the same declaration, and Debug shows shop.book.

The set of nouns is closed: every Noun is a declaration in a file the program reaches, so agreement is checked over the whole program, as coherence is. A name known only at run time, such as a title from a database, is a String, and passing one where a Noun is expected is the error expected Noun, got String, whose hint says a noun is a declaration. A phrase writes such a name through a String parameter, in a sentence that does not agree with it. A noun must be declared in a project whose source locale’s language has no grammatical gender, since the declaration has no place to give one: `noun book` is declared in Polish, whose nouns have a grammatical gender, which a `noun` declaration has no place to give.

Taught in Translating Text.

Each check is an error at the declaration, in its text, or in the catalog entry it is about:

  1. Completeness. Every phrase has text in every locale locales lists: in that locale’s catalog, in a listed ancestor’s on its CLDR fallback chain (pt-PT may leave out what pt says), or because the source locale is that ancestor. A locale in partial_locales may leave a phrase out, and the phrase then shows in the source locale.

  2. No stray entries. A catalog entry that names no phrase or noun of its file (pl: `ghost` is not a phrase or noun of cart.nomi), a catalog file whose Nomi file does not exist, and a catalog directory for a locale [i18n] does not list, or for the source locale.

  3. Parameters. Every variable a text reads is a parameter or a variable the text declares (pl: `$cnt` is not a parameter of `cart_items` ), and the source text uses every parameter (en: the source text of `m` does not use `$count` ).

  4. Types. Each function takes the types its row above names, and an unannotated placeholder’s type implements Localize.

  5. Plural arms. A plural selector has an arm for every category the locale’s rules select for the operand’s type, except other, which * covers: for an Int, English needs one, and Polish one, few and many. An English-shaped Polish text is pl: `cart_items` has no `few` arm; 2, 3 and 4 select `few` in Polish. A key that is not one of the locale’s categories, or a number, is an error. A Float selects no plural category, since its category depends on the digits it shows, which a Decimal keeps.

  6. Enum selectors. A :string selector over an enum has an arm for each variant and no other key, as case does: en: `m` has no `Pending` arm; `.match $s` needs an arm for every variant of `Status` .

  7. Freshness. An entry’s source is the declaration’s current text, compared as MF2 data models, so layout and declaration order do not count. A stale entry in locales is an error:

    pl: `cart_items` was translated from an older English text
      was: {$count :integer} items
      now: {$count :integer} items in your cart
    help: update the translation, then accept it with the quick fix or `nomi phrases accept pl cart_items`
    

    In partial_locales a stale entry counts as missing, so the phrase shows in the source locale, never in a translation of an old meaning.

  8. MF2 validity, including MF2’s required variant whose keys are all *, kept even where the other arms cover every value, so catalogs stay valid for other MF2 tools.

  9. Agreement. Every noun has a translation in every listed locale, as a phrase does, with its source and no text. Its entry has a gender exactly when the language’s nouns have one, and it is one CLDR lists (pl: `masculine` is not a gender in Polish). Every other key is a case of the language (pl: `genetive` is not a case in Polish, nor a key of a noun's entry), the nominative is present, and each form has the plural arms the locale needs. A case= option names a case of the language (en: `genitive` is not a case in English). Over the whole program, every noun has each form some phrase in the locale asks for (pl: `laptop` has no `genitive` form, which `sold_out` asks for, at the noun’s entry), and each gender selector has an arm for every gender some noun has there, naming the noun (pl: `has_shipped` has no `personal` arm; the noun `staff.courier` is personal in Polish). A gender selector in a language with no genders is en: English nouns have no grammatical gender, so `has_shipped` cannot select on `$product`'s.

Taught in Building & Shipping.

An embed declaration names files a program carries inside itself:

[pub] embed name `pattern ...`

The compiler finds the files the patterns match when it compiles the program, and records each one’s size and SHA-256, and name is a value of std::embed’s Files, a read-only tree of them (std::embed). It is read like a once value (site, web.site from another file). A program reaches an embedded file only through the declaration that names it, and a built image holds the files of the declarations the program reaches.

When a file is read. The tree, each file’s path, size and SHA-256, is in the program from the start: paths, list, walk, metadata, exists, sum and sub read no file. A file’s contents are read when the program reads that file (read, read_text), each time it does, and are kept only as long as the program keeps the Bytes. A built program holds the contents in its image, after the code it starts from, so nomi build’s executable, its WebAssembly modules and a .nomic read no file but their own, and starting one costs the same however much it embeds. nomi run, nomi test and the REPL read a file’s contents from the file, and a file whose size or SHA-256 is not what the program was compiled with stops the program with an error naming the file (static/a.css changed after the program was compiled); the next run compiles the new contents. A build checks each file the same way when it writes it into the image.

import std::embed.Files

/// The site's pages and styles.
pub embed site `
    static
    templates/*.html
    `

fn home() -> String
    Files.read_text(site, "static/index.html")!
end

The body is one or more patterns, separated by white space; a pattern that holds a space is written in double quotes ("my notes.txt"). A pattern is Go’s path.Match pattern (*, ?, [a-z]), slash-separated, and names files from the module root, as an import path names a file (§14 Files and modules), whatever directory the declaring file is in, so moving the file never changes what its patterns name. It never reaches outside the module. The other rules are Go’s //go:embed’s:

  • A pattern that matches a file embeds it, whatever its name. One that matches a directory embeds every file under it, except names that start with . or _; a pattern that starts with all: embeds those too (all:static).
  • A directory holding a nomi.toml of its own is another module: a directory walk leaves it out, and a pattern that names it, or a file under it, is an error.
  • A path in the tree is the file’s path from the module root (static/index.html), whatever pattern matched it, and two patterns that match one file embed it once.
  • A pattern whose base does not exist, from the module root or from the declaring file’s directory, is a warning rather than an error, except in a build. The base is the path its names spell before the first one holding a wildcard, the whole pattern when none does: web/dist for web/dist and for web/dist/*.js. The tree holds the base as an empty directory, so Files.sub(site, "web/dist") is an empty tree, and a read under it returns NotFound. This is the state of a frontend’s build folder before its first build: nomi run, nomi check, nomi test, the REPL and the language server report the `embed` pattern `web/dist` matches no file: `web/dist` does not exist, so `site` is empty until it does at the pattern and go on, and nomi build refuses it, for every target, so a built program holds the files its patterns name. A pattern that matches nothing in a base that exists (static/*.png in a static with no .png) is an error everywhere.
ViolationError, at the pattern
A pattern that matches nothing, in a base that exists, or in any base in a buildthe `embed` pattern `static/*.png` matches no file
A leading or trailing /the `embed` pattern `/static` starts with `/`
A . or .. name, or an empty onethe `embed` pattern `../x` names `..`
**the `embed` pattern `static/**` holds `**` : a directory’s name already embeds everything under it
A \the `embed` pattern `static\a` holds `\`
A malformed patternthe `embed` pattern `static/[a` is not a valid pattern: a `[` is not closed, or a `\` ends it
A directory with nothing to embedcannot embed `empty`: it holds no file to embed
A symbolic link or other irregular filecannot embed `link.html`: it is a symbolic link
Another module’s directorycannot embed `tools`: it is another module, with its own nomi.toml
No body, parameters or a result typean `embed` names the files it holds

Literal paths are checked. A call to Files.read, read_text, metadata, list, walk or sub whose path is a string literal, and whose tree is an embed declaration (site, web.site) or a Files.sub of one with a literal directory, unwrapped with ! or ? (Files.sub(site, "static")!, nested or piped), is checked against the files the declaration holds. read and read_text name a file, list, walk and sub a directory, and metadata either. The path is cleaned as the run time cleans it, so ./static//a.css is static/a.css. A path built at run time (an interpolation, a variable, a parameter) is not checked and stays a run-time Result, and neither exists nor paths is checked. A literal at or under the base of a pattern whose base does not exist is not checked either, since its files are not there to check it against; the build refuses the pattern itself.

ViolationError, at the literal
No such file`static/indx.html` is not embedded in `site`, with did you mean `static/index.html`? when one path is close
A directory where a file is read`static` is a directory in `site`, not a file
No such directory`public` is not an embedded directory of `site`
A file where a directory is read`page.html` is a file in `site`, not a directory
A path under a Files.sub`index.htm` is not embedded in `static` of `site`
A leading /`/a.css` is not an embedded path: an embedded path is relative to the root of the embedded tree
.. out of the tree`../a.css` is not an embedded path: the path leaves the embedded tree

Nomi differs from Go in five things: a pattern names files from the module root, where Go’s names them from the declaring file’s directory; ** is an error rather than a pattern matching like *, since naming a directory embeds its whole tree; \ is an error rather than an escape, so a pattern reads the same on every system; a quoted pattern takes no escapes; and a file’s modification time is the Unix epoch, since an Instant cannot hold Go’s zero time.