Skip to content

14. Files, modules and imports

Taught in Modules & Imports.

A file is one .nomi source file. It is the unit of import, scope and visibility. A Nomi module is the directory tree rooted at a nomi.toml, with a go.mod when it is distributed. It is what ships together, and it is the unit the orphan rule (§12) checks. Projects, nomi.toml and dependencies are in the tooling reference.

A file’s import path is its path from the module root, without .nomi, with :: between directories. Nothing in the file declares it, so renaming the file renames the path.

FileImport path
users.nomiusers
users/helpers.nomiusers::helpers
http/request.nomihttp::request

File names are snake_case. A file cannot be reopened or split across files. Importing http does not import http::request: a file is imported on its own, or reached through an import of a directory above it (Directory imports below).

A file API object is the qualifier a path-only import binds: import http::request binds request, and request.get(...) calls its pub fn get. Inside a file, the last segment of its own path is also that file’s qualifier when no top-level declaration of the file has that name: users.nomi may call its own pub fn new as users.new(...). In main.nomi, fn main owns the name, so there is no main qualifier.

Import paths across modules. Within a module, a path names a file of that module. A file may also start the path with its own module’s short name, the name in its nomi.toml (import my_app::models::user inside my_app). A path into another module starts with that module’s short name: import sqlite::driver names driver.nomi at the root of module sqlite. An import that is a short name alone is an ordinary path inside its own module: inside sqlite, import sqlite names sqlite.nomi at the root, and with no such file and no directory sqlite/, the module’s root directory (Directory imports below). From another module, a dependency’s short name alone names the file of that name at the dependency’s root, so import sqlite is import sqlite::sqlite when the module holds sqlite.nomi, and binds sqlite either way. A dependency’s name wins over a file of the same name in the importing module. A module with no such file is its root directory under its short name alone: import sqlite, then sqlite::driver.open(path). A file inside an internal/ directory can be imported only by files under that directory’s parent: import a::internal::x from main.nomi at the root is the error cannot import "a::internal::x" from "main": outside the parent subtree of a/internal/.

Taught in Modules & Imports.

Import paths separate segments with ::, written with no space around it. An import takes one of these forms:

FormBinds
import http::requestthe file API object request
import http::request as reqthe file API object, renamed req
import views::adminthe directory admin, when views/admin/ holds no file of that name (Directory imports)
import task_parser.parsethe exported item parse, bare
import std::maybe.Maybe.Some as Justan item, renamed
import users.{User, Role}each listed item
import std::io.{self, print}self binds the file API object io, beside print
import shape.Shape.{Circle, Square}variants selected through their enum
import std::calendar.Disambiguation.{self, Earlier}self binds the owner type Disambiguation, beside the variant

Several imports may be written as one block, one entry per line, with no commas:

import
    std::io.{self, print}
    std::maybe.Maybe.{None as Nothing, Some as Just}
    http::request
end

The rules:

  • X.Y after an import names a member of X, never a file: import utils::inner.Thing needs utils/inner.nomi, and does not look inside utils.nomi. A top-level function imported this way is called bare; a file imported path-only is reached through its qualifier.
  • Between the path and the selected names, only PascalCase segments are owners, since an owner is a type. A lowercase segment after a dot with more after it is a path segment, so import std.io.print is import std::io.print.
  • A / between segments is an error that spells the path with ::: import std/io is import paths use `::`: write `std::io`. A :: with a space on either side joins nothing, and is the error `::` joins the lowercase segments of a file's path, with no space around it, as in `std::io` or `db::posts.post_by_id`.
  • Braces select names from one file; a path cannot be grouped. import std::{io, regex.Regex} is the error braces select names from one file, as in `std::regex.{Regex, Match}`.
  • A selector list cannot hold another: import shapes.{self, Shape.{Circle, Square}} is the error a selector list cannot hold another list. Write shapes and shapes.Shape.{Circle, Square} as two entries of a block.
  • A variant is imported through its enum. import shape.Circle is the error cannot import variant 'Circle' directly — use 'import shape.Shape.{Circle}' to lift specific variants, or 'import shape.{Shape}' and qualify as 'Shape.Circle'.
  • There is no glob import (import path.*).
  • Standard library files start with std::: import std::io. A module that helps test another is nested in that module’s directory as testing: import std::fs::testing binds testing, beside import std::fs, which binds fs. std alone names the standard library’s root directory: import std binds it, and std::io.print(x) reaches io.nomi (Directory imports). A directory has no members to select, so import std.io is the error `std` is a module, not a file; an import names a file in it, with the hint did you mean `import std::io`?.

Two imports that bind one name to two declarations are an error at the second: import a.{Thing} then import b.{Thing} is 'Thing' is already imported on line 1 from another file; two imports cannot bind one name, with the hint to import one under another name (Thing as OtherThing). Importing the same declaration twice is an unused import.

A top-level declaration may not share a name with an imported item: import other.helper beside fn helper is 'helper' is already defined in this scope as a function. A file or directory import’s name follows the same rule, with its own message; see Short names below.

Taught in Modules & Imports.

A path-only import binds one name, its short name: the last segment of its path or its as alias. import db::posts binds posts, and posts.post_by_id(1) calls the file’s pub fn post_by_id. The import’s path is not a name at a use: after import db::posts, db::posts.post_by_id(1) is the error `db::posts` is not a name in this file: `import db::posts` binds the file as `posts`, with the hint write `posts.post_by_id`, or import its directory (`import db`) and keep `db::posts.post_by_id`. The editor’s quick fix, and its source.fixAll, write the short name. A path at a use starts with the name a directory import binds (Directory imports below); any other path is the error `views::admin::reports` is not imported, whose hint names the file import and the directory import that would reach the file.

  • Two imports may not bind one name. import db::notifications beside import jobs::notifications is the error at the second, 'notifications' is already imported on line 1 from db::notifications; two imports cannot bind one name, with the hint import the directories (`import db` and `import jobs`) and write `db::notifications` and `jobs::notifications`, or import one under another name with `as`. A file and a directory of one name are the same error. The same file imported twice is an unused import. Two std modules nested under their parents (std::fs::testing and std::process::testing) have no directory to import, since std::fs is a file, so the hint renames one after its parent: import one under another name, as in `import std::process::testing as process_testing`.
  • A declaration keeps its name. A top-level declaration of the file named like an import’s short name is what the name means, and the import is the error 'users' is already defined in this scope as a function on line 3, so `import views::admin::users` cannot bind it, with the hint import its directory (`import views::admin`) and write `admin::users`, or import it under another name with `as`. A file at the module root is reached through the module’s root: import my_app, then my_app::users.
  • A local keeps its name. A local, a parameter or a pattern binding named like an import’s short name wins in its scope, and name.member there reads the local. When a member access on it fails and the file imports a file of that short name, the error’s hint says how to reach the file: schema.post(1) where schema is a local and db::schema is imported is Int has no field 'post', with the hint `schema` here is the binding on line 4, not the file db::schema; import its directory (`import db`) and write `db::schema.post`, or import the file under another name with `as`.
  • An import that binds nothing, since another import or a declaration holds its name, is that error alone and not also an unused import.
  • An alias is a short name. import jobs::mail as notifications binds the file as notifications only.

Prefer the short name. Where it is ambiguous or taken, import the directory and write dir::file; alias a file where a directory import does not help (Writing Nomi: Imports).

Taught in Modules & Imports.

A path-only import whose path names a directory and no file binds the directory under its short name: import views::admin binds admin when views/admin/ exists and views/admin.nomi does not. A path written below the name at a use reaches a file under the directory: admin::users.index(rows) calls pub fn index of views/admin/users.nomi, and admin::reports::daily.show() a function of views/admin/reports/daily.nomi. A directory import is how a file reaches several files under one directory with one import line.

import views::admin

fn page(rows: List<admin::users.Row>) -> String
    "${admin::users.index(rows)}${admin::reports::daily.show()}"
end
  • Every position. A path at a use stands wherever a file’s short name does: a call (admin::users.index(rows)), a type (admin::users.Row, std::http.Response<Int>), a pattern (db::schema.Kind.Draft, db::schema.Post{id:, title:}), a struct literal (db::schema.Post{id: 1, title: "x"}), an owner function (db::schema.Post.blank()) and a variant (db::schema.Kind.Published(4)). Its last segment names a file and the segments between name directories. Like a short name, a path alone is not a value: `admin::users` is a file, not a value; name one of its members, as in `admin::users.name`.
  • The directory’s name is not a file. admin.users is the error `admin` is a directory, not a file, with the hint reach a file in it with `::`, as in `admin::users.name`, and admin alone is `admin` is a directory, not a value.
  • A path that names no file is an error at the use that says what is there: admin::user.render(u) is `admin::user` names no file: views::admin has no user.nomi, with the hint did you mean `admin::users`?, or a list of the directory’s files and directories when no name is close. A path that names a directory, admin::reports.total(), is `admin::reports` is a directory, not a file, whose hint names a file in it.
  • Only the files a path reaches are part of the program. Importing a directory loads no file under it. Each path the import’s scope writes below the name loads the file it names, as an import of that file would, and the file’s impls come with it. A directory import through which no path reaches a file is unused: imported directory 'admin' is unused — remove the import.
  • A file wins over a directory of its name. Where views/admin.nomi sits beside views/admin/, import views::admin names the file, since a parent file beside the directory of its children is the usual layout (Cyclic imports below). The directory is reached from its parent: import views, then views::admin::users.index(rows).
  • Module roots. A module’s own name alone names its root directory when the root holds no file and no directory of that name: inside module my_app, import my_app binds the root, and my_app::users.count() reaches users.nomi there. A dependency’s name alone is its root in the same way when the dependency has no file of its name (Files and modules above), and import std binds the standard library’s root: std::io.print(x). A path through std reaches an internal std module no more than an import does: `std::phrase::format` is internal to std::phrase.
  • Another module’s directory. A directory that holds its own nomi.toml is another module’s root, which no path of this module reaches. import plugins::billing is the error `plugins::billing` is another module's directory: it holds a nomi.toml, whose hint says to add the module with nomi add and import it by its name, and a path through it at a use is `plugins::billing::pay` is in another module's directory: plugins/billing/ holds a nomi.toml. A path into an internal/ directory from outside its parent’s subtree is the error an import of that file is (Files and modules above).
  • Scope. The directory’s name is a short name like a file’s (Short names above): an alias renames it (import views::admin as pages, then pages::users.index(rows)), an import at the top of a block binds it in that block only, and a local, a parameter or a pattern binding of the name wins in its scope, where a path through the name is the error `admin` here is the parameter on line 3, not the directory views::admin.

Placement. Imports come first: at the top of a file, before any declaration, and at the top of a block, before any other statement. An import after a declaration is the error imports must appear at the top of the file — 'std::io' came after another statement, and one after a statement in a block is imports must appear at the top of this block — 'std::io' came after another statement.

An import inside a function body binds its names in that block only, and shadows a file-level binding of the same name. It costs nothing per call.

import std::io

fn main()
    import std::io.print

    print("bare")
    io.print("qualified")
end

Every file outside the standard library starts with the imports in std/prelude.nomi, an ordinary file that holds one pub import block. It brings in:

  • the primitive and collection types Int, Float, Decimal, String, Unit, Infallible, Byte, Bytes, Codepoint, List, Vector, Map, Set and Range, and Bool with its variants True and False;
  • Maybe with Some and None, and Result with Ok and Err;
  • std’s subtypes of the primitive and collection types (§4 Subtypes): NonZeroInt, NonNegativeInt and PositiveInt, the same three for Float and Decimal (NonZeroFloat, PositiveDecimal), NonEmptyString, NonEmptyList, NonEmptyVector, NonEmptyMap, NonEmptySet, and NonEmptyRange, ClosedRange and BoundedRange;
  • the interfaces Add, Subtract, Multiply, Divide, Remainder, BitwiseAnd, BitwiseOr, BitwiseXor, BitwiseNot, ShiftLeft, ShiftRight, Averageable, Comparable, Contains, Debug, Discrete, Display, Distinct, Equatable, Hashable, Iter, Productable, Steppable, Struct, Summable and Variants, From (§11 Propagating with ?) and TryFrom (§12 TryFrom), and Release and Commit (§9 Releasing resources);
  • Ordering, Type, Startup and Context;
  • Locale (std::locale), and Phrase and Noun (§18 Phrases), so formatting a phrase needs no import.

What it leaves out:

  • File API objects. String is in scope but strings is not, so String.uppercase(s) needs no import and io.print needs import std::io.
  • Bare functions. The prelude binds types, interfaces and variants only.
  • Ordering’s variants. Code writes Ordering.Less or .Less.
  • Literal and Fragment (§18 Typed literals) and assertion types such as Assertable and AssertionFailure. Code that names them imports them.

Owner functions on a prelude type need no import (Iter.map, Map.get, Result.is_ok). An owner function on another type needs that type imported (import std::assertions.AssertionFailure for AssertionFailure.format).

Standard library files do not get the prelude; each imports what it uses. A std file’s //! prompts (§17 Attached tests) see the file’s scope, so a prompt that writes a bare False needs the file to import it.

The standard library’s modules and their contents are in the standard library reference.

Taught in Modules & Imports.

Files may import each other in a cycle. Names resolve across the whole program, so the order of imports and declarations never matters. A parent file may import a child and the child the parent:

http.nomi           // imports http/request; declares HttpRequest
http/request.nomi   // imports http.HttpRequest

A once whose initializer reads its own value is a compile error at its declaration, cyclic 'once' binding: `a` depends on itself: it reads `once a` (main.nomi:1). A cycle closed through a function value traps when the read re-enters (§6 once Bindings).

An import path that names no file is an error at the path, in every import form, whether or not the file uses the import:

CaseError
No such fileno module `lib`: no file lib.nomi in this file's directory
No such file in a directoryno module `utils::inner`: no file inner.nomi in utils/
No such std moduleno module `std::nosuch`: the standard library has no nosuch.nomi
No file, no directory, and no require in go.modno module `csvdata`: no file csvdata.nomi in this file's directory, and go.mod has no `require` line for `csvdata`
A replace with no requirego.mod replaces `csvdata` with ../csvdata but does not require it; run `nomi add ../csvdata`
A required module with no nomi.tomlno module `csvdata`: go.mod replaces `csvdata` with ./generators/csvdata, which has no nomi.toml

A hint names a sibling file the path misspells (did you mean 'helpers'?), or, for an import that selects names from a path that is a directory, a file inside it (`sub` is a directory; import a file in it, such as `sub::inner`). When go.mod requires a module the Go module cache does not hold, the hint says to run nomi fetch. When the first name is neither a file nor a directory and go.mod does not require it, the hint says to run nomi add, with the directory when exactly one directory under the project root (at most three levels down) or beside it holds a Nomi module of that name (run `nomi add ../csvdata` to add the module in that directory), and with a module path or directory otherwise.

A selected name the file does not export is an error at the name: file 'std::io' has no exported name 'nosuchname'.

A name is in scope only through an import, so a std type or module used without one is the ordinary error for an unbound name, with a help naming the import. Method.Post is undefined type or variant 'Method' with help: import `std::http.Method` , c: Catalog is unknown type "Catalog" with help: import `std::phrase.Catalog` , and io.print("x") is undefined variable 'io' with help: import `std::io` . A type name two or three std modules export lists each import (help: import `std::mail.Message` or `std::websocket.Message` ); one that more export names none. The help never names an internal std module.

An imported item that nothing in the file uses is an error. There are no warnings in Nomi. The unit is the item: in import std::calendar.{Days, Months} with Months unused, the error is at Months, imported name 'Months' is unused — remove it from the import. An unused file import is imported module 'io' is unused — remove the import, and an unused directory import imported directory 'admin' is unused — remove the import.

  • An aliased item is used through its alias.
  • self in a brace list is its own item, used when the name it binds is used.
  • Any reference that resolves to the imported name is a use: an expression, a pattern, a type annotation, an impl header, a where bound, a derive declaration, and a typed literal’s prefix (Date"..." uses Date).
  • An item re-exported with pub import is used.
  • A name in a comment or a doc-comment example is not a use.
  • A dot-shorthand pattern (.Some(v)) resolves through the scrutinee’s type, so it does not use a variant import.

An import of a whole project file also brings that file’s impl blocks into the program (§12 Foreign Types). It is used when the program uses one of those impls, even if nothing names the file: a call that resolves to one of its functions, or a conformance the program needs of the type and interface it implements (a where bound, an interface-typed parameter, an operator, an interpolation). The use may be anywhere in the program. Two impls do not count: one for a type the imported file declares, since a value of that type already needs another import of the file, and a call from inside the file to its own impl. A standard library file is never used this way, since std’s impls are always in the program.

Importing a name the prelude already binds is an error at the item, even when the item is used: import std::iter.Iter is imported name 'Iter' is already in scope from the prelude — remove it from the import. A self under a prelude type (import std::maybe.Maybe.{self, None}) is the same error. The rule follows from prelude.nomi and applies only where the prelude is in scope, so standard library files are exempt.

These are not re-imports:

  • a whole-file import (import std::strings), since the prelude binds no file API object;
  • an aliased item (import std::iter.Iter as It), which binds a new name;
  • a selection below what the prelude binds (import std::comparable.Ordering.{Less} binds bare Less);
  • a same-named item of another module, since identity is the resolved declaration, not the spelling.

Taught in Modules & Imports.

A top-level declaration is private to its file unless it carries pub. Other files reach a pub declaration through the file’s qualifier (io.print(...), io.Error.NotFound{...}) or by importing it by name. Inside the declaring file, its declarations are bare.

pub struct Config
    host: String
    port: Int
end

pub fn parse(s: String) -> Result<Config, String>
    ...
end

fn validate(c: Config) -> Bool
    ...
end // private to this file
  • Placement. pub is the first modifier: pub [opaque] <keyword> <name> ....
  • What takes pub. fn, struct, enum, type, interface, typealias, once, host fn, host type, and import (a re-export, Re-exporting imported names below).
  • What does not. Interface impl functions, struct fields and enum variants take their owner’s visibility. A declaration inside a body (a function’s, a lambda’s, a test’s, a once initializer’s) is local to that body, and pub there is the error `pub` applies to top-level declarations only. An export fn (§7 Exported Functions) is callable from outside the program, which is a different thing; pub export fn is the error an exported function takes no `pub`: write `export fn`.
  • A file qualifier is not a value. io alone, as a statement, a binding’s value or an argument, is the error `io` is a file, not a value.
  • File API is top-level functions. A file’s pub fn and pub host fn are reached through its qualifier (users.find(...)). A function or once declared in an impl block is reached through its owner (Duration.seconds(1), Display.to_string(n)). A file-qualified spelling of one, duration.seconds(1), is the error file 'duration' has no member 'seconds', whose hint names the owner.
  • Private names are invisible to other files. No other file can name a private declaration in any position: a call, a type annotation or type argument, a struct literal or pattern, a variant, an interface bound or impl header. A qualified spelling is the error file 'other' has no member 'Hidden', and an import is 'Hidden' is private and cannot be imported.
  • A file’s partner test reads its private declarations. A file named as another file in the same directory with _test before .nomi (shapes_test.nomi for shapes.nomi) is that file’s partner test, whether or not it declares tests. It may import and name every top-level declaration of its partner as if it were pub, and is inside the partner’s opaque types, so it can construct, destructure and read them. It still imports what it uses, and it publishes none of it: a file importing from shapes_test reaches only shapes_test’s own pub declarations. Any other file, a _test file named after no sibling included, gets the errors above. A test of a private function goes in the partner test file, and the function stays private. A partner test may also derive an interface, or write an impl, for its partner’s types (§12 Derive); the impl is the test file’s own.
// shapes.nomi
struct Shape
    size: Int
end

fn area(shape: Shape) -> Int
    shape.size * shape.size
end

// shapes_test.nomi
import shapes.{Shape, area}

test "area"
    assert area(Shape{size: 3}) == 9
end
  • A private type may still be a type argument. A file may pass its own private type to another file’s public generic (other.ident(Point{x: 1})). Only the declaring file names the type.
  • Impl functions follow the interface. If the interface is pub, other files can call an impl’s functions; if it is private, they cannot. There is no per-function pub in an impl Iface for Type block.
  • No renames at the declaration. A declaration is published under its own name. An imported item is re-exported under its local name.
  • opaque. pub opaque struct, pub opaque enum and pub opaque type Name Inner publish the type’s name and keep its construction, destructuring and field access private (§4 Opaque distinct types). opaque on anything else is an error: 'pub opaque' must be followed by 'struct', 'enum', or 'type', and on a zero-sized type cannot declare 'Marker' as opaque — zero-sized distinct types have no representation to hide.
  • Std’s internals. A std file’s private declarations, and the internal modules std::phrase::format and std::money::format, belong to std. Naming one is the error `phrase.compiled` is internal to std::phrase, or `std::money::format` is internal to std::money for an import.

A pub declaration may not expose a private type. Each of these is an error:

ExposureError
A pub fn’s parameterfunction parameter exposes private type Secret
A pub fn’s resultfunction return exposes private type Secret
A pub struct’s fieldpublic struct field exposes private type Secret
A pub enum’s embedspublic enum embed exposes private type Secret
A pub interface’s function signaturepublic interface function parameter exposes private type Secret
A pub typealiaspublic type alias exposes private type Secret
A pub once’s type, written or inferredpublic once binding exposes private type Secret
A pub once whose type is declared in a bodypublic once binding exposes private type Box, which is declared inside a body
struct Secret
    value: String
end

pub fn leak() -> Secret
    Secret{value: "x"}
end // error: function return exposes private type Secret

A pub opaque type is the exception: its representation (the inner type, its fields or its variants’ payloads) may be private, since no other file can reach the representation (§4 Opaque distinct types).

Taught in Modules & Imports.

pub import makes every item the statement selects part of the file’s public surface, under its local name: the alias when there is one, the imported name otherwise. In a block, every entry is re-exported. A file that re-exports some items and imports others privately writes an import and a pub import.

pub import
    std::bool.Bool.{self, False, True} // the type and its variants
    std::io.{print, write}
    other.{Helper as Helpr, Thing}
end
  • Items only, never a file. pub import leaf, pub import leaf as lf and a brace list whose self is the file (pub import std::io.{self, Error}) are each the error `leaf` is a file, and a file cannot be re-exported, with a hint to list the items or have importers import the file. A self after an owner type (Bool.{self, False, True}) is the type, and is re-exported like any item.
  • A file that a facade imports is not one of the facade’s items: import facade.{leaf} is the error `leaf` is a file that `facade` imports, not an item it exports; import `leaf` directly.
  • The upstream item must be public: pub import other.{private_thing} is 'private_thing' is private and cannot be imported.
  • pub import applies only to imported names. To publish a local declaration under another name, rename it or write a wrapper.

x.y and T.y must name a member the static type guarantees. A missing member is a compile error where it is written, never a run-time trap. The one exception is a value whose type is still being inferred; the check waits until inference resolves it.

  • A value of a concrete type. p.z must name a field the type declares: struct 'Point' has no field 'z'. A function of the type is not a field: where impl HasName for Person declares fn name, p.name is struct 'Person' has no field 'name', whose hint names the call Person.name(p) or HasName.name(p). A value with no fields at all is the same error, () -> Int has no field 'x'.
  • A tuple and a named tuple read their items by ordinal name: pair.first, pair.second. Reads chain left to right, so nested.second.first is (nested.second).first. An ordinal past the last item is an error that names the last (§4 Tuples), and pair.0 is the error that writes pair.first.
  • A value of interface type has no fields, since an interface declares functions only: interface 'Struct' has no field 'x'. A required value is read through a function requirement (§12 Requiring a Value), qualified by the interface: n.name is interface 'HasName' has no field 'name' even when HasName declares fn name.
  • A value of type-parameter type has no fields, bounded or not: type parameter `T` has no field 'name'. Call the bound’s function, T.name(x).
  • A type qualifier must name a real member: an inherent or interface function, a once, or a variant. List.empty() is type 'List' has no member 'empty', and Maybe.Bogus is type 'Maybe' has no member 'Bogus'. empty or new on Map, Set or Vector adds a hint naming the empty literal (write the empty map as {}). Members of imported types are checked the same way.

How X.Y resolves:

  1. When X is a value (a local, a parameter, a once, a local function), X.Y is field access on that value. A file of the same name is never consulted, since files are not values.
  2. When X is an imported file API object, type or interface, X.Y is a qualified name, and Y must be a public member of X.
  3. When X is a path at a use (admin::users), X.Y is a qualified name when the path’s first segment is a directory import’s name in that scope (§14 Directory imports), and an error otherwise.