Skip to content

Imports

Bring names or module namespaces into an Atoll source file.

An import makes declarations from another module visible in one source file. A path names a module, never a filesystem location. It is written bare, with / between segments, and can be spelled in three ways.

Every example below is a file of this project:

ledger/
  atoll.toml            module = "example.dev/ledger"
  main.at               module  example.dev/ledger
  money/
    amount.at           module  example.dev/ledger/money   — Money, usd, total, with_tax
  report/
    format.at           module  example.dev/ledger/report  — Line, render, line
  audit/
    format.at           module  example.dev/ledger/audit   — Line, render, line

report and audit deliberately export the same two names; that collision is the subject of Collisions. The project is in the repository at book/projects/ledger, and each listing below is checked as the file of it that it is, with what atoll prints for it.

Named imports

A named import puts selected declarations directly into local scope.

import example.dev/ledger/money.{usd, with_tax}
import example.dev/ledger/report.{Line, render}

fn main() int {
    due := with_tax(usd(19, 99))
    println(render(Line { label: "invoice", amount: due }))
    return due.dollars()
}
$ atoll run ledger/main.at
invoice: $21
atoll run: `main` returned 21

The names follow the path, as a member follows its value, and as renames one. This is also the form a view’s portable elements are named in, import ui.{View, Text}.

import example.dev/ledger/money.{usd, with_tax}
import example.dev/ledger/report.{Line, render as render_line}

fn main() int {
    due := with_tax(usd(19, 99))
    println(render_line(Line { label: "invoice", amount: due }))
    return due.dollars()
}
$ atoll run ledger/main.at
invoice: $21
atoll run: `main` returned 21

Older code writes the names first, braced or not: import { usd, with_tax } from example.dev/ledger/money, or import usd, with_tax from example.dev/ledger/money. Both are refused (ATOLL1135) with their rewrite, which atoll fix and atoll fmt apply.

Variants

A variant in a pattern needs no import. It is resolved against the type of the value being matched, so with only import ./csv.{load}, a match load(path) can have the arm Err(Missing { path }) => … — Missing is found in load’s error type, CsvError, which this file never names.

To build or raise a variant by its bare name, its enum must be in scope — imported by name, or declared in any file of this module — and an enum in scope lends its variants: with import ./csv.{load, CsvError}, error Empty and Err(Missing { path: p }) both work. The import is counted as used by them.

Through a module imported whole, a variant is named in full, in a construction and in a pattern alike: csv.CsvError.Missing { path: p }. And CsvError.Missing { path } qualifies a pattern by its enum, which is checked against the value being matched.

Renaming with as

as renames an import. The new name is local to the importing file and is not part of the declaration’s public identity:

import example.dev/ledger/money.{usd, with_tax}
import example.dev/ledger/report.{Line, render as render_line}

fn main() int {
    due := with_tax(usd(19, 99))
    println(render_line(Line { label: "invoice", amount: due }))
    return due.dollars()
}

A type renamed with as is the same type under another name — the value is still a Money, with Money’s methods:

import example.dev/ledger/money.{Money as Amount, usd}

fn twice(a Amount) Amount {
    return a.plus(a)
}

fn main() int {
    due := twice(usd(2, 50))
    println("dollars: ${due.dollars()}")
    return due.dollars()
}
$ atoll run ledger/main.at
dollars: 5
atoll run: `main` returned 5

Within one file, a type alias gives a type a second name the same way, and the two names unify in both directions:

struct Money {
    cents int

    fn dollars(&self) int {
        return self.cents / 100
    }
}

type Amount = Money

fn twice(a Amount) Amount {
    return Money { cents: a.cents * 2 }
}

fn main() int {
    a := twice(Money { cents: 1250 })
    println("dollars: ${a.dollars()}")
    return a.dollars()
}

Module namespaces

Importing a module without braces creates a namespace whose default local name is the last path segment. Reach members with dot syntax — in value position and in type position:

import example.dev/ledger/money as cash
import example.dev/ledger/report as fmt

fn subtotal(a cash.Money, b cash.Money) cash.Money {
    return a.plus(b)
}

fn main() int {
    due := cash.with_tax(subtotal(cash.usd(19, 99), cash.usd(4, 50)))
    println(fmt.render(fmt.Line { label: "amount due", amount: due }))
    return due.dollars()
}
$ atoll run ledger/main.at
amount due: $26
atoll run: `main` returned 26

as names the namespace, and every member is reached through it: a function, cash.usd, a type, cash.Money, and a struct literal, fmt.Line { … }.

Module namespaces suit an API with many related names, or one where the namespace makes call sites clearer. Named imports are shorter for a small, unambiguous set of foundational types.

Traits are named by their module

A trait belongs to the module that declares it, as a type does, so two modules may each declare a trait of one name. A file writes Name for a trait its own module declares or one it imported by name, module.Name for a trait of a module it imported whole, and the traits of the standard library’s root files — Drop, Iterator, Display — bare, everywhere. json declares an Encode; a program may declare its own beside it, and say which one each impl and each bound means:

import json

/// The program's own `Encode`. `json.Encode` is another trait.
trait Encode {
    fn encoded(&self) string
}

struct Point {
    x int
    y int
}

impl Encode for Point {
    fn encoded(&self) string {
        return "${self.x},${self.y}"
    }
}

impl json.Encode for Point {
    fn encode(&self, out &mut string) void {
        out.append("[${self.x},${self.y}]")
    }
}

fn label[T: Encode](value T) string {
    return value.encoded()
}

fn main() int {
    p := Point { x: 3, y: 4 }
    println(label(p))
    println(json.encode(p))
    return 0
}

An import by name binds the trait, and as renames it: import example.dev/kit.{Agent as Worker} makes Worker the kit’s Agent in this file.

In a bound or an impl, a bare name that this module does not declare and the file does not import names the one trait of that name the program holds. Two modules of the desk project each declare an Agent, and main.at says which it means with the module’s name:

import example.dev/desk/front
import example.dev/desk/back

fn welcome[T: front.Agent](x T) string {
    return x.greet()
}

fn busy[T: back.Agent](x T) int {
    return x.work()
}

fn main() int {
    println(welcome(front.Greeter { name: "ada" }))
    return busy(back.Worker { jobs: 3 })
}
$ atoll run desk/main.at
welcome, ada
atoll run: `main` returned 3

Where nothing chooses between two modules’ traits, the use is refused with both named, instead of one being guessed:

import example.dev/desk/front
import example.dev/desk/back

fn welcome[T: Agent](x T) string {
    return "welcome"
}

fn main() int {
    println(welcome(front.Greeter { name: "ada" }))
    return back.Worker { jobs: 3 }.work()
}
error[ATOLL2104]: trait `Agent` is declared by more than one module: `example.dev/desk/back` and `example.dev/desk/front` at main.at:4:15
  help: say which one: import its module and write `back.Agent` or `front.Agent`, or import the trait by name with `import <module>.{Agent}`
1 error(s) found

A module still declares a name once: two trait Agent in one module is the same error it always was.

Three ways to name a module

A module of this package, or of a package it declares, can be named three ways. All three name the same module, and every check treats them alike:

import ./money.{usd, with_tax}
import ledger:report.{Line, render}

fn main() int {
    due := with_tax(usd(19, 99))
    println(render(Line { label: "invoice", amount: due }))
    return due.dollars()
}

It is the program from Named imports, with the other two spellings.

  • The full path, example.dev/ledger/money. This is what the module is called everywhere, and the spelling a diagnostic prints.
  • Relative, ./money or ../money, counted from the importing file’s own module: report/format.at could write import ../money.{Money}. A relative path stays inside its package, so ../money from the package root names nothing and is an error that says so. A module of another package is imported by its path.
  • Package-qualified, ledger:report: the package’s name, a colon, and the path inside it. The name is the last segment of the package’s path, or the as its [dependencies] entry gives it, so kit:util is acme.dev/kit/util once acme.dev/kit is declared. When two declared packages answer to the same name, the import is an error that names both rather than picking one.

A path is written bare. Quotes are the older spelling. The compiler still reads them, and atoll fmt removes them. The one path that keeps them is one that cannot be written bare, because a segment is not an identifier: my-utils would read as a subtraction.

import "./my-utils" as utils

fn main() int {
    return utils.three()
}
$ atoll run tools/main.at
atoll run: `main` returned 3

Collisions

A name a file binds is bound once. Here report and audit both export Line and render, and importing both pairs by name is an error that names both modules, once for each name:

import example.dev/ledger/money.{usd, with_tax}
import example.dev/ledger/report.{Line, render}
import example.dev/ledger/audit.{Line, render}

fn main() int {
    due := with_tax(usd(19, 99))
    println(render(Line { label: "invoice", amount: due }))
    return due.dollars()
}
error[ATOLL1074]: `Line` is imported from `example.dev/ledger/report` and from `example.dev/ledger/audit`, so only the first is in scope at main.at:3:1
  help: give this one a name of its own — `import example.dev/ledger/audit.{Line as <name>}`, or import the module and write `audit.Line`
error[ATOLL1074]: `render` is imported from `example.dev/ledger/report` and from `example.dev/ledger/audit`, so only the first is in scope at main.at:3:1
  help: give this one a name of its own — `import example.dev/ledger/audit.{render as <name>}`, or import the module and write `audit.render`
2 error(s) found

So is an import of a name this file declares, or another file of its module does: a module is one scope. The same name imported twice from the same module is one binding, and is not an error.

The help gives the two ways out. Give the second pair names of its own:

import example.dev/ledger/money.{usd, with_tax}
import example.dev/ledger/report.{Line, render}
import example.dev/ledger/audit.{Line as Entry, render as render_entry}

fn main() int {
    due := with_tax(usd(19, 99))
    println(render(Line { label: "amount due", amount: due }))
    println(render_entry(Entry { actor: "ada", label: "invoice", amount: due }))
    return due.dollars()
}

Or import the modules, and let the namespace say which:

import example.dev/ledger/money.{usd, with_tax}
import example.dev/ledger/report
import example.dev/ledger/audit

fn main() int {
    due := with_tax(usd(19, 99))
    println(report.render(report.line("amount due", due)))
    println(audit.render(audit.line("ada", "invoice", due)))
    return due.dollars()
}
$ atoll run ledger/main.at
amount due: $21
ada changed invoice to $21
atoll run: `main` returned 21

Placement

Imports are top-level declarations. They are not statements, not conditional, and not a runtime namespace object, so this does not parse:

fn main() void {
    import example.dev/ledger/report.{Line}
    println("unreachable")
}

Group them at the top of the file. An import belongs to that one file: a sibling in the same directory does not inherit it and writes its own. Only same-directory public declarations arrive automatically, without any import.

Resolution

An import path is matched, in order, against:

  1. modules collected from the current source tree;
  2. module roots contributed by path or resolved git dependencies;
  3. built-in std/* compatibility paths;
  4. otherwise, an unresolved external path.

A path with no source file behind it is an error, and a typo in the last segment is the common way to meet it. The error offers the module you probably meant:

import example.dev/ledger/monye.{Money}

struct Line {
    label  string
    amount Money
}

fn render(l Line) string {
    return "${l.label}: $${l.amount.dollars()}"
}
error[ATOLL1040]: unknown module `example.dev/ledger/monye` — no source file is in it — did you mean `example.dev/ledger/money`? at report/format.at:1:1
  help: a module is a directory of `.at` files: create `monye/` with one in it, or import a module that exists
1 error(s) found

The import is the one error: Money, which it failed to bring, is not then reported at every use.

A path that resolves but does not export the requested name is a different failure, and so is a name that exists but is not visible to you:

import example.dev/ledger/money.{Money, Reservation}
import example.dev/ledger/money.{cents_of}

struct Line {
    label  string
    amount Money
}

fn render(l Line) string {
    return "${l.label}: $${l.amount.dollars()}"
}
error[ATOLL1041]: module `example.dev/ledger/money` has no public export named `Reservation` at report/format.at:1:1
  help: `example.dev/ledger/money` exports `Money`, `RATE_BP`, `tax_on`, `total`, `usd` and `with_tax`
error[ATOLL1078]: `cents_of` is private to `money/amount.at`, so only that file can use it at report/format.at:2:1
  help: `private` keeps a declaration to its own file: mark it `internal` to share it with its package, or `pub` to export it
2 error(s) found

So is a module of another package that this package does not declare:

import example.dev/other
import example.dev/ledger/money.{Money}

struct Line {
    label  string
    amount Money
}

fn render(l Line) string {
    return "${l.label}: $${l.amount.dollars()}"
}
error[ATOLL1077]: `example.dev/other` is not a dependency of `example.dev/ledger` at report/format.at:1:1
  help: a package imports only itself and what its own atoll.toml declares — add the package that supplies `example.dev/other` to `example.dev/ledger`'s [dependencies]
1 error(s) found

These have different fixes. Editing { Money } cannot repair a missing module; adding a dependency cannot repair a visibility boundary. See Visibility and Projects.

Local and dependency modules are all registered before import resolution, so mutual imports between modules resolve without ordering them — money importing from report while report imports from money checks and runs.

A package imports only itself and what its own atoll.toml declares, so whether it compiles never depends on what the program using it happens to depend on as well.

Names with no import

List, Map, Set, Option, Result, and the scalar types come from the stdlib’s root files, which every program has. They need no import, and neither do println, assert, and the four ways to stop a program on purpose, panic, todo, unimplemented and unreachable (see Panics):

fn main() void {
    mut names: []string = []
    names.push("ada")
    names.push("grace")

    mut seen: Map[string, int] = Map.new()
    for n in names {
        seen.put(n.clone(), n.len())
    }

    println("${names.len()} names, ${seen.len()} lengths")
    println("first: ${names.get(0) ?? "none"}")
}

These bare names are a default. A declaration of your own replaces one: a struct Map in any file of a module is what Map means in every file of that module (a private one, only in its own file), and the compiler warns with ATOLL2107 that it took the name. A named import replaces it the same way in the file that writes it. std.Map always reaches the standard library’s, whatever replaced the bare name, and so does std.Display for a trait:

struct Map {
    x int
}

trait Display {
    fn show(&self) string
}

struct Point {
    x int
}

impl std.Display for Point {
    fn write_to(&self, out &mut string) void {
        out.append("(")
        self.x.write_to(out)
        out.append(")")
    }
}

fn shown[T: std.Display](v T) string {
    return v.to_string()
}

fn main() int {
    mut counts := std.Map.new[string, int]()
    counts.put("a", 1)
    mine := Map { x: 2 }
    return counts.len() + mine.x + shown(Point { x: 3 }).len()
}

Another module’s Map never changes a file’s bare Map unless the file imports it by name, import ./mymap.{Map}; otherwise the file writes mymap.Map. Importing one name from two modules is ATOLL1074 (see Collisions): rename one with as.

time and task are modules, not root files: import time reaches time.Duration and time.sleep, and import task reaches task.Task and task.Stream. spawn, race and select are syntax and need no import.

Old documents show import std/collections.{list, map, option, result}. That lowercase spelling contradicts the current naming rules and imports nothing you do not already have. Import a library module only when the API is genuinely outside the root files.

Re-export

A plain import creates no declaration in the importing module: downstream code that wants Money imports it from example.dev/ledger/money, whatever local name you chose.

pub import re-exports what it imports, so a package can present one module as its face:

pub import example.dev/ledger/money.{usd}
pub import example.dev/ledger/money.{usd as dollars}

Another package can now write import example.dev/ledger.{usd} and gets the same declaration — not a copy, so a value made through either path is the same type. internal import shares the names with the rest of the package and no further. There is no wildcard export list: each re-exported name is written.

A public function may of course mention an imported type in its signature. Callers still resolve that type through its defining module.

An import controls name reachability, not dependency acquisition — configure the source of a dependency in atoll.toml, described in Projects.

Type to search…

↑↓ navigate↵ selectEsc close