Skip to the page
The language / Imports and exports

Start here01

The language02

Programs and the world03

Kiln04

02 The language / 12

Imports and exports

A program over several files: what each one shares, and what it uses.

A program can grow past one file. Each file decides what it shares, by marking definitions export, and what it uses, by naming other files with import at its top. Everything else stays inside the file, so its helpers and its names never get in another file's way.

Sharing and using

A file shares a definition by marking it export, and another file uses it with import. Here money.hem shares a static and two methods, and keeps whole to itself:

money.hem
export static CENTS_PER_UNIT = 100

export def cents(units: Int): Int
  return units * CENTS_PER_UNIT
end

export def format(amount: Int): String
  return "#{amount / CENTS_PER_UNIT}"
end

# Not exported: only money.hem can use it.
def whole(amount: Int): Int
  return amount - amount % CENTS_PER_UNIT
end

What a file exports joins the importing file's names, so cents and format are called as if they were defined there. whole isn't exported, and the error says so:

app.hem
import "money"

print(format(cents(3))) # prints 3.0
print(CENTS_PER_UNIT)   # prints 100
print(whole(250))       # error: 'whole' is defined in money.hem but not exported; add 'export' to it there

Only definitions can be exported: export static, export def, export class, export trait and export enum. Everything else in a file is its own. Other files can't see it, and may use the same names for their own things.

Writing an import

import "path" names a file from the importing file's folder, without .hem: import "money", import "models/account", import "../money". Imports go at the top of the file, one per line, before anything else, so a file's first lines show everything it depends on.

What a file can see

Every name a file uses is defined in the file, or in a file it imports at its top. (Built-ins like print and File need no import: every file has them.)

Since imported names join the file's own, two of them can't be the same. It's an error when two imports export the same name, or when an import exports a name the file defines itself. Import one of them with a name instead.

Checked together

A file is read once, however many files import it. Files may import each other (a imports b, b imports a): each sees what the other exports.

A file's statics are set up after those of the files it imports. Of two files that import each other, the one reached second is set up first: when app imports a, and a and b import each other, b's statics come before a's. A static that uses one set up after it is a mistake, where it's written.

hem run app.hem checks every file the program imports before anything runs, and each error names the file it's in: money.hem:4:10: error: ....

Importing with a name: as

With as, a file's exports stay behind a name of your choosing, and each use says where it comes from:

import-with-a-name.hem
import "money" as money

print(money.format(money.cents(2))) # prints 2.0
print(money.CENTS_PER_UNIT)         # prints 100
print(cents(2))                     # error: 'cents' comes from an import with a name: write 'money.cents'

The name goes in front of everything the file exports: calls, consts, types (account: models.Account), new models.Account(...), enum values (money.Currency.dkk) and traits (with models.Named). It is only a prefix, never a value on its own.

A file's script

A file's script is its top-level code that isn't a definition: its vars, consts and statements like print(...). It runs only when the file is the one being run (hem run greeter.hem), never when another file imports it. So one file can hold definitions for other files, and a small program that uses them:

greeter.hem
export def greet(name: String): String
  return "Hello, #{name}!"
end

print(greet("greeter")) # prints Hello, greeter!

Imported, the same file gives only its definitions, and its own print stays quiet:

greet-ada.hem
import "greeter"

print(greet("Ada")) # prints Hello, Ada!

Statics are definitions, not script: an imported file's statics are set up before the importing file's code runs. Its top-level vars and consts belong to its script, and so are never set up.

Passing names on: export "path"

export "path" imports a file, and also exports everything that file exports to whoever imports this one. A file of nothing but export lines gathers several files into one import:

shop.hem
export "money"
export "greeter"

Importing shop now brings in what money and greeter export:

import-the-shop.hem
import "shop"

print(greet(format(cents(5)))) # prints Hello, 5.0!

Packages: Lode

A package is a folder of .hem files that apps share. Lode, Hematite's package manager (the lode command), puts the packages an app needs in its packages/ folder:

terminal
lode init                          # this folder's lode.hem
lode add greet --path ../greet     # needs greet, from a folder, and installs it
lode add maps --git https://example.com/maps.git
lode install                       # what lode.hem needs, as lode.lock has it
lode update                        # the same, with the newest that will do
lode list                          # what's installed
lode test                          # runs README.md's examples and tests/
lode run database migrate app.sqlite3  # a package's command, here in the app

An app's lode.hem says what it is and what it needs, in Hematite:

lode.hem
import "lode"

const package = new Package(
  name: "shop",
  version: "0.1.0",
  needs: [
    new Need(name: "greet", version: "0.3", path: "../greet"),
    new Need(name: "maps", version: "1.2", git: "https://example.com/maps.git"),
  ],
)

A package has one too, the same way, and may say the Hematite it's written for: hematite: "0.1". Its files are imported with @:

hem
import "@greet"           # packages/greet/greet.hem, the package's main file
import "@greet/words"     # packages/greet/words.hem
import "@maps" as maps
  • @ marks a package, so one is never taken for a file of the app's own.
  • The app is the nearest folder above the file that's run with a lode.hem; its packages are in its packages/.
  • A file imports the packages its lode.hem needs, and no others: the app's, or, for a file of a package, the package's. A package the app doesn't need is an error that says to lode add it.
  • A version is three numbers: "1.4.2". What will do is written as the least of it: "1.4" is 1.4.0 or any later 1.x; before 1.0, "0.4" is a 0.4.x. A name is small letters, digits and _, as Hematite's names are.
  • An app has one version of each package: the newest that every need of it allows. When none does, lode install stops and names every need.
  • A package comes from a git repository (git:, whose tags, v1.4.2 or 1.4.2, are its versions), or from a folder (path:, from the lode.hem's own) while it's being written. Each package is a repository of its own; nothing comes with Hematite. Lode's registry comes later.
  • lode.lock records each package's version, where it came from (for git, the commit) and a hash of its files. lode install keeps to it while it still will do; a git tag that has moved since is an error, never taken quietly. Keep lode.lock with the app's code: packages/ can always be made again from it.
  • packages/ holds exactly what the app needs: lode install removes what nothing needs any more.
  • hem checks that what's installed is a version lode.hem allows, and says to run lode install when it isn't.

A package's Rust

A package can have a Rust half, for what a Rust crate does best: a native/ folder holding a Rust library, whose functions it gives Hematite. lode install builds it inside the app, in packages/<name>/native/target, and writes the package's native.hem from it:

text
packages/password/
  lode.hem
  password.hem    # what apps use: import "native", then Hematite
  native/
    Cargo.toml    # crate-type = ["cdylib"], and hematite-native = "0.1"
    src/lib.rs
  native.hem      # written by lode install

The Rust marks what it gives, and lists it once:

rust
/// A password, hashed with Argon2id and a random salt.
#[hematite_native::export]
fn argon2_hash(password: &str) -> String {
    // ...
}

hematite_native::package!(argon2_hash, argon2_matches);

lode install declares each one in native.hem, which the package's own Hematite imports:

hem
# A password, hashed with Argon2id and a random salt.
export native def argon2_hash(password: String): String
  • An app never sees the Rust: it imports the package, as any other.
  • A Rust type is its Hematite counterpart: &str and String are String, i64 Int, f64 Float, bool Boolean, Time a Time, Zone a Zone (its .0 the zone's name), Bytes Bytes (its .0 a Vec<u8>), Option<T> is T?, Vec<T> is [T], Hash<K, V> is {K: V} (in order), and Result<T, Failure> is T!: a failure for try (Failure::invalid(...), and the other kinds). Any other type is an error in the Rust, where it's written.
  • A Rust object Hematite holds is a handle: a struct marked #[hematite_native::handle], listed in package!(...; handles: Connection). It's declared export native class Connection; a function that gives Handle<Connection> makes one, and one that takes &Connection uses it. Hematite never sees inside, new can't make one, and the Rust object is dropped when Hematite's last copy of it goes.
  • Records of any type: a function that takes row: RecordType is generic in Hematite, rows[Row with Record](...), and the caller says which record (rows[Visit](3), or from its arguments). The Rust reads the record's fields (row.fields(): names and types), makes records of it (row.make(values), a Record), and reads the ones it's given (record.values()). Their values are Values: nil, a Boolean, an Int, a Float, text (an enum's value by its name), bytes, a Time, a Zone, an array, a hash, an object (its class and fields by name), or a handle.
  • native.hem and the library are made from the same signatures. Hematite checks the two still agree at the first call, and says to run lode install when they don't, or when the library isn't built. A panic in the Rust stops the program with what it said, as a mistake does.
  • native def is only ever in a package's native.hem.
  • A program made with hem build carries the library inside it, so it's still one file that runs anywhere: the first time it runs, it writes the library to the user's cache (~/.cache/hematite), and loads it from there.
  • Building it needs Rust (cargo) on the machine, for now.

Methods a package's Rust calls

A parameter typed Method takes a method of any shape, named without parentheses: a package's Rust calls it, after asking what it takes. Hematite holds a Method, keeps it in records and arrays, and gives it on, but can't call one itself: what it takes isn't known there. A method's own type, like (Int): Int, takes only methods of that shape, and Hematite calls those.

method-page.hem
def double(n: Int): Int
  return n * 2
end

record Page
  path: String
  handler: Method
end

const page = new Page(path: "/double", handler: double)

print(page.handler) # prints double

The Rust takes a Method and asks what it is: method.name, method.params (each one's name and type, as Hematite writes it), method.gives and method.fails. A function that takes call: &Call is given the call, and call.call(&method, &[...]) runs the method:

rust
#[hematite_native::export]
fn apply<'a>(
    call: &Call<'a>,
    method: Method,
    n: i64,
) -> Result<Any<'a>, Failure> {
    match call.call(&method, &[call.make(n).into()]) {
        Called::Gave(value) => Ok(value.into()),
        Called::Failed(error) => Err(Failure::passing(error)),
        Called::Stopped(why) => Err(Failure::other(why)),
    }
}
  • The method runs on the thread the Rust was called on, with the program's statics as its caller sees them.
  • Hematite runs only a method the program gave its Rust, and holds what the Rust gives it to the method's parameters: anything else stops it, with what was wrong.
  • Called::Failed is the method's failure, its Error. Failure::passing(error) gives it on as it was; it can be given to another method too.
  • call.make(method) gives a method back, to a method that takes one: Hematite calls it there, by its type.
  • Any is a value of a type the Hematite side names: a type parameter, named after the Rust's parameter (request: Any is request: Request), which the Rust gives on as it is. A function that gives one gives a value of its type parameter Out: apply[Out](method: Method, n: Int): Out!, called as apply[Int](double, n: 21). What it gives is held to that type, as every function's result is to its own: a value of another stops the program, with what was wrong.

A package's check of calls sees each call of its methods that's given a method (its functions', its classes' static methods' and its objects' methods'), when the program is checked: a function marked #[hematite_native::check_call] that takes a &CallSite. The call has the method's name as code writes it (route, Router.get) and each argument's name, type and place, with its text when it's written out, and what a method given to it (double, Users.show) takes and gives. Like a check of code, it only adds mistakes, where they are:

rust
#[hematite_native::check_call]
fn check(site: &CallSite) -> Vec<Refusal> {
    let (Some(path), Some(to)) = (site.arg("path"), site.arg("to")) else {
        return Vec::new();
    };
    let (Some(text), Some(method)) = (&path.text, &to.method) else {
        return Vec::new();
    };
    let parts: Vec<&str> = text
        .split('/')
        .filter_map(|part| part.strip_prefix(':'))
        .collect();
    let params: Vec<&str> = method
        .params
        .iter()
        .map(|param| param.name.as_str())
        .collect();
    if parts == params {
        return Vec::new();
    }
    let message = format!("{} takes ({})", method.name, params.join(", "));
    vec![Refusal::at(to, message)]
}

Workers run methods on threads of their own: Workers::start(call, count) makes copies of the program, each on a thread with its statics set up, and workers.run(|call| ...) runs a job on the first that's free, with a call of that copy's. Values never go from one copy to another: a job makes what it gives the methods it calls, and keeps what it gets to itself. A server is what they're for: each request is a job.

Code: blocks a package reads

A parameter typed Code[(Row): Boolean] takes a block its method reads instead of running. The block comes after the call, as any block does, and the package's Rust gets what it says, to make something else of it, like a database's query. Hematite checks the block first, as a block of that type.

code-rows.hem
class Rows
  readable const name: String

  # Reads its block as code; here, it only passes it on.
  def keep(condition: Code[(Int): Boolean]): Code
    return condition
  end
end

const rows = new Rows(name: "numbers")
const low = 3

const kept = rows.keep do (n)
  const even = n % 2 == 0

  return n > low and even
end

print(kept) # prints code
  • The block holds consts that name parts of it, then return and what it gives.
  • What doesn't use the block's parameters is worked out where the block is given, and goes with it as a value: low above is the value 3.
  • What uses them is written out: their fields, operators, calls, if ... then ... else, text with #{...}, and blocks inside it given as code too. Anything else is a mistake, where it is.
  • A method of the program's whose body is consts then return is read through: the code holds what it gives, with its arguments (and its object) put in. So a record's method can say once what several blocks use. Any other method stays a call, for the package to read or refuse.
  • Nothing in a block read as code runs, so a call in it that can fail needs no try: there, it's what it gives.
  • An object's own method takes a block before a built-in of the same name: rows.filter do ... end is its class's filter.
  • Code is passed on as any value is; a package's Rust takes it as plain Code.

The Rust reads its tree (code.tree: the parameters, what it gives, and its body, each part with its type and where it's written) and its values (code.values). code.key is the same each time the same block is given, for keeping what's made of it. A package's check sees each block given to its methods when the program is checked, and refuses what the package can't read, where it is:

rust
#[hematite_native::check]
fn check(code: &Tree) -> Vec<Refusal> {
    let mut found = Vec::new();
    code.body.each(&mut |node| {
        if let Kind::Call { name, built_in: false, .. } = &node.kind {
            found.push(Refusal::of(node, format!("{name} can't become SQL")));
        }
    });
    found
}
  • A check only adds mistakes. Hematite has checked the block either way, and a package can't change what it means.
  • hem run, hem build and the editor all run it, from the package's built library.

A package's tests

lode test, in a package's folder, installs what it needs (building its Rust), then checks that it does what it says:

  • Each hem example in its README.md runs on its own, and must print what its # prints ... comments say, a line each.
  • Each file in tests/ must print what its # expect: ... comments say. One with # expect error: ... comments must stop with each of those mistakes, on its line, and no others.
  • They run inside the package, where import "@name" is the package itself, so they're written as an app would write them.

It says which passed and which failed, with what came instead, and fails when any did.