Tern

12. Modules and packages

Real programs outgrow one file. This chapter shows how Tern splits a program into modules (one file each) and packages (a directory of files), how import finds them, how to use the names they define, and how to keep helper functions private with a leading _. There is no package manager and no configuration file: the directory layout is the whole story.

Using a module

You have already used modules from the standard library. import name makes a module available, and its functions and types are then written name.thing:

import math
import fmt

fn main():
    r = 2.5
    area = math.pi() * r * r
    print(fmt.fixed(area, 2), math.sqrt(2.0), math.floor(3.7))
Output
19.63 1.4142135623730951 3.0

from name import a, b brings specific names in so you can use them without the prefix. The module name is not in scope then, unless you also import it:

from math import pi, floor
from fmt import fixed
import fmt

fn main():
    print(fixed(pi(), 3), floor(9.99), fmt.thousands(1234567))
Output
3.142 9.0 1,234,567

Asking for a name the module doesn't have is caught at compile time:

Does not compile
import math

fn main():
    print(math.sqroot(2.0))
Compiler output
4: error: module `math` has no `sqroot`

The standard library overview lists every module and function.

Your own modules

Every .tn file is a module, named after the file. Put money.tn next to your main file, and import money finds it. A module contains the same things as any Tern file (imports, structs, enums, functions), but no fn main(): the program starts in the file you run.

Here is a small program in three parts. First, money.tn, a module that handles prices in cents so that amounts never suffer from floating-point rounding:

# money.tn
import fmt

struct Price:
    cents: int

fn from_cents(cents: int) Price:
    return Price(cents)

fn add(a: Price, b: Price) Price:
    return Price(a.cents + b.cents)

fn times(p: Price, n: int) Price:
    return Price(p.cents * n)

fn show(p: Price) str:
    return "$" + fmt.cents(p.cents)

Other files refer to its type as money.Price and to its functions as money.from_cents, and so on. Modules can import other modules, including standard ones, as money.tn imports fmt.

Packages: a directory is one module

When a module grows too big for one file, make it a directory. All the .tn files in a directory together form one package, imported by the directory's name. Files in the same package share one namespace: they see each other's structs and functions without importing anything.

shop/
    main.tn
    money.tn
    inventory/
        item.tn
        stock.tn
# inventory/item.tn
import money

struct Item:
    name: str
    price: money.Price
    qty: int

fn new_item(name: str, cents: int, qty: int) Item:
    return Item(_tidy(name), money.from_cents(cents), qty)

fn _tidy(name: str) str:            # private: only this package can call it
    return name.trim().lower()
# inventory/stock.tn
import money

struct Stock:
    items: [Item]                   # Item comes from item.tn: same package, no import

fn empty() Stock:
    return Stock([])

fn add_item(s: mut Stock, it: Item):
    s.items.push(it)

fn value(s: Stock) money.Price:
    total = money.from_cents(0)
    for it in s.items:
        total = total.add(it.price.times(it.qty))
    return total
# main.tn
import inventory
from money import Price, show

fn main():
    s = inventory.empty()
    s.add_item(inventory.new_item("  Lamp ", 2500, 3))
    s.add_item(inventory.new_item("Rope", 899, 10))
    total: Price = s.value()
    print(len(s.items), "items, worth", show(total))
    for it in s.items:
        print(it.name, it.price.show(), "x", it.qty)

Running it:

tern run shop/main.tn
2 items, worth $164.90
lamp $25.00 x 3
rope $8.99 x 10

Notice how the "methods" work across modules. s.add_item(...) in main.tn finds add_item even though it lives in inventory: x.f(...) looks for f in the module where the type of x is defined. Likewise it.price.show() finds money.show, because Price is defined in money. This is what lets you call d.exec(...) on a database handle from the sqlite module without writing sqlite.exec(d, ...).

A package's files are read in alphabetical order, but the order doesn't matter, since functions and types can be used before they are defined. Two files of one package can't define the same name.

How import finds a module

For import name, the compiler looks in this order and takes the first match:

  1. library/std/name.tn, a standard library module;
  2. library/name/, a first-party package such as roost, queue, or pg;
  3. name.tn in the directory of the main file (the file you passed to run, check, or build);
  4. name/, a directory of .tn files next to the main file;
  5. deps/name/, a third-party package fetched by tern get (only in a project with a tern.mod).

Some consequences:

  • Imports are always resolved from the main file's directory, even inside a package. That is why inventory/item.tn writes import money, not import ../money: there are no relative paths and no nested module names like a.b.
  • The standard library and first-party packages come first. A file of yours named fmt.tn, json.tn, or web.tn would be ignored in favor of the library's, so pick other names.
  • Each module is loaded once, however many files import it.
  • Modules can't import each other in a cycle (a imports b and b imports a). Move the shared part into a third module that both import.
  • If nothing matches, the error lists where it looked: can't find module `invntory` (looked in the standard library and /path/to/shop).

Private names

A struct, enum, or function whose name starts with _ is private to its module (or package): other modules can't use it, with or without from ... import. Use this for helpers that are not part of the module's promise to its users, so you can change them freely:

Does not compile
import fmt

fn main():
    print(fmt._scaled(1205, 2))
Compiler output
4: error: `_scaled` is private to module `fmt`

The same error appears for inventory._tidy("x") in the shop example. Inside inventory, both item.tn and stock.tn may call _tidy, because they are the same package.

Sharing code between projects

To use code from another repository, add it as a package:

tern add geo https://github.com/someone/tern-geo

That records geo = https://github.com/someone/tern-geo@v1.2.0 in your project's tern.mod, fetches it into deps/geo/, and pins its exact files in tern.lock, so every checkout builds the same code. import geo then works from any file in the project. tern search WORD lists what's in the package index. Sharing your own module works the same way the other way round: put it in a git repository and tag a version. Writing and publishing a package has the details, and Packages covers tern.mod and tern.lock.

Try it

Split the bank from chapter 9 into two files: bank.tn with the Bank struct and its functions (make a private _check_owner(b: Bank, owner: str) bool helper that deposit uses to ignore unknown owners), and main.tn that imports it and calls b.deposit(...) with method syntax. Then try calling bank._check_owner from main.tn and read the error.

Solution

# bank.tn
struct Bank:
    accounts: {str: int}

fn new_bank() Bank:
    return Bank({})

fn open_account(b: mut Bank, owner: str):
    b.accounts[owner] = 0

fn deposit(b: mut Bank, owner: str, amount: int):
    if _check_owner(b, owner):
        b.accounts[owner] += amount

fn total(b: Bank) int:
    t = 0
    for owner, bal in b.accounts:
        t += bal
    return t

fn _check_owner(b: Bank, owner: str) bool:
    return owner in b.accounts
# main.tn
import bank

fn main():
    b = bank.new_bank()
    b.open_account("ada")
    b.deposit("ada", 100)
    b.deposit("zed", 50)            # ignored: no such account
    print(b.total(), b.accounts)
100 {"ada": 100}

Next: 13. Where to go next. Reference: §17 Modules and packages.

Source: docs/tour/12-modules.md. Every example on this page is compiled and run by tern x test docs.