18. Typed literals and keyword declarations
Typed literals
Section titled “Typed literals”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.
The Literal interface
Section titled “The Literal interface”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
Section titled “The prefix”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
Literalimpl istype '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 notI, 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.
Desugaring
Section titled “Desugaring”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 thatT.Date"2026-05-04"is aDateandRegex`\d+`is aRegex<Unit>; neither needs a?, andonce 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’sDisplay, or itsDebugwhen 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.
Checked literals
Section titled “Checked literals”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:
checkruns while the program is checked, once per literal, on the literal’s static text: then + 1pieces around itsnslots, in order, empty ones included. It follows the rules of a handler run at compile time: acheckthat 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 ischeck. 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). ARoute<{id: Uuid}>literal gets["{id: Uuid}"], aUrlliteral[]. 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, writescheck_type; it followscheck’s rules, and an effect in it is reported asRoute.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 aRegexliteral’s captures do: with no expected type, or one that leavesPopen once the arguments that solve it on their own are checked (§18 Literals typed by their position),Route"GET /users/{id}"is aRoute<{id: String}>, aStringfield per wildcard ({rest...}included), and a route with none is aRoute<Unit>. Itscheck_typeholds the wildcards toP’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 toParseandDisplay: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 carryingmessageat the characteroffsetcode points into staticfragment, counted in the text ascheckreceived 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. buildruns when the program runs, gets the fragmentsfrom_fragmentswould get, and cannot fail: oncecheckaccepts the text, every slot value must build. Abuildthat 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.
Literals typed by their position
Section titled “Literals typed by their position”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,
checkruns 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
Stringvalue where aUrlis 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 aRoute<{id: Int}>, and so doesRoute.to_with("PATCH /todos/{id}", auth(update))with a middlewarefn 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
CheckedLiteralimpl, the literal is aString, as always. ALiteralimpl does not make a literal typed by its position, since such a literal is its handler’s result, usually aResultbuilt when the program runs. - The literal keeps the form it was written in;
nomi fmtdoes not add or remove a tag.
Coherence
Section titled “Coherence”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.
HTML templates
Section titled “HTML templates”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 & Co <span class='badge'>2</span></p>
<p><b>hi</b></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:
| Context | Example | The value must be | Written as |
|---|---|---|---|
| Element content | <p>${x}</p> | ToHtml, or another Display | a 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 one | escaped text; an Html is refused, since its markup could end the element |
| Quoted attribute value | class='a ${c}', data-reaction="${kind}" | Display, or a Maybe of one | escaped for an attribute: &, <, >, " and ' |
| URL attribute, the start of its value | href="${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 text | href="/posts/${id}", ?q=${q}, #${f} | Display, or a Maybe of one | percent-encoded as a path segment (/ and : included), a query value or a fragment, then escaped |
style attribute | style="width: ${pct}%" | CssValue (Int, Float, Decimal, Css, a Maybe of one) | a number as written; a Css as it is; escaped |
| A whole unquoted value | checked=${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:
| Where | Error |
|---|---|
| A tag or attribute name | a slot cannot name a tag or an attribute: `<${tag}>` |
| Part of an unquoted value | quote the attribute's value to put a slot in it: `class="...${...}..."` |
An unquoted URL or style value | quote `href`'s value to put a slot in it: `href="${...}"` |
| An event handler attribute | a 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 comment | a slot in an HTML comment is not rendered safely |
In srcset | a slot in `srcset` is not supported; build the attribute from `SafeUrl` values |
| A URL’s scheme or host | a 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.
Keyword declarations
Section titled “Keyword declarations”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.
| Violation | Error |
|---|---|
| Another keyword | unknown declaration keyword `database` |
message | unknown declaration keyword `message` , with a help naming phrase |
| A type name as the name | the 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 body | a `phrase` body is MessageFormat 2 text and takes no tag: remove `Mf2` |
A result type on a phrase | a `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).
Phrases
Section titled “Phrases”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}} `
The declaration
Section titled “The declaration”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,:timeand:datetimeselect nothing:en: `:date` writes a calendar value and selects nothing, whose help points to:nomi:weekday. :nomi:weekdayonly selects. A selector that names one day needs all seven, and a placeholder that writes it isen: `:nomi:weekday` selects by the day of the week and writes nothing.- A placeholder with no function,
{$name}, writes its value withLocalize, so its type must implementLocalize(Int,Float,Decimal,StringandPhrasedo). - An enum selected or written with
:stringreads as its variant’s name (Shipped), whatever itsDebugsays. :offsetand:unitare each`:offset` is not supported yet.
Nouns and agreement
Section titled “Nouns and agreement”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.
What the compiler checks
Section titled “What the compiler checks”Taught in Translating Text.
Each check is an error at the declaration, in its text, or in the catalog entry it is about:
-
Completeness. Every phrase has text in every locale
localeslists: in that locale’s catalog, in a listed ancestor’s on its CLDR fallback chain (pt-PTmay leave out whatptsays), or because the source locale is that ancestor. A locale inpartial_localesmay leave a phrase out, and the phrase then shows in the source locale. -
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. -
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`). -
Types. Each function takes the types its row above names, and an unannotated placeholder’s type implements
Localize. -
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 anInt, English needsone, and Polishone,fewandmany. An English-shaped Polish text ispl: `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. AFloatselects no plural category, since its category depends on the digits it shows, which aDecimalkeeps. -
Enum selectors. A
:stringselector over an enum has an arm for each variant and no other key, ascasedoes:en: `m` has no `Pending` arm; `.match $s` needs an arm for every variant of `Status`. -
Freshness. An entry’s
sourceis the declaration’s current text, compared as MF2 data models, so layout and declaration order do not count. A stale entry inlocalesis 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_localesa stale entry counts as missing, so the phrase shows in the source locale, never in a translation of an old meaning. -
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. -
Agreement. Every noun has a translation in every listed locale, as a phrase does, with its
sourceand notext. Its entry has agenderexactly 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), thenominativeis present, and each form has the plural arms the locale needs. Acase=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 isen: English nouns have no grammatical gender, so `has_shipped` cannot select on `$product`'s.
Embedded files
Section titled “Embedded files”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 withall:embeds those too (all:static). - A directory holding a
nomi.tomlof 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/distforweb/distand forweb/dist/*.js. The tree holds the base as an empty directory, soFiles.sub(site, "web/dist")is an empty tree, and a read under it returnsNotFound. 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 reportthe `embed` pattern `web/dist` matches no file: `web/dist` does not exist, so `site` is empty until it doesat the pattern and go on, andnomi buildrefuses 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/*.pngin astaticwith no.png) is an error everywhere.
| Violation | Error, at the pattern |
|---|---|
| A pattern that matches nothing, in a base that exists, or in any base in a build | the `embed` pattern `static/*.png` matches no file |
A leading or trailing / | the `embed` pattern `/static` starts with `/` |
A . or .. name, or an empty one | the `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 pattern | the `embed` pattern `static/[a` is not a valid pattern: a `[` is not closed, or a `\` ends it |
| A directory with nothing to embed | cannot embed `empty`: it holds no file to embed |
| A symbolic link or other irregular file | cannot embed `link.html`: it is a symbolic link |
| Another module’s directory | cannot embed `tools`: it is another module, with its own nomi.toml |
| No body, parameters or a result type | an `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.
| Violation | Error, 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.