The language / Imports and exports
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
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:
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
endWhat 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:
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 thereOnly 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 "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:
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:
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:
export "money"
export "greeter"Importing shop now brings in what money and greeter export:
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:
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 appAn app's lode.hem says what it is and what it needs, in Hematite:
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 @:
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 itspackages/. - A file imports the packages its
lode.hemneeds, 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 tolode addit. - 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 installstops and names every need. - A package comes from a git repository (
git:, whose tags,v1.4.2or1.4.2, are its versions), or from a folder (path:, from thelode.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.lockrecords each package's version, where it came from (for git, the commit) and a hash of its files.lode installkeeps to it while it still will do; a git tag that has moved since is an error, never taken quietly. Keeplode.lockwith the app's code:packages/can always be made again from it.packages/holds exactly what the app needs:lode installremoves what nothing needs any more.hemchecks that what's installed is a versionlode.hemallows, and says to runlode installwhen 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:
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 installThe Rust marks what it gives, and lists it once:
/// 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:
# 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:
&strandStringare String,i64Int,f64Float,boolBoolean,Timea Time,Zonea Zone (its.0the zone's name),BytesBytes (its.0aVec<u8>),Option<T>isT?,Vec<T>is[T],Hash<K, V>is{K: V}(in order), andResult<T, Failure>isT!: a failure fortry(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 inpackage!(...; handles: Connection). It's declaredexport native class Connection; a function that givesHandle<Connection>makes one, and one that takes&Connectionuses it. Hematite never sees inside,newcan'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: RecordTypeis 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), aRecord), and reads the ones it's given (record.values()). Their values areValues: 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.hemand the library are made from the same signatures. Hematite checks the two still agree at the first call, and says to runlode installwhen 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 defis only ever in a package'snative.hem.- A program made with
hem buildcarries 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.
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 doubleThe 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:
#[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::Failedis the method's failure, itsError.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.Anyis a value of a type the Hematite side names: a type parameter, named after the Rust's parameter (request: Anyisrequest: Request), which the Rust gives on as it is. A function that gives one gives a value of its type parameterOut:apply[Out](method: Method, n: Int): Out!, called asapply[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:
#[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.
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, thenreturnand 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:
lowabove 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 thenreturnis 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 ... endis its class'sfilter. - 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:
#[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 buildand 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
hemexample in itsREADME.mdruns 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.