
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
The Louise language (v0)
This reference describes what programs mean. The exact syntax is in grammar.md, and every diagnostic code is in diagnostics.md. The design decisions behind each part are in the ADRs.
Programs and modules
Files: a program is a set of modules, one per .lse file.
Packages: a package is a directory with a louise.toml.
- Its modules live under
src/, named by their path:src/app/main.lseis moduleapp/main. src/lib.lsetakes the package's name.- Tests can also live under
test/, which onlylouise test,louise checkand the language server load. - Other packages are dependencies;
[dev-dependencies]are for the tests only.
Visibility and imports:
- Items are private unless marked
pub. pub opaque typeexports a type without its representation (ADR 0033). Other modules can name it, in signatures and inimport m.{type T}, but cannot call its constructors (record update included), match on them, or read its fields (E0117). They build and read its values through the module's functions, so the module can keep an invariant: a validatedEmail, a non-negativeMoney.
// email.lse
pub opaque type Email { Email(String) }
pub fn parse :: s: String -> Option<Email>
{
if string.contains s "@"
{
Some(Email(s))
}
else
{
None
}
}
pub fn text :: e: Email -> String
{
match e { Email(s) -> s }
}
importbrings a module into scope under its last segment, and can name items to use unqualified:
import std/html.{type Html}
import std/io
import std/list.{filter, map}
pub fn main :: -> () / <io>
{
io.println (show (map (filter [1, 2, 3] fn x { x > 1 }) fn x { x * 10 }))
}
The prelude (std/prelude) is always in scope. It provides the basic types (Int, Float, String, Bytes, Bool, List, Option, Result, Order, Never), the core traits (Eq, Ord, Num, Semigroup, Show, Debug, Hash, Default), and panic.
Attributes go before an item. These exist; any other, a malformed one, or one on the wrong item is an error (E0114):
@extern c "symbol", with the optionsblocking(orblocking cpu,blocking io) andowned: a function without a body, implemented in C (below). Every other function, apart from trait methods, has a body (E0115).@testand@should_panic "text", on functions: tests.@derive Trait ...on a type and@derivableor@derivable fon a trait: deriving.@thread_safeon a type: aResourceof that kind may be sent to another actor.@fipon a function: it must update in place (below).@builtin, only in the standard library: an abstract type (without a body) the runtime implements.@intrinsic, only in the standard library: a function without a body whose body the compiler gives (std/wire's, ADR 0072).@remoteon a top-level function: another node of a cluster may spawn it (ADR 0072, the tutorial). It needs a full signature (E0107) and a body, takes one argument (or none) whose type isWire, returns(), is not generic, and performs only what a remote actor body may (proc,clock,random,io,ffi; hostfs/netare denied by ADR 0084); otherwiseE0707(E0706for the argument,E0708for two functions whose keys collide). Called, it is a function; its name used as a value is astd/dist/remote.Remote<A>(dist.Remote<A>, whatdist.spawn_ontakes), the key other nodes know it by (the hash of its qualified name, docs/wire-format.md), not a closure: passfn x { worker x }where a function is expected.
louise run runs main. It must take no parameters and perform only effects the runtime handles: io, ffi, proc (std/process), clock (std/time), random (std/random), fs (std/file) and net (std/net) (ADRs 0036 and 0084). Tests and ordinary local actors get the same handlers.
Values and types
Built-in types:
| Type | Values |
|---|---|
Int | Integers of any size: 63-bit words, promoted to big integers when a result does not fit (ADR 0014). Literals are 63-bit. |
Float | 64-bit IEEE floats. |
String | Immutable UTF-8 text. <> concatenates (see Semigroup). A literal interpolates: "{n} items" (below). |
Bytes | Immutable binary data (std/bytes). |
Bool | True, False |
() | The unit value. Tuples are (a, b), and t.0 indexes them. |
List<a> | [1, 2, 3], [x, ..rest] |
fn(a) -> b / <e> | Functions and closures, with the effects a call may perform. |
Data types list their constructors. A constructor with labelled fields is a record: .field reads a field, and Ctor(..base, field: v) copies with changes. Both need a type with one constructor (E0206, E0204): for a type with several, match on it.
@derive Eq Show
pub type Shape { Circle(radius: Float), Rect(width: Float, height: Float) }
pub type Point { Point(x: Int, y: Int) }
fn moved :: p: Point -> Point
{
Point(..p, x: p.x + 1)
}
type Pair<a> = (a, a)
Refined constructors: GADTs and existential types (ADR 0041). A constructor may say which type it builds, after ->. Its type variables are its own: those of the result say what the type's parameters are for this constructor (a GADT), and the others are hidden (existential). A where lists traits the hidden or refined types implement: the value stores their dictionaries.
pub type Expr<a>
{ IntLit(Int) -> Expr<Int>
, BoolLit(Bool) -> Expr<Bool>
, Add(Expr<Int>, Expr<Int>) -> Expr<Int>
, If(Expr<Bool>, Expr<a>, Expr<a>) -> Expr<a>
, Pair(Expr<b>, Expr<c>) -> Expr<(b, c)>
}
fn eval :: e: Expr<a> -> a
{
match e
{ IntLit(n) -> n
, BoolLit(b) -> b
, Add(x, y) -> eval x + eval y
, If(c, t, f) -> if eval c { eval t } else { eval f }
, Pair(x, y) -> (eval x, eval y)
}
}
pub type Showable { Showable(b) -> Showable where Show<b> }
fn describe :: s: Showable -> String
{
match s { Showable(x) -> show x }
}
- Building one is a call, as for any constructor:
IntLit(1) : Expr<Int>,Showable(42)(it needsShow<Int>). As a function value (list.map xs Showable), it takes its dictionaries along. - In a
matcharm, what the constructor says holds in that arm only: in theIntLitarm ofeval,aisInt, sonis ana. A hidden type is known only by name (babove), with the traits of itswhere; it can't leave the arm (E0705). Match on a value whose type is known (annotate the function):amust be a type variable of the signature, or a known type, for the arm to tell anything about it. - Exhaustiveness knows which constructors a type rules out: a
matchon anExpr<Int>needs noBoolLitarm (and can't have one: E0202). - Only in a
matcharm of its own (E0215): not in alet, a parameter or an alternative of|. Neither.fieldnor..basework on such a constructor, and its type can't@derive(write the impl). The type's parameters must all be types (not effect rows or type constructors: E0214). - Use it for typed syntax trees, values that carry their traits (
List<Showable>), and actor protocols whose requests say the type of their reply:Ask(Request<r>, Subject<r>) -> Msg, soask server (GetAge id)returns anInt(tests/run/gadts.lse).
Values are immutable. Mutable state lives in a region (below) or in an actor.
Functions and inference
Signatures:
- A definition's parameters follow
::(ADR 0062):fn add :: a: Int b: Int -> Int { a + b }. A lambda has no name and no:::fn x { x + 1 }. A parameterless function isfn main :: -> () / <io>, andfn() -> Tisfn(()) -> T: calling it isf (). - A
pub fnmust have a complete signature: parameter types, result type, and effect row. - Private functions and lambdas are inferred (Hindley–Milner). Hover and inlay hints in the editor show the result.
- Local
lets are not generalized.
Calls may pass arguments by label (ADR 0062): a parameter declared ~width at the definition is filled by ~width: 2.0 (or the ~width pun) at the call, in any order; unlabelled arguments fill the unlabelled slots in order. A function is curried: applying it to fewer arguments than its arrow takes is the function of the rest. use's callback is the final, unlabelled argument: use v <- f ~when: cond x is f ~when: cond x (fn v { rest }).
Tail calls are guaranteed to run in constant stack, whether the callee is the function itself, another function, or a closure. Recursion is the way to loop.
Tail recursion modulo cons (ADR 0039): a function whose recursive call's result goes straight into a constructor or tuple it returns, as [f x, ..map rest f] does, also runs in constant stack. The constructor is built first, with a hole that the recursive call fills. That covers std's map, filter, append, zip and zip_with, and functions of your own of that shape: one or more constructors around the call, each in a field of the next, with nothing else between the call and the return. It needs the recursive result in the same field everywhere in the function; mutual recursion and n + f x still use the stack.
In-place updates (ADR 0040): when a function matches a value it holds the only reference to, the native backend reuses the value's cells for the cells the function builds, instead of freeing one and allocating another. That works for constructors, tuples and record updates (State(..s, count: n) updates s's cell), and a function may hand a cell to a function it calls that builds one of the same size. Shared values are copied, so this never changes results.
@fip ("fully in place") makes it a promise the compiler checks: every cell the function builds must reuse one it matched, of the same size, and it may call only functions that allocate nothing (inferred: they need no annotation). Closures, calls of function values, effects and externs that allocate are refused, with E0901 pointing at the expression. Int arithmetic is allowed, though a result beyond 62 bits is allocated (as in Koka). The promise holds when the function's arguments are unique; a shared argument is copied. Tail recursion modulo cons doesn't apply to an @fip function (its context would be an allocation).
type Tree { Leaf, Node(Tree, Int, Tree) }
@fip
fn mirror :: t: Tree -> Tree
{
match t { Leaf -> Leaf, Node(l, k, r) -> Node(mirror r, k, mirror l) }
}
fn sum_to :: n: Int acc: Int -> Int
{
if n == 0
{
acc
}
else
{
sum_to (n - 1) (acc + n)
}
}
Early return (ADR 0037): return e leaves the enclosing named function with e, and return alone with ().
emust have the function's result type.return eitself never produces a value (its type isNever), so it fits anywhere:let x = if ok { 1 } else { return 0 }.- It works from the function's blocks,
ifs andmatcharms, and from inside ausecallback or adefer,handleorregionbody. From those, it leaves through the code in between:defercleanups run, and ahandle'sreturnclause doesn't. - A
usecallback canreturnonly if the function given it accepts the callback's effects (fn(a) -> b / <e>), so the return can pass through it. Like a handler (ADR 0010), the callback can't outlive theuse: returning or storing it is an error. - It can't leave from a lambda, a capture (
f _), a handler clause or adefercleanup (E0119): those may run after the function returned. return f xis a tail call.
fn first_admin :: users: List<User> -> Option<User>
{
{
use u <- list.each users
if u.admin
{
return Some(u)
}
}
None
}
Sugar for calls, as in Gleam (ADR 0023):
- Pipes:
x |> f yisf x y, andx |> fisf x. To pipe into another argument, mark it with_:x |> f y _isf y x, andx |> f ~label: _works too. The left side is evaluated first. - Captures: a call with a
_argument is a function of that argument:add 1 _isfn v { add 1 v }, as inlist.map xs (add 1 _). The callee and the other arguments are evaluated each time the function is called. A call has at most one_(E0116). use:use a <- f xpasses the rest of the block tofas its last argument:f x (fn a { rest }).
Pattern matching
match arms may use:
- constructor patterns, positional or labelled (
Rect(width: w, ..)); - literals, tuples, and list patterns (
[],[x, ..rest]); - or-patterns (
A | B),asbindings, and guards (if cond).
Exhaustiveness: a match must be exhaustive (E0301). Unreachable arms are warnings. A let pattern must be irrefutable. A type with no constructors — type T { } or bodyless type T — is empty, and matches with no arms (ADR 0059); @builtin types (Int, String) are inhabited by the runtime and stay non-empty.
fn describe :: xs: List<Int> -> String
{
match xs
{ [] -> "empty"
, [x] if x < 0 -> "one negative"
, [_] -> "one"
, [_, ..rest] -> show (1 + list.length rest) <> " items"
}
}
Errors
Errors are values (ADR 0024). A function that can fail returns Result<a, e> from the prelude, Ok(value) or Error(reason), and its caller matches on it:
Result: a failure the caller should handle, with its reason. The reason is aStringfor a message, or a sum type when callers branch on it.Option: a value that may be absent without that being a failure.Bool: a predicate.- A panic: a bug. It stops the actor, and it is not part of the function's type.
- An effect: when the handler, chosen by the caller, decides what failing means.
Chaining: use v <- result.try r continues with v on Ok, and returns the Error otherwise. std/result also has map, map_error, replace_error, flatten, unwrap_or, unwrap_or_else, expect, to_option, all and values, and option.to_result turns absence into an error.
Combining: list.try_map xs f maps while f succeeds and stops at the first Error. result.map2 a b f and option.map2 combine two values, result.or a b and option.or take the first that worked (lazy_or computes the fallback only if needed), and list.flat_map, zip, unzip and zip_with work on lists.
No monad hierarchy, no symbolic operators (ADR 0026). The standard library has no Functor or Monad trait, and no <$>, >>= or <|>. Effects cover what Haskell does with monads (state, configuration, logging, early exit, nondeterminism), use replaces do, and each type has named functions.
fn port :: text: String -> Result<Int, String>
{
use n <- result.try (string.to_int text)
if n > 0 && n < 65536
{
Ok(n)
}
else
{
Error("out of range: " <> show n)
}
}
Traits
Declaring and implementing:
- A trait has one or more type parameters.
- An impl gives each parameter a named type applied to distinct type variables, or a tuple of distinct type variables:
impl Show<List<a>>,impl Convert<Int, String>,impl Eq<(a, b)>(ADR 0018 Rev. 1). - An impl lives in the trait's module or in the module of one of its named types (coherence); a tuple has no module. There is at most one impl per trait and head types.
- The prelude gives
()and tuples of up to 12 elementsEq,Ord,Show,Debug,HashandDefault, element by element. - Constraints are written
where Show<a>,where Convert<a, b>. - Trait methods are called like functions, and the instance is chosen by type.
trait Describe<a>
{
fn describe :: x: a -> String
}
impl Describe<Bool>
{
fn describe :: b
{
if b
{
"yes"
}
else
{
"no"
}
}
}
fn twice :: x: a -> String where Describe<a>
{
describe x <> describe x
}
Operators are trait methods: == and != use Eq; <, >, <= and >= use Ord; +, -, *, /, % and unary - use Num; <> uses Semigroup (ADR 0027), whose method is append. The prelude implements Semigroup for String, List and Bytes (one value, then the other) and for Order, where <> breaks ties: compare a.last b.last <> compare a.first b.first compares by last name, then first name. Both sides of <> have one type, so "total: " <> 3 is an error: write "total: {3}".
String interpolation (ADR 0034): in a string literal, {e} is show e and {e:?} is debug e, with the prelude's Show and Debug. A hole holds any expression; the parts are joined in one allocation. \{ and \} are literal braces.
fn summary :: name: String xs: List<Int> -> String
{
"{name} has {list.length xs} items: {xs:?}"
}
Several parameters relate types (ADR 0018). Every argument must be known where a method is called, from the arguments, the expected type or an annotation: one parameter is never inferred from another. (A type the impl chooses is an associated type, below.)
trait Convert<a, b>
{
fn convert :: x: a -> b
}
impl Convert<Bool, Int>
{
fn convert :: b
{
if b
{
1
}
else
{
0
}
}
}
impl Convert<List<a>, List<b>> where Convert<a, b>
{
fn convert :: xs
{
list.map xs convert
}
}
fn bits :: -> List<Int>
{
convert [True, False]
} // Convert<List<Bool>, List<Int>>
fn unknown :: -> String
{
show (convert True)
} // E0403: the result type is unknown
So each method must mention every parameter of its trait, and each variable of a where clause must appear in the function's type.
Type constructors as parameters. A type variable may stand for a type constructor and be applied: f<a>. A named type with its last arguments left out is a type constructor: List, Result<a>.
trait Functor<f>
{
fn map :: x: f<a> g: fn(a) -> b / <e> -> f<b> / <e>
}
impl Functor<Option>
{
fn map :: o g
{
match o { Some(x) -> Some(g x), None -> None }
}
}
fn double_all :: x: f<Int> -> f<Int> where Functor<f>
{
map x fn n { n * 2 }
}
- Kinds say what a type expects:
IntandList<Int>areType, andListandResult<a>areType -> Type. They are inferred, never written, and checked (E0213). - Arguments are left out from the end only. So
Result<a>(value type first) gives an impl over the error type. - A type variable is applied to types only:
t<List>is an error. - Effects: a method that accepts effectful functions says so with a row variable, as
mapdoes with/ <e>. Each call then performs the effects of the function it is given.
Associated types (ADR 0047): a trait may name types each impl chooses. A projection names one, applied to the trait's arguments: Elem<c> is the Elem of c's impl.
trait Container<c>
{
type Elem
fn first :: c: c -> Option<Elem<c>>
}
impl Container<List<a>>
{
type Elem = a
fn first :: c
{
match c { [x, ..] -> Some(x), [] -> None }
}
}
fn describe :: c: c -> String where Container<c>, Show<Elem<c>>
{
"first: {first c}"
}
- Defining. Every impl defines each associated type of its trait exactly once (E0406, E0407), and the trait defines none (E0120). A definition uses the impl's type variables (and its own parameters), and may itself be a projection on them:
type Elem = Elem<c>inimpl Container<Nested<c>> where Container<c>. A projection on anything else could be computed forever (E0415). - Using.
Elem<List<Int>>isInt: a projection on a named type is computed from its impl. A projection on a type variable needs the trait in thewhereclause (E0402), and stays as it is:Elem<c>is a type of its own, like a type variable. It does not tell whatcis, so a variable that appears only inside projections is an error (E0403). - Bindings say what a projection is, in a
whereclause:fn total :: c: c -> Int where Container<c, Elem = Int>. In the bodyElem<c>isInt, and every call must agree. A binding may be to a type variable (Container<c, Elem = e>, Show<e>), whichcthen determines. A constructor's bindings hold in the arms that match it (ADR 0041). Bindings that contradict each other, refer to themselves, or contradict an impl are errors (E0416). - Inference waits for a projection's arguments: in
let x: Option<Int> = first c,Elem<c> = Intis decided oncecis known. An unannotated function keeps what is left as part of its type:fn(a) -> Option<Int> where Container<a, Elem = Int>. Amatcharm's knowledge of a type (ADR 0041) is used only in that arm. What nothing decides needs an annotation (E0403). - Own parameters.
type Mapped<x>takes parameters of its own, written after the trait's:Mapped<c, x>. They are types (not type constructors), and a projection is always fully applied. A binding of one quantifies them:where Mappable<c, Mapped<y> = List<y>>says mappingcgives a list whateveryis. Every call must satisfy it for everyy, and its parameters may not reuse the signature's names (E0416). - Not allowed: as a constructor's index (E0214, ADR 0041), and in
@derivabletraits (E0412). Sendlooks through projections:Subject<Elem<c>>needswhere Send<Elem<c>>unlesscis known.
Deriving: @derive Trait ... on a type implements traits marked @derivable. The prelude's are Eq, Ord, Show (for display), Debug (Rust-like, with quoted strings), Hash and Default. A derived impl requires the trait of the type's parameters, and every field's type must implement it.
Your own derivable traits (ADR 0019) name a derive function. It receives the value seen through its constructor, with each field already converted by the trait's method:
@derivable count_nodes
trait Size<a>
{
fn size :: x: a -> Int
}
fn count_nodes :: c: Constructor<Int> -> Int
{
list.fold c.fields 1 fn n f { n + f.value }
}
impl Size<Int>
{
fn size :: _
{
1
}
}
@derive Size
pub type Tree { Leaf, Node(Tree, Int, Tree) }
Constructor(name, index, fields)andField(label, value)come from the prelude.labelis""for positional fields.- The trait has one parameter and one method
fn m :: x: a -> R, whereRhas no type variables and the method has no effects. - The derive function has type
fn(Constructor<R>) -> R, is total, and is in scope where the trait is declared. - Elsewhere: derive a trait of another module with
@derive module.Trait.
Effects
Every function type says which effects a call may perform. The row after / lists them, and an omitted row means total.
effect log
{
fn log :: message: String -> ()
}
effect fail
{
final ctl fail :: reason: String -> Never
}
effect gen
{
ctl yield :: x: Int -> ()
}
Four kinds of operation:
fn: the handler's clause returns the operation's result. Use it for logging, configuration and dependency injection.final ctl: the clause's result replaces the whole handled computation, which is abandoned. Use it for exceptions and early exit.ctl: the clause receivesresume, a one-shot continuation of the rest of the handled computation. Use it for generators and async-style code. Callingresumetwice panics, and so does calling it after its handler finished.multi ctl: the same, butresumemay be called several times; each call runs a copy of the rest of the computation. Use it for nondeterminism and backtracking (ADR 0017):
effect amb { multi ctl choose :: -> Bool }
fn all :: action: fn() -> a / <amb | e> -> List<a> / <e> { handle { [action ()] } with { choose -> list.append (resume True) (resume False) } }
Copies share references (`Ref`); a `defer` cleanup runs once per copy that leaves its scope. A continuation that holds another handler with `ctl` operations cannot be resumed, nor can one whose handler's body is running.
**Handlers** remove an effect from the row:
```louise
fn with_prefix ::
prefix: String
action: fn() -> a / <log, io | e>
-> a / <io | e>
{
handle
{
action ()
}
with
{ log m -> io.println (prefix <> m) }
}
fn collect :: action: fn() -> () / <gen | e> -> List<Int> / <e>
{
handle
{
action ()
}
with
{ yield x -> [x, ..resume ()], return _ -> [] }
}
pub fn main :: -> () / <io>
{
use <- with_prefix "[app] "
log "starting"
}
Handlers are lexically scoped (ADR 0010). An operation goes to the handler visible where it is written:
- inside
handle { ... }, the operation goes to that handler; - in a function whose type lists the effect, it goes to the handler the caller provides;
- a library that installs its own handler never catches its callbacks' operations by accident.
Consequences:
- A function that calls a callback inside its own handler must declare the callback's type with that effect, as
with_prefixandcollectdo above. Otherwise the compiler reports E0703 and explains what to write. - A closure cannot outlive a handler it uses (E0703).
Row variables: e, e1, and so on stand for "whatever else the caller allows". A callee needs only the effects it performs, so a callback with fewer effects than its caller is fine.
Effect aliases name a set of effects once (ADR 0044):
pub effect alias app = proc, random, io, ffi
fn serve :: -> () / <app>
{
io.println "serving"
}
fn with_store :: db: Db action: fn() -> a / <users, app | e> -> a / <app | e>
{
action ()
}
A row may name an alias where a label goes — <app> is <proc, random, io, ffi>: the alias expands to its members at name resolution, so unification, handlers and the dead-member warning (W0501) all see the expanded row. Members may be applied effects (state<Int>) and other aliases, expanding transitively; duplicates collapse. An alias takes no type parameters and may not refer to itself (E0122). A pub alias is imported like a type: import app/web.{type app}.
Built-in effects:
io(console);ffi(foreign calls);proc(actors);allocandst(references, handled byregion).
Regions and references
Mutable references exist only inside a region.
ref.newcreates one,ref.getandref.setuse it.- Neither the region's value nor anything outside it may hold a reference (E0701).
- When the region ends, its references are cleared, so reference cycles cannot leak.
fn count_positive :: xs: List<Int> -> Int
{
region
{
let n = ref.new 0
list.each
xs
fn x
{
if x > 0
{
ref.set n (ref.get n + 1)
}
else
{
()
}
}
ref.get n
}
}
Cleanups: defer
defer expr runs expr when the rest of the enclosing block is left, however it is left: normally, by a final ctl operation, by a panic, when the actor is killed, or when a ctl handler finishes without resuming the code (ADR 0016).
fn report :: xs: List<Int> -> Int / <io>
{
io.println "start"
defer io.println "done"
list.length xs
}
- The block's value is the value of what follows the
defer. Several cleanups run in reverse order. - A cleanup has type
(). It may useio,ffiand references, and may panic. Effects with operations (user effects,proc,clock,randomandfs) are rejected (E0506); the real fs root also takes the I/O blocking-pool suspension path, which is forbidden during cleanup. - A cleanup that panics replaces the unwinding in progress. A kill is not delayed by cleanups: a cleanup still running at the actor's next preemption point, or that waits, is cut short there.
HTML literals
An expression starting with <tag is an HTML literal of type Element<msg>; Html is Element<Never>.
Children are elements, lists of elements, strings, or any other value with Show, which is shown. Text is escaped when rendered (<td>{user.age}</td>).
Attributes are strings, Ints, Bools (boolean attributes, present iff true), or Option<String>s (None leaves the attribute out).
Components: an Uppercase or dotted tag calls a function: <Card title="x">...</Card> is card(title: "x", children: [...]) — a component call is constructor-like: its props fill the component's parameters by name (ADR 0061).
Rendering: html.render produces the markup.
fn card :: title: String children: List<Element<msg>> -> Element<msg>
{
<section class="card"><h2>{title}</h2>{children}</section>
}
fn page :: names: List<String> -> Html
{
<Card title="Team">
<ul>{list.map names fn n { <li>{n}</li> }}</ul>
</Card>
}
Tagged templates
A value followed directly by a backtick literal is a tagged template (ADR 0048): tag is called with the literal's std/template.Template — its text and the values of its {expr} holes ({e:?} shows with Debug; escapes are a string's, plus \`). Holes are converted by their type as in HTML literals: Strings and values with Show become text the templater escapes, Elements (and lists of them) embed as is. A templater is any function from a Template, so libraries can add their own (CSS, SQL, …).
std/template's own three tags are different: they are compiled syntax, not functions (ADR 0057). The compiler lowers the template to the same tree an HTML literal produces, so holes are typed by position (a Bool attribute is a flag, an Option<String> is absent for None), a malformed template is a compile error pointing at the line, and a rendered page needs no tree at run time:
pug: the indentation-based shorthand —.cardand#idaredivs, attributes go in parentheses,|prefixes a text line,//comments, a hole alone on a line embeds its element, and an uppercase tag calls a component, as in a literal.html: the markup as written, with holes escaped or embedded.xml: the same, as an opaqueXml(template.render_xmlgives the markup).
import std/template.{pug}
fn card :: title: String body: Html -> Html
{
pug`
.card
h2 {title}
{body}
`
}
The three are syntax, not values: let t = pug is an error (E0605). Editors highlight a template's contents by its tag (pug, html, xml).
Actors
std/process provides lightweight processes that share nothing:
spawnstarts one;spawn_linkandspawn_monitoralso link or monitor it, in one step (with several scheduler threads, a separatelinkormonitormay come after the child already stopped);- a
Subject<msg>is a typed mailbox address (subject,send,receive,receive_forever); link,monitor,trap_exitsandkillfollow Erlang's exit rules;demonitor pid downends the monitor whoseDownsubject isdown: noDownarrives on it once it returns (one already there stays;demonitor_flushalso drops it);unlink pidremoves a link: once it returns, neither side's exit reaches the other through it, until a newlink(anExitSignalalready in the mailbox stays). Across nodes too: an exit that crosses the unlink is ignored.
Scheduling is preemptive: no actor can hog the scheduler.
What an actor body can do: its type is fn() -> () / <proc, clock, random, fs, net, io, ffi>. Each actor gets the runtime's handlers of proc, clock, random, fs and net; a handler around spawn (random.with_seed or a fake filesystem, say) does not follow it. A named function passed as a body (or as actor.start's step function) must declare that whole row; a lambda calling it need not. See capabilities.
What can be sent is decided by Send, a trait the compiler implements for every type from its structure (ADR 0004, Revision 6):
- A
Refnever is: it belongs to its region. AResource<k>is when its kindkis marked@thread_safe. - Values, tuples and built-in types (
Int,String,Bytes,Array<a>, …) are when what they hold is. A type is when every field of every constructor is. Subjects always are: they hold a pid and a tag. - A constructor that hides a type (ADR 0041) and stores a value of it needs
where Send<b>for it. process.sendrequiresSendof the message, andactor.startof the initial state. So does generic code that sends: an annotated function writeswhere Send<a>(E0402 otherwise), and an unannotated one infers it.Sendcannot be implemented (E0413), and costs nothing at run time.
fn relay :: to: Subject<m> message: m -> () / <proc> where Send<m>
{
process.send to message
}
What can cross hosts is decided by Wire, a stricter sibling of Send, for distribution (ADR 0072): dist.name's message type, dist.spawn_on's argument and a @remote function's need it.
- The built-in values (
Int,Float,String,Bytes,U64,Dec,Pid,Array<a>),Never, tuples, and a type whose fields are, given the arguments of the parameters they store (a phantom parameter needs nothing); aSubject<m>whenmis. - Never a function, a
Ref, aResource(even@thread_safe), aDynamic, aBuilderor another built-in or foreign abstract type, nor a type whose constructor stores a dictionary or hides or refines a type (ADR 0041), nor a nested type (Nest<a> { Nil, Cons(a, Nest<(a, a)>) }). The error (E0706) names the field. - Unlike
Send, it has a dictionary: the type's description, sowhere Wire<a>costs a parameter. A givenWire<a>impliesSend<a>. It cannot be implemented (E0413).
Functions say whether they can be sent: send fn(a) -> b is a function whose captures can be.
- A closure that is sent (spawned, passed as a
send fn, sent as a message) may capture only sendable values, and no handler of where it was written:process.spawn fn { process.send reply n }is fine, a closure capturing aRefis an error (E0704). - A partial application is such a closure: it captures its arguments, so
greet prefixis asend fnwhenprefixcan be sent (issue #325). spawn's body,actor.start's handler,supervisor.Child's start function andstd/http's handler aresend fn.- A plain
fnparameter accepts any function, so the body cannot send it: writesend fnto. A plainfnin a result or a field holds any function, so a type with one is notSend. - Which check fires when: the compiler's is the one you meet — a bad send does not compile (E0704). What
@externcode hides behind a sendable signature slips past it, so the runtime walks every message as a backstop and refuses the same values; that failure is a panic in the sending actor, never a process abort (see the runtime ABI).
Higher-level modules:
std/actor: gen_server-style actors (start,call,cast);std/supervisor: restarts children that crash (OneForOne,OneForAll, with a restart limit).
Panics: a panic crashes only its actor ("let it crash"). Recoverable errors use Result or an effect.
For the optimiser (ADR 0043), a crash is observable — a monitor sees its message — so a pipeline stage that can panic is never fused, and a run that finishes normally computes the same value with or without optimisation, on both back ends. Divergence is imprecise, though: a pure stage that loops forever hangs fused or not, and length (map xs f) never runs f — a stage that is pure, cannot panic, and is only dropped.
import std/process.{type proc}
pub fn main :: -> () / <io, proc>
{
let replies = process.subject ()
process.spawn fn { process.send replies (6 * 7) }
io.println (show (process.receive_forever replies))
}
Foreign functions and native dependencies
An @extern c "symbol" function without a body calls C (ADR 0005):
- the C side uses
louise_rt.h's convention: borrowed arguments, an owned result; blockingruns the call on a thread pool while the actor waits:blocking cpu(what plainblockingmeans) for calls that keep a core busy, such as hashing, on a small pool (LOUISE_BLOCKING_CPU_THREADS, default half the cores, at most 4);blocking iofor calls that mostly wait, on a larger one (LOUISE_BLOCKING_IO_THREADS, default 16).std/runtime.blocking_stats ()tells how many calls run and wait on each (ADR 0005, Revision 2);Resource<t>(std/ffi) wraps a foreign pointer with a finalizer. Mark the kind typetwith@thread_safewhen the C side may be used from any thread; only then may the resource be sent to another actor (the C side must also create it withthread_safe).- A parameter of function type is a callback C may call during the call (ADR 0015). It runs in the calling actor, may perform
<ffi>at most, and ablockingextern cannot take one (E0113). If it panics, the actor stops once the C call returns. louise bindgen header.h --lse src/lib.lse --c csrc/bindings.cgenerates the declarations and their C shim for a header's simple functions, and reports what it skips.examples/qsortbinds a C library this way, with a comparator.
Native dependencies are declared in louise.toml and built by louise build, in the package's build/ directory with the generated C (ADR 0025); the executable is build/<package name> unless -o says otherwise:
[dependencies]
argon2 = { path = "../packages/argon2" }
[native.mylib]
kind = "c" # c | static | pkg-config | cargo
sources = ["c/*.c"]
include = ["c"]
Supervised programs
A package's louise.toml may say how the runtime supervises its main (ADR 0060):
[application]
restart = "transient" # permanent | transient | temporary
intensity = 5 # at most 5 restarts...
period_ms = 60000 # ...within 60 s, else exit non-zero
shutdown_timeout_ms = 10000 # on a signal, main's time to stop
signals = ["term", "int"] # term | int | hup: start a shutdown
- Every key is optional; the values above are the defaults. Without the section,
mainruns once, as always. - With it,
louise runandlouise buildrunmain(which must bepub) undersupervisor.application:- a crash restarts
main(not fortemporary), unless that makes more thanintensityrestarts withinperiod_ms; then the program ends with the panic; mainreturning ends the program with status 0;- on one of
signals,mainis stopped (process.stop): one that traps exits getsShutdownto clean up, such as by stoppinghttp.serve_until. It is killed aftershutdown_timeout_ms, and the program exits 0.
- a crash restarts
louise checkreports an invalid section;louise testignores it.- Without
[application], a program can subscribe to signals itself (os.signals). Unsubscribed, SIGTERM, SIGINT and SIGHUP end it at once with status 128 + the signal's number, even as PID 1 in a container.
Distributed programs
A distributed program's louise.toml holds the policy every node shares (ADR 0072):
[cluster]
name = "orders" # required: nodes of another cluster are refused
listen = "0.0.0.0:4370" # where nodes listen; LOUISE_LISTEN overrides it
heartbeat_ms = 1000
node_down_after_ms = 10000 # a peer silent this long is down
max_message_bytes = 8388608 # the largest message payload a node accepts
outbound_queue_bytes = 67108864 # message bytes queued per peer before senders wait
max_peers = 256 # connections a node keeps before it refuses a stranger
discovery = "seeds" # seeds | mesh: also dial the nodes peers list
- The other keys are optional; the values above are the defaults.
namehas a node name's syntax (a lowercase DNS name);listenis an IP address and a port; the delays are at most a day,heartbeat_msbelownode_down_after_ms;max_message_bytesis between 1 KiB and 64 MiB; the queue counts each message's 36-byte header with its payload and must hold one message ofmax_message_bytes.max_peersis between 1 and 4096: a node with that many connections refuses a node that is not one of its seeds. Seeds count, and are never refused. - A node's own name, certificates and seeds are not policy: each instance gets them from its environment (
dist.from_env:LOUISE_NODE,LOUISE_CERT,LOUISE_KEY,LOUISE_CA, and optionallyLOUISE_LISTEN,LOUISE_ADVERTISEandLOUISE_SEEDS; the tutorial has the table).LOUISE_DISCOVERY(seedsormesh) overridesdiscovery.LOUISE_CLUSTERmay repeatnamebut not change it, anddist.startrefuses aConfigof another cluster. Without the section,LOUISE_CLUSTERis required anddist.config's defaults apply. - Nodes always authenticate each other with mutual TLS:
authmay only say"mtls". - Discovery. With
discovery = "seeds", a node dials its seeds and the nodesdist.connectnames, again whenever their connection is lost. With"mesh", nodes that both discover also tell each other which nodes are up, and where to dial them, and dial those they did not know: a full mesh from a few seeds. A node's address isLOUISE_ADVERTISE(dist.Config'sadvertise), else its listen address unless that is every interface (0.0.0.0,::); a node with neither is dialed by no one, and dials. An address a peer gives is a hint: TLS checks the name, so a wrong one costs a refused dial, and the addresses different peers give are tried in turn. A discovered node is dialed again while a peer lists it, and forgotten after10 × node_down_after_msonce none does; a node knows at mostmax_peersdiscovered nodes, shared among the peers that list them so that none takes them all, and is refused by a full node as any stranger is (docs/wire-format.md). - The compiler checks the section (
louise checkreports it) and builds it into the program as a constant, whichstd/distreads (std/wire.cluster,Nonewithout the section). Only a program that reads it carries it. A dependency's[cluster]is checked but not used;louise testkeeps the root package's. - Across nodes,
std/process'ssend,link,monitor,killandstoptake another node's subjects and pids as local ones. Messages are delivered at most once, in order per sender and receiver with exits andDowns; a lost node isCrashed("noconnection")on every link and monitor across it. Distribution is native only: in the interpreter,std/distfails with "distribution needs --native". It needs a security review before production use: an authenticated node is trusted as local code (ADR 0072, Trust).examples/clusteris a two-node program.
Dependencies
A package's louise.toml lists the packages it uses, from a directory or from a git repository (ADR 0020):
[package]
name = "app"
[dependencies]
argon2 = { path = "../argon2" }
json = { git = "https://example.com/json.git", tag = "v1.2.0" }
http = { git = "https://example.com/http.git", branch = "main" }
util = { git = "https://example.com/util.git", rev = "4f2a9c1" }
log = { git = "https://example.com/log.git" } # the default branch
uuid = { git = "https://example.com/louise.git", tag = "v0.2.0", subdir = "packages/uuid" }
Modules: a dependency's src/lib.lse is imported by the dependency's name (import json), and its other modules by json/<path>. Dependencies of dependencies are included.
Compiler version: [package] louise names the compilers that can build the package — one comparison, >=, >, <=, < or = and a version, or a bare x.y.z for =:
[package]
name = "postgres"
louise = ">= 0.1.1"
A compiler that does not satisfy it stops with an error naming the package, the requirement and itself; the language server shows it on the requirement in louise.toml. Compilers before 0.1.1 do not know the key and ignore it.
Git dependencies:
louisefetches them with thegitcommand, so your SSH keys and credential helpers apply.- The package's
louise.tomlis at the repository's top directory, or in the directorysubdirnames (a relative path, without..), for a repository holding several packages. - A package reached twice in one repository, by
subdirand by apathfrom another of its packages, is one package if both are the same commit, and a version conflict otherwise. - The cache is
$LOUISE_HOME/git(default~/.cache/louise/git). Deleting it is safe. - Native dependencies (
[native.*]) of a git dependency are built like any other.
The lockfile:
- The first build records the commit of every git dependency, transitive ones included, in
louise.lock. Commit this file. - Later builds use the recorded commits, even after a branch or tag moves.
- Changing a dependency's URL or reference in a manifest re-resolves that dependency.
| Command or flag | Effect |
|---|---|
louise update | Resolve every git dependency again and rewrite the lockfile. |
louise update json | Resolve only json again. |
--locked | Fail instead of changing the lockfile (for CI): louise test --native --locked. |
--offline | Never fetch; use what is in the cache. |
One version of each package. A build holds one commit per repository. If two packages ask for different commits of the same repository, for example a tag and a branch that has moved on, the build stops and names both requirements. Make them agree. The same applies to two different packages with the same dependency name.
Warnings are the root package's own. louise check, run, build and test print the warnings of the package being worked on; a dependency's (and std's) are summarized in a note with their count, not shown — --deps-warnings shows them. Errors in a dependency still stop the build. louise check --deny-warnings fails on warnings, which CI uses to keep a package clean.
Only the std a program reaches is checked (ADR 0074). Every command checks the std modules that the program's modules import, directly or through other std modules, plus the prelude. Syntax that needs a std module reaches it without an import: an HTML literal (std/html), a template literal (std/template), region (std/ref) and @remote (std/dist/remote). louise check --all-std checks all of std.
Tests
@test marks a test function, next to the code or under test/. @should_panic "text" expects a panic.
louise testruns them in the interpreter, each in isolation. In a package it runs the package's own tests, insrc/andtest/, and not its dependencies'.- They run in parallel, one per core (
--jobs Nto choose), and report in order, as a serial run would. A test that callsos.exitfails; the others still run. - A test that passed is not run again while nothing it depends on changed: what its module imports, the environment variables and files it read. It reports
ok (cached);--no-cache(orLOUISE_TEST_CACHE=off) runs everything (ADR 0061). louise test --watchruns them again whenever a source changes: only the tests a change can affect.louise test --filter textruns the tests whosemodule.namecontainstext;louise test src/util.lseruns the tests of one module only.- Interpreted tests run unoptimised;
--optruns them optimised, as native code is. louise test --nativecompiles them; packages with native dependencies need it. An unchanged test executable is reused.std/testprovidesassertandassert_equal.- Test-only code (ADR 0064):
@test import mimportsmfor tests only. Only@testfunctions may use it (E0126), and it can name a module undertest/. A program build (build,run) leaves out every@testfunction and@test import, so what only tests use is neither checked nor compiled;louise checkandlouise testcheck it. Unused imports (W0102) are reported only where the tests are seen. [dev-dependencies]inlouise.tomlare resolved and locked like[dependencies], but loaded only bytest,checkand the language server: a program build leaves them out. A dependency's own dev-dependencies do not count.- Randomized tests: the
genpackage (packages/gen) has generators (gen), fake data (gen/fake) and property checks that shrink a failing case (gen/check).
@test
fn sums ::
{
assert_equal (sum_to 4 0) 10
}
The standard library
| Module | Contents |
|---|---|
std/io | println, print, eprintln |
std/string | length, join, concat, split, chars, trim, to_lower, to_int (a Result), starts_with, ... |
std/bytes | Bytes: length, get, slice, concat, UTF-8 conversions, and a Builder that appends in place when unique (ADR 0012) |
std/list, std/option, std/result | Lists, optional values and results, and their combinators (Errors) |
std/iter | Lazy iterators (`iter.range 1 n |
std/array | Array<a>: from_list, to_list, length, get, set, push, slice, map, fold; set and push update a unique array in place (ADR 0014) |
std/dict | Persistent ordered maps |
std/collection | Collection<c>, with the element type Elem<c> (ADR 0047), for List, Array, Dict ((k, v)) and Bytes (Int): size, fold, to_list, iter, and the generic is_empty, count, contains and sum |
std/ref | References in regions |
std/html | Element, Html, text, raw, render, escape |
std/template | Tagged templates (ADR 0048): Template and Hole for user-defined templaters, and the compiled pug, html and xml tags (ADR 0057) |
std/process, std/actor, std/supervisor | Actors and OTP: process.stop and the Shutdown reason; supervisors with a restart window (Spec), child kinds (Permanent, Transient, Temporary) and an ordered shutdown; supervisor.application, which [application] uses (ADR 0060) |
std/net, std/http | TCP on Bytes, and an HTTP/1.1 server (native programs): resolve/listen/connect use the net opening root; accepted socket I/O and serving an existing listener use handle-mediated io (capabilities). HTTP has keep-alive and chunked request bodies. http.serve_with takes Settings: idle, head and write timeouts, a request body limit (413 beyond it) with larger ones under chosen path prefixes (large_bodies, ADR 0012, Revision 5), and a limit on open connections; start from Settings(..http.defaults (), ...). net.peer conn and http.peer req give the client's address, http.client_address req trusted the client's through trusted proxies (ADR 0012, Revision 4) |
std/http/cookie | Cookies (RFC 6265): cookies and cookie read a request's Cookie headers; SetCookie (new's defaults are Path=/, Secure, HttpOnly, SameSite=Lax), to_header, set_cookie and expire build Set-Cookie ones |
std/int, std/float, std/u64 | Bit operations on Int; Float conversions and IEEE 754 bits; U64, unsigned 64-bit integers that wrap (ADR 0035) |
std/dec | Dec, a 128-bit fixed-point decimal for money (18 places, round-half-even, panicking operators, no literals, no implicit Float↔Dec) (ADR 0070) |
std/time | The clock effect, Timestamp, Duration, the UTC calendar, RFC 3339 (ADR 0036) |
std/random, std/prng | The random effect: integers, floats, shuffles, tokens; seeded handlers over SplitMix64 (not for secrets) |
std/os, std/ffi | Environment, process arguments (os.args) and exit (os.exit), OS signals as messages (os.signals), foreign values |
std/runtime | The runtime's state: blocking_stats, the blocking pools' sizes, running and queued calls, for back-pressure |
std/file | The fs effect and whole-file operations (read, read_bytes, write, write_bytes, exists, size, list_dir), natively on the I/O blocking pool (ADRs 0049, 0084) |
std/crypto, std/base64 | SHA-256, HMAC-SHA-256, PBKDF2-HMAC-SHA-256 (over ring), and base64 (ADR 0050) — what SCRAM needs |
std/msgpack | MessagePack: Value, write/read, and the ToMsgPack/FromMsgPack traits with impls for the std types; @derive ToMsgPack works, the decoder derive is ADR 0051 |
std/tls | TLS clients, verified by default, and servers, with mutual TLS (ADR 0038); std/io's Stream trait covers TCP and TLS streams. Only tls.dial additionally opens through net; config secret reads stay separate (capabilities) |
std/test | Assertions |
std/dist | Distribution (ADR 0072; native only): configure and start a node (Config, config, from_env, start, Discovery), connect to one by hand (connect), name a subject for every node (name, register) and find one on another (whereis), typed by Name<m>; start a @remote function on a node (spawn_on, spawn_link_on, spawn_monitor_on, Remote<a>); follow a node's connection (monitor_node, NodeEvent) and every known node's state and counts (peers, Peer); errors as DistError |
std/dist/remote | Remote<a>, a reference to a @remote function, and its key (ADR 0072) |
std/wire | Distribution's internals (ADR 0072), for std/dist: a Wire type's descriptor (describe, describe_none), the program's type definitions table and schema hash, its @remote entries and their dispatcher (entries, Arg, dispatch; docs/wire-format.md), its [cluster] policy (cluster); mostly @intrinsic, not for programs |