Home / Learn / 11 Packages and modules

Release v0.4.0Edition 0.2

11.2 pub and import

Page 3 of 9

11.2.1 What pub and import do

Section 6.3 compared a module to a shop: its public functions are the counter, where anyone may ask, and its private ones the back room. Until now every program was one module, so the counter had no other customers. With several modules, it does:

A module sees exactly three sources of names: its own declarations, the names it imports, and the prelude, the functions and types that every module sees without importing, such as List, Option and Console.

11.2.2 Why a module keeps its helpers private

A helper is often written for one job, and assumes things that its module guarantees. Here is the money code again, in one module. format handles a negative amount, a refund, by putting the minus sign in front and passing the amount without its sign to digits. digits was written for amounts of 0 or more. Nothing stops main from calling it directly:

steps/06-helper/src/store.unacheckrununa
module store

--- An amount in cents as a person reads it: 1990 is "19.90", and -150 is "-1.50".
format(cents: Int) -> Text = if cents < 0 then "-{digits(0 - cents)}" else digits(cents)

--- The digits of an amount of 0 or more, with two after the point.
digits(cents: Int) -> Text
=
  let rest = cents mod 100
  if rest < 10 then "{cents / 100}.0{rest}" else "{cents / 100}.{rest}"

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("a refund of 150 cents, by format: {format(-150)}")
  @console.print("the same refund, by digits: {digits(-150)}")

una run . prints:

Output
a refund of 150 cents, by format: -1.50
the same refund, by digits: -2.50

The second line is wrong: a refund of 150 cents is 1.50, not 2.50. digits divides with Una's division, which rounds down, toward the smaller number: -150 / 100 is -2, and the remainder is 50 (section 2.2 shows why). That is right for the job digits was written for, and wrong for any other. The checker cannot know which job a function was meant for.

When digits is private to store.money, no other module can call it, so it can only be reached through format, which keeps its assumption. The module can also change digits, rename it or delete it, and no code outside it breaks. Private stays private shows what happens when another module tries.

11.2.3 How to write pub

Write pub at the very start of the declaration, before its name:

steps/07-imports/src/store/money.unauna
--- An amount in cents as a person reads it: 1990 is "19.90", and -150 is "-1.50".
pub format(cents: Int) -> Text = if cents < 0 then "-{digits(0 - cents)}" else digits(cents)

pub goes on a function, a kind or a predicate, and on two declarations of later chapters: a capability and a handler (chapter 12), and a policy (chapter 17). An example or a requirement is never pub: an example belongs to its module, as Examples of private functions shows.

A pub function promises its callers a header they can rely on, so it writes every clause: its uses and its fails. A private function may leave them to inference (section 6.3, section 7.2), since all its callers are in its own module. Give every pub declaration a doc comment (---), since other modules read it to learn what the declaration does.

11.2.4 How to write an import

An import line has four parts:

steps/07-imports/src/store/app.unauna
import store.catalog (Product, find)
import store.money (format)
  1. import. The keyword that starts the line.
  2. store.catalog. The module path of a module of the same package, or of a standard module.
  3. (Product, find). In parentheses, each declaration the line takes, by its name, separated by commas. At least one name, and each name once.
  4. import store.money (format). One line per module: a module that takes names from two modules has two import lines. They come right after the module line, before any declaration, sorted by module path, with the names inside each sorted too, names with a capital letter first: una fmt . keeps them in that order.

There is no form that imports every name of a module, and no form that imports a module without naming what it takes. A reader of the import lines knows exactly which names come from where.

11.2.4.1 Functions

An imported function is used by its plain name, format(1990) or find(catalog, sku), as if the importing module had declared it. The same holds for an imported predicate (section 5.3).

11.2.4.2 Record kinds, with their constructor and fields

Importing a record kind brings its type, its constructor and its fields. This step's catalog module shares a record, Product, and a function that looks a product up, both pub:

steps/07-imports/src/store/catalog.unacheckuna
module store.catalog

import store.money (Cents)

--- A product the store sells.
pub kind Product
  sku: Text
  name: Text
  cents: Cents

--- The product with a SKU in a catalog, or `None` for a SKU the catalog does not list.
pub find(catalog: List[Product], sku: Text) -> Option[Product] = catalog.first_where(keep: fn(product) -> product.sku == sku)
  1. import store.money (Cents). A module imports what it uses, even another module's kinds. Cents, an Int that is never below zero, is a refined kind of section 5.3. Product.cents is a Cents, so a negative price cannot be built anywhere in the package.
  2. pub kind Product. The record, its constructor and its fields are part of the interface. A module that imports Product can write Product(sku: …, name: …, cents: …) and read product.name.
  3. pub find(...). The lookup: the first product of the list whose SKU matches, found with first_where (section 10.3), or None (section 7.1). The catalog is a parameter, so each caller passes the list of products it works with.

A capability and a handler, which chapter 12 teaches, are shared and imported in the same way: pub on the declaration, and the name in an import.

11.2.4.3 Sum kinds, with their variants

Importing a sum kind brings its variants with it, so the importing module can build them. This step has a module that tells whether a shelf can sell a SKU:

steps/08-import-forms/src/store/stock.unacheckuna
module store.stock

--- Whether a shelf can sell a SKU now.
pub kind Availability = InStock(units: Int) | SoldOut

--- The availability of a shelf that holds `units` units.
pub availability(units: Int) -> Availability = if units > 0 then InStock(units: units) else SoldOut

The app imports Availability, and with it InStock and SoldOut:

steps/08-import-forms/src/store/app.unacheckrununa
module store.app

import std.host (Console)
import store.stock (Availability, availability)

--- What a shelf card says.
card(sku: Text, stock: Availability) -> Text
=
  when stock
    is InStock(units) -> "{sku}: {units} in stock"
    is SoldOut -> "{sku}: sold out"

--- Prints the card of each shelf.
report(cards: List[Text]) -> Unit
  uses @console: Console[print]
=
  for line in cards
    @console.print(line)

pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = card("LAMP-01", stock: availability(4))
  let desk = card("DESK-02", stock: availability(0))
  let chair = card("CHAIR-09", stock: SoldOut)
  report([lamp, desk, chair])
Output
LAMP-01: 4 in stock
DESK-02: sold out
CHAIR-09: sold out

card writes the kind in a parameter's type, and main builds a variant, SoldOut, so both need the import. A when needs no import to match a variant, even in a module that did not import the kind: its arms take the variants of the value's type, whatever module declared it.

11.2.4.4 The host's capabilities: std.host

The same step also writes import std.host (Console). std.host is one of the two standard modules a package can import. It holds the host's capabilities, such as Console and Clock (chapter 12), which the prelude already puts in every module. So the import changes nothing but makes the source explicit, and you may leave it out. The other standard module, std.testing, holds helpers for examples.

11.2.5 A private helper next to a public function

Back to money, now split into modules. store.money keeps the helper, digits, next to its public format:

steps/07-imports/src/store/money.unacheckuna
module store.money

--- An amount of money in cents, never below zero.
pub kind Cents = Int where it >= 0

--- An amount in cents as a person reads it: 1990 is "19.90", and -150 is "-1.50".
pub format(cents: Int) -> Text = if cents < 0 then "-{digits(0 - cents)}" else digits(cents)

--- The digits of an amount of 0 or more, with two after the point.
digits(cents: Int) -> Text
=
  let rest = cents mod 100
  if rest < 10 then "{cents / 100}.0{rest}" else "{cents / 100}.{rest}"

The app takes what it needs from the two modules, one name at a time:

steps/07-imports/src/store/app.unacheckrununa
module store.app

import store.catalog (Product, find)
import store.money (format)

--- Why a price could not be shown.
kind PriceError = | NotListed(sku: Text)

--- The price of a SKU in a catalog, as a person reads it.
price_tag(sku: Text, catalog: List[Product]) -> Text
  fails PriceError
=
  let product = find(catalog, sku)
    if none fail NotListed(sku)
  "{product.name}: {format(product.cents)}"

pub main() -> Unit
  uses @console: Console[print]
=
  let catalog = [Product(sku: "LAMP-01", name: "Desk lamp", cents: 1990)]
  let lamp = attempt price_tag("LAMP-01", catalog)
  let chair = attempt price_tag("CHAIR-09", catalog)
  @console.print("{lamp}")
  @console.print("{chair}")
Output
Ok("Desk lamp: 19.90")
Err(NotListed("CHAIR-09"))

PriceError and price_tag have no pub, so they belong to store.app alone. A private function may leave its fails to inference, but price_tag writes it, so its header can be read without its body. price_tag calls find and format by their plain names, since the import lines name them. It also writes Product in a parameter's type, List[Product], and main builds one, so Product is imported too. attempt keeps each lookup's outcome as a Result (section 7.4), and the two lines print them: the lamp's text, and the failure for a SKU the catalog does not list.

11.2.6 How names are found

11.2.6.1 Where a name comes from

When a module uses a name, una looks for it in this order, and the first place that has it wins:

  1. the local names: parameters, let bindings and the like;
  2. the module's own declarations;
  3. the names it imports, and the variants of the sum kinds it imports;
  4. the prelude.

A name found nowhere is U1001, "cannot find name … in this module, its imports or the prelude". Using a name you did not import shows it. An import of a module that the package does not have, or of a name that the module does not declare, is U1001 too.

11.2.6.2 Private stays private

Try to import digits into the app:

src/store/app.unadiff
--- a/src/store/app.una
+++ b/src/store/app.una
@@ -4 +4 @@
-import store.money (format)
+import store.money (digits, format)

una check . reports:

Diagnostic
[U1004] Error: function `digits` is private to module `store.money`
    ╭─[ src/store/app.una:4:21 ]
    │
  4 │ import store.money (digits, format)
    │                     ───┬──
    │                        ╰──── function `digits` is private to module `store.money`
    │
    ├─[ src/store/money.una:10:1 ]
    │
 10 │ digits(cents: Int) -> Text
    │ ───┬──
    │    ╰──── declared here without `pub`
    │
    │ Help: repair 1 (widens visibility: every module may then call it: check that it belongs to the module's interface): declare `digits` with `pub`; edit src/store/money.una:10:1..10:1 to "pub "
    │
    │ Note: run `una explain U1004` for an explanation
────╯

Read it from the top. The first line names the problem and the module that owns the function. The first mark points at the name in the import, and the second at the declaration in store.money, "declared here without pub". The help line offers the repair, adding pub, but marks it as one that widens visibility: every module may then call it. una fix . does not apply such a repair by itself. Making a helper public is a decision about the module's interface, and you take it by editing the declaration, with a doc comment for its new callers.

11.2.6.3 One name, one meaning

An import and a declaration of the same module share one set of names, so a module cannot declare a name it also imports, and cannot import one name from two modules. Both are U1002, as two declarations of one name are (An import that clashes with a declaration). A declaration or an import may reuse a name of the prelude: the module's own wins.

11.2.6.4 No cycles

If store.money imports store.pricing, then store.pricing cannot import store.money, directly or through other modules. A loop of imports is an import cycle, U1003 (An import cycle). Without cycles, every module can be read, and checked, after the modules it uses.

11.2.7 Choosing what to share and what to import

Which to use:

You want… Use
A function, kind or predicate that other modules need pub, with a doc comment, and every clause of its header written
A helper that only this module uses no pub: it stays private, and may infer its uses and fails
A declaration of another module import module.path (name, …), one name per declaration
A host capability's name, written explicitly import std.host (Console), optional, since the prelude has it
The same helper in two modules One pub declaration in the module it belongs to, imported by the other

Share as little as the other modules need. Every pub declaration is a promise: changing its header changes every module that uses it.

11.2.8 Check yourself: names and imports

The app of A private helper next to a public function changes one line: price_tag now calls digits directly, without importing it.

src/store/app.unadiff
--- a/src/store/app.una
+++ b/src/store/app.una
@@ -15 +15 @@
-  "{product.name}: {format(product.cents)}"
+  "{product.name}: {digits(product.cents)}"

Does it check? If not, which code does una check . report: U1004, since digits is private, or another one?

Show the answer

It does not check, and the code is U1001, not U1004:

Diagnostic
[U1001] Error: cannot find name `digits` in this module, its imports or the prelude

The app never imported digits, so the name is in none of its three sources: its declarations, its imports and the prelude. U1004 is reported only when an import names a private declaration, as in Private stays private. Either way, the fix is the same: call format, which is public and handles every amount.

Next:11.3 The manifest and the lock