Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Modules and visibility

Module scope contains declarations only — every statement lives inside a function, and loading a module executes nothing. Visibility is private by default, with package-scoped forms for libraries.

Module structure

Allowed at module scope:

DeclarationSpelling
importuse pkg::{ A, B }; / use pkg::A; / use pkg::a::b::{ C }; (see below)
child modulemod name; / pub mod name; — declares a file module
bindinglet name: T = expr; (also under pub)
enum / struct / class / interfaceenum E { .. }, struct S { .. }, class C { .. }, interface I { .. }
impl blockimpl T { .. } — inherent, the type’s module only
functionfn f(..) { .. }, async fn f(..) { .. }
entry pointentry fn f(..) { .. }
aliastype X = A; (see Type aliases and union bounds)

Anything else — calls, any statement — is a compile error: statements are not allowed at module scope — modules contain declarations only.

host fn / host struct and builtin declarations are signature-only native surfaces: host rows live in declaration files (.d.rut) and builtin rows in the engine’s own core surface, never as executable bodies in .rut.

File modules (mod)

A mod NAME; declaration mounts a file module. The child has two spellings, probed beside the declaring file in order:

  1. the directory form — NAME/mod.rut (or NAME/mod.d.rut on a host surface tree);
  2. the single-file form — NAME.rut in the same directory.

Both spellings present is a loud ambiguity error naming both — the mount is undecidable until you delete one. In an implementation file there are no inline mod X { .. } blocks — files are the one mechanism. The package’s root module is mod.rut beside its manifest (Project structure); a child’s own declarations may declare grandchildren (layout/mod.rut declaring pub mod grid; mounts layout/grid/mod.rut), recursively. Mounting follows declarations in source order, cycle-guarded by file identity; a repeated name mounts once. A missing child (under both spellings) or a directory without its mod.rut is a loud error naming the spellings. Logical mod paths are unchanged by the spelling — a single-file imp.rut mounts at module path imp exactly as the imp/mod.rut directory would, so qualified positions, uses, and visibility read identically over either shape. mod versus pub mod feeds the same visibility law every declaration follows (below): a pub mod child’s pub members cross packages; a plain mod child is the package’s own.

The inline form lives in declaration files (.d.rut, wire 12): pub? mod NAME { <declarations> } nests declarations in the grammar — host-fn signatures, nested mod blocks, type declarations — no bodies, recursively. This is how a published group’s consolidated declaration entry spells its whole mod tree in ONE file (Module bundles): structure lives in the grammar, never in paths. A directory tree and its consolidated entry are two spellings of one truth — they lower to the same path-qualified rows.

Uses

use pouch::{ Vec };
use ink::Logger;

entry fn main() {
    let log = Logger("uses");
    let v = Vec<i32>::new();
    log.info(f"{v.len()}");
}
0

The use path is pkg:: followed by module segments: the head is the mounted package’s bare [a-zA-Z0-9_]+ name — or the consumer’s own package (its name, or one of its mod edges; see the intra-package import below) — then zero or more module segments walking the package’s file modules, then the leaf — a brace list of one or more names, or a single name:

use tur_kit::layout::grid::Cell;       // one name from a nested module
use tur_kit::layout::{ Column, Span }  // several names from a module
use ink::Logger;                       // the degenerate root path

Importing a module itself (use tur_kit::layout;) is an error — modules are namespaces, not values; the diagnostic names the fix (spell a name at the leaf). rut is fully statically typed: the compiler resolves every used name and knows from usage whether it lands in type position (Column in an annotation) or value position (Logger(..)), so there is nothing for the user to annotate. A use line may spell only what the target exports: a name the target doesn’t declare is rejected at the use line itself — `ink` has no `Nope` — unknown import — not later, at a call site that might never be written. An unreferenced use name is a lint, not an error.

Every leaf must bind — at the use line. Validation is total and it happens where the use was written, before any body compiles: a leaf that binds nothing in its own file is a hard error there. A name the target declares but does not export — a private row — names the fix on the exporter’s side:

`helper` is not exported by `pkga` — mark it `pub` there

(a qualified leaf names the walked module: not exported by `pkga::layout::grid`; the intra-package lane keeps its own visibility spelling, naming both files). A compiled dependency — a packed .rutbundle — carries its declarations as a binary surface with no source text, so a leaf its surface never carried states the bare law: `leaf` is not part of `pkga`'s exported surface — nothing binds in this file.

A use binds its own file. The binding a use creates is visible in the file that wrote it and nowhere else: every file of a multi-file package spells its own imports, the root’s use never feeds a child module’s file, and a sibling’s never feeds its sibling’s. There is no ambient fallback beyond the engine’s own names (the builtins below); beyond them, a bare dep name resolves in a file iff that file’s own use bound it, and a miss at the call site says exactly which fix applies — the name rides another file’s use:

`fetch` is bound by a `use` in the root module — write the `use` in this file

(intra-package bindings add where that file imported it from), or the name is a mounted export no use spells at all:

`dup` is not bound — no `use` statement names it

One name, one leaf, per file. The duplicate-name law is NAME-level, not package-level: a leaf name spelled by more than one use leaf in the same file — whatever the heads, including twice within one list — errors at the second spelling, citing the first:

use pkga::{ x };
use pkgb::{ x };
// duplicate name `x` — `use pkga::{ x }` (mod.rut) already binds it in this file

use pkga::{ x }; use pkga::{ y } is fine — the name is the rule, never the package or the list.

pub async fn crosses package surfaces. A plain pub async fn exports like any pub fn. The exporter materializes the sugar law’s export shape beside the woven body — a hidden start wrapper spelling fn f(p) -> Future<T> that mints the frame — and the surface row carries the declared answer type. The consumer’s use binds the name, a call answers the closed Future<answer>, and await drives it like any future: the wrapper mints the frame in the one unit that knows its full layout, and the drive reaches the exporter’s woven body through the frame’s yield slot exactly as a local call would. The one gap is the generic async fn — the weave refuses generics, no row materializes, and a use leaf naming one refuses at the use line: `grab` is a generic `pub async fn` — generic async fns do not cross package surfaces yet.

The head may also name the consumer’s own package — the intra-package import. The package’s own name resolves to its root module, and a mod edge of its own tree resolves by walking from the file the use is written in (the current module first, then the ancestors — the same walk qualified positions take):

use imp::{ TodoList, Task };   // beside `mod imp;` — imp's pub names

mod imp;

The leaves obey the same laws every crossing does. Each must be a declaration of the walked module, visible from the importing file: a bare, private member of imp is not importable — pub or pub(pkg) is (import is no visibility bypass). A module itself is not an import — walk it (use imp::grid::{ Cell }, not use imp::{ grid }). And the binding is per file, exactly like a dep use: a module needs its own use line. One head must never answer as two things: a name that is both a declared dep and an own module edge is a loud ambiguity — rename one of the two.

The head itself is declaration-scoped: a package may use exactly the heads its own manifest names — deps ∪ (dev-deps when the package is the program root) ∪ core. Mounting stays transitive (a dep’s own deps still join the program’s closure), but a head that is mounted without being declared by this package is the resolver’s dedicated diagnostic, naming who pulled it in and the row to add (dependency kinds).

The engine’s builtin names — the primitives, opaque, panic, type_id<T>(), str(x) — are ambient: no use is needed for them. The gated names resolve only through use core::{ .. }: the const NAN, the disposal context DisposalContext, the weak reference Weak<T>, and the closed async pair (Future<T>, RunContext) — the engine’s weave never needs the import, only source that spells one of the names does. The bracket markers ([disposal]/[iterable]/[constructor]) need no import — the marker word is the designation, not a name (Host fns and declaration files). Package code (pouch, ink, nmapset, …) mounts only through use.

Qualified positions

Inside one package, a declaration of another module is nameable where a path is legal — a type annotation, a call, a field read — by qualified position: layout::Column, store::Source<str>, widget::mk(3). The head resolves against the current module’s scope, then the module’s ancestors up to the package root; positions never take a dep package head — use statements are the only cross-package door. use is also the intra-package import — a use head may be this package’s own name, or one of its mod edges (see Uses) — so a cross-file name binds bare once imported; positions stay spelling-free: imp::grid::Cell never needed an import, and still spells. :: is THE path separator — every name-resolution path (use paths, qualified positions, enum members, statics/associated fns, extern namespaces) spells its segments with it; . is value access only (fields, instance methods, tuple indices — see Lexical structure). One separator, two doors:

formspellingdoor
use pathuse pkg::a::b::{ C }:: — cross-package and own-package module, the import
qualified positiona::b::C / a::b::f(..):: — intra-package, at the use site

Module-level let

Initializers must be load-time expressions: literals, enum members, builtin operators over load-time expressions, struct literals whose fields are load-time expressions, fixed-array literals whose elements are, type_id<T>(), and builtin zero allocations ([nil; n] with a const n). Calls to user functions are not load-time expressions.

let KIND_ADD: i64 = 1;
let ORIGIN = Point { x: 0, y: 0 };

There is no mutable module state: program state is constructed in main, or held by the embedder and passed across the boundary. No user code runs at load.

Entry points

The embedder loads a module and then explicitly calls an entry function — entry fn main for a script, sync or async. entry fn publishes a function to the embedder; entry is orthogonal to visibility and does not combine with pub. Consequences of declarations-only loading: no use side-effect ordering, no load-order bugs, deterministic and cheap loads.

Bindings: let vs let mut

  • let x = e; binds immutably — no reassignment, no field assignment through x, and no mut self method calls on it. It is a read-only view of the shared object.
  • let mut x = e; may be reassigned and grants write access to the object it holds. Every non-primitive is a shared cell (see By-reference and nullable), so that write is visible through every other handle: mut is permission, never a copy. Every assignment path must run through a mut binding.
  • Parameters may declare mut name — the callee’s permission to mutate the caller’s object: fn step(mut p: Point) moves the caller’s point; fn area(p: Point) promises not to.

Visibility

Modules form a tree per package (the package root is the root module mod.rut; each declared child is a module file). Every declaration — and every class member — carries a visibility:

FormMeaning
pub fn ..public — nameable by any rut module (other packages included)
pub(pkg) fn ..visible everywhere inside this package (its whole module tree)
pub(super) fn ..visible to the parent module’s subtree only
(unannotated)module-private — visible in this module and its descendants; the default
  • Unannotated = private to the declaring module and its descendants (a child module sees its ancestors’ privates, never a sibling’s).
  • The paren forms pub(mod) / pub(self) are repealed — they parsed but gated nothing; the parser refuses them with the fix (bare private, or pub(super)/pub(pkg)/pub).
  • Applies uniformly: let, enum, struct, class, interface, impl (an impl exports with its target type), fn, type aliases, and the mod edge itself (pub mod opens the child’s pub members to other packages; a plain mod keeps the child package-internal). On a class declaration it means the type name is visible.
  • Class members take the same forms: an unannotated field or method is module-private; pub (optionally scoped) exposes it. See Classes and constructors.
  • Struct fields are always public — the field law has no dial (see Structs). Impl-block methods take the pub dial — pub fn exports cross-module, plain fn is module-private — the same law a class’s methods follow, enums included (see Structs and Enums). Interface members take no pub at all — they are as visible as their interface; satisfaction reads a type’s public inherent members (see Interfaces and dispatch).
  • Visibility is checked at compile time; it has no runtime representation. Only pub names enter a module’s export table; a non-exported declaration is known inside its module but nameable nowhere else — which is how libraries hide implementation surfaces behind exported ones. Hiding stops at the checker’s door: every non-generic, non-async fn/method body is type-checked even when nothing calls it.