Almac language report
ortfero
Almac is a small imperative language for the aldan system.
This report states the rules needed to implement its compiler;
the standard library is written in almac and documented in its
own modules.
1. Lexical rules
- Tokens are separated by blanks, line breaks, comments.
- Letters are a..z and _ only; hex digits are lowercase.
- Reserved words (31):
affine as asm break const
continue defer else enum failure
false final fn for from
guard if import inline into
mod none on raise record
return true union var when
with
- A reserved word where a name goes is an error of its own (reserved word).
- naked is contextual: a keyword only directly after asm.
- const only marks a view slice type (4.2). Constant and type declarations take no keyword (3, 4); type is an ordinary name. A failure's name comes before failure (7.9), a function's before fn (8).
- ... is lexed greedily, distinct from the selector . .
- ! alone opens a failure clause (4.6); != is one token.
- A minus followed by a digit starts a negative literal, followed by another minus a comment, followed by > the arrow before a result type (4.6), otherwise it is subtraction or negation: write x - 5, not x-5.
- integer and hex literals both have type integer; the notation carries no type.
- 'x' is a byte character. 'xy (no closing apostrophe) is a short-string, ending at whitespace or at a closer (comma, ), ], }). The bytes ' " ` ( [ { inside it are errors. The byte after the content decides: 'x' vs 'xy.
- "..." strings have no escapes and cannot hold ". A nonempty literal is const string (a view); "" is string (writable, can birth a slice).
- none converts only to optional pointers; it is also the return value of a no-result function.
2. Declarations and scope
- Declare before use. A function name binds at its signature, before its body, so a body may call itself; a callee must still be defined (or deferred with ...) above its caller, so two functions calling each other defer the lower one.
- Top-level names are module-wide; those before the module's ... separator are exported.
- A function body opens a scope; a nested scope may redefine an outer name for the rest of the body. A compound { } opens no scope of its own for locals, but with/guard bindings last to the end of the enclosing compound.
- The built-in names (4.1, 6.2: the primitive types, integer, length, ram_base, and, or, not) are reserved: no function, variable, constant, type, failure, parameter, local or with binding takes one (reserved name). A record field may.
3. Constants
- n = constexpr, with no keyword; folded at the declaration. So are a record-constant field, an array-constant element and an array size. At module scope no statement can stand, so a name opening a declaration always opens a constant.
- At the prompt n = v assigns when n is a variable and defines a constant otherwise, replacing any other binding of n. t.n = v defines a scoped constant when t is a type; through a variable or a module it assigns.
- There is no type slot. A scalar constant takes its value's type; x as t writes one, converting as 6.6 does. An aggregate literal that cannot say its type takes it as a prefix (3.1, 3.2).
- constexpr: an expression (6.1) over constants — integer, fp, bool, character literals; named constants (n, m.n, t.n); enum variants; ram_base; a type name (its size in bytes, int) — with + - * / mod, unary -, ( ), x as t between scalar types, and the forms and, or, not. No relation, call or other operator. A string, slice or record constant is an operand alone.
- Computed as at run time (6.1-6.3, 6.6): an untyped operand adopts a typed one's type, two typed operands must match, each operation wraps to its type, / and mod signed on int, unsigned on bit types, x / 0 = -1, x mod 0 = x. An expression of untyped operands only stays untyped: it adopts the type it meets later.
- A named constant brings its value and type.
- A type given to a value — a prefix's element, a record field, a scoped constant's type — must admit it; an untyped integer fits any integer type, but an out-of-range value (300 in byte, -1 in word) is rejected, never truncated.
- fn d (address of function d) and an in-place record have no type of their own: only as a record-constant field or an element of an array constant with a prefix slice type. d must already have its final address (imported module, or earlier prompt unit); a function of the current module or an inline one is rejected. fn d alone is not a constant.
3.1 Array constants
- [e, e, ...] binds the name to a const []t slice over elements in the image; never an array. A string constant is the []byte case.
- []t [e, e, ...] writes the element type as a prefix: [] then a type, then the list. A bare [] is the empty list, and [n]t is no prefix.
- Element type: the prefix's element type, else the first element's (untyped integer -> int). Every element must fit. So []byte [27, 91] is a byte table, [27, 91] an int one.
- Elements: scalar constants (a constexpr of bool, integer, fp, char, enum variant or names for them), slice constants (a string in place, or a named string/array constant), record constants (in place or named), and fn d. A record in place and fn d need the prefix: []point [{x: 1}].
- Rejected: empty list, none, nested list [[1]], arrays. Tables of tables are spelled by naming: [a, b].
- Read-only place: index and sub-slice only; no writes, no var/into argument, assignable only to const []t.
3.2 Record constants
- c = rec {f: v, ...}: the type as a prefix (t, m.t), then the record literal of 7.1 with constant values. Left out is zero; a slice field is given. A record literal without a prefix has no type and is rejected.
- Field values: scalar (a constexpr), enum variant, none (optional pointer), string/slice constant (slice field), fn d (function field), record in place or named.
- A type with a non-null pointer, address, array or union field has no constants.
- Read-only place: fields read, with-aliasable, passed by reference to a bare record parameter; no writes, no var/into, no whole copy. Slices read out of it are views.
3.3 Scoped constants
- t.name = v, only for a distinct (from/affine) type t, only in t's own module under t's own name. The value must be admitted by t; type is t.
- Read as t.name or m.t.name (also through an alias of t) as an operand, constant or when label.
- Interface section = public, body = private.
- The namespace is t's alone: no fallback to t's base, to the module, or from b from t.
4. Types
- x as y: transparent alias, same type everywhere (structure included). Two aliases of one target are one type.
- x from y: distinct nominal type, y's representation, compatible only with itself; crossing to/from y or another distinct type needs as. Integer literals still coerce to it; an operator on two values of it yields it. from on a union subtype is rejected.
- x affine y: distinct as from, plus affine (single owner). y is an integer type (int, byte, hword, word, dword) or a distinct/affine type over one.
- x y (bare typename, no marker) is rejected. Structural RHS takes no marker: x record {...}, x enum a | b, x union ..., x [n]t, x []t, x ^t.
- A function type is named through as: x as fn () -> int. x fn ... declares a function (8).
- No keyword opens the declaration: the token after the name tells a type (a marker or a structure) from a constant (=).
- At the prompt record, enum, union and affine after a name always open a type. as, from, [ and ^ also continue an expression (x as int, f from p), so with those the line is a type only when the name is unbound or already a type.
- Markers appear only in the declaration; elsewhere a named type is written bare.
- A named type may refer to itself only through a pointer.
- typename: ident, m.t, u.v or m.u.v (union subtype).
4.1 Basic types
type size align meaning
bool 1 1 logical
byte 1 1 8-bit field, unsigned; the byte
hword 2 2 16-bit field, unsigned
word 4 4 32-bit field, unsigned
int 8 8 signed integer
dword 8 8 64-bit field, unsigned
double 8 8 IEEE-754 double
address 8 8 raw address, non-null
string alias for []byte
integer type of an unconverted literal
- No other unsigned type. The bit types byte, hword, word and dword (RISC-V widths): unsigned ordering, division, mod; bit indexing. byte, hword, word are loaded zero-extended, held zero-extended after every operation, and stored as exactly their own bytes.
- These names are reserved (2).
- address is non-null: shares the zeroed-storage bans and the birth rule.
4.2 Arrays and slices
- [n]t: n a positive int constant; contiguous; aligned as t. []t: {data address, count}, 16 bytes, align 8.
- [n]t converts implicitly to []t (assignment, argument, as).
- const []t is a view: elements read-only, subranges and slices read out of it are views (const []string is const []const string). const applies only to slice types. []t -> const []t implicit; never the reverse (an as of a view yields a view).
- Views are: constants, nonempty string literals, plain parameters (inside their function), anything read out of a read-only place (constant, plain parameter, with alias of one, element of a view), and any slice over a read-only place (subrange, array->slice, byte view). A view cannot go into a []t binding/field/module var, be returned as []t, or passed var/into as []t.
- Element types may not be non-null (^t, address) or contain one; use ^t|none or int.
- Frame rule: a slice over a local array (and anything derived: subranges, byte views, slice locals assigned one, slices through a with alias of a local) may not be returned, stored in a module var, a var/into parameter, or a field reached through a pointer. It may be read, indexed, passed, stored in another local or a field of a local record. Slices over parameters, module storage or heap are free to escape.
4.3 Records
- Fields in order, natural alignment; record aligned to its strictest field. A run of names may share one type.
- Non-null fields (^t, address) are leaves (5.1).
4.4 Pointers
- ^t non-null, ^t|none optional (none = address 0). Both 8 bytes.
- ^t|none: assignment, == / != (none or same base), guard. Nothing else.
- p^ (^t only) is a writable place, even through an immutable parameter or field.
- Owners: ^t, ^t|none, address, affine values.
- Assigning a whole owned binding (local, from/into parameter) moves it: the source dies.
- An optional place not owned outright (field, var parameter) is taken with null: left none.
- A non-optional owner is never extracted from an aggregate slot; borrow it with with / for with.
- Borrow: an owner read from a bare or var parameter, a with / for with binding, or reached through one. Dereferenced, compared, passed bare/var, re-aliased; never stored, returned, moved or consumed.
- Comparing, bare/var arguments, with / for with never consume. Dropping a live owner is allowed. Use after move and double ownership are errors.
- Exclusivity: a place is a variable plus selectors. Two places overlap unless their paths diverge (a.x / a.y, a[0] / a[1]); a[i] with non-literal i overlaps every a[...]. Enforced by the argument rule (8.1) and the with rule.
4.5 Enumerations and unions
- enum a | b | ...: at least one variant, stored as byte, nominally distinct.
- union v1 {fields} | v2 | ...: tag at offset 0, payload after it, sized/aligned to the largest variant.
- u.v is a subtype: size/align of u, tag fixed to v, only v's fields reachable. A u variable exposes no fields until narrowed by guard or when.
- u.v -> u only in argument position (by reference). Reverse conversion, subtype-to-subtype assignment and whole-union assignment are rejected.
- Liftable union (inferred, never declared): every variant has exactly one payload field and the field types are pairwise distinct. Others are just not liftable; no diagnostic at the declaration.
4.6 Function types
- fn (params) [-> ret] [! ...]. No ret = returns nothing. The arrow ends a signature without a result: newlines end nothing, so start fn () cannot take the next declaration's name as its result type.
- The failure clause, ! a | b, names failures (never kinds), |-separated, and is part of the type. A raising value is callable only where its failures are declared or handled.
- ... (the unnamed failure) may close the clause, alone or after names; nothing follows it. Such a type is open, others closed.
- A function value converts to an open type that agrees on params, markers and result, whatever it raises. Never the reverse. A closed type accepts only itself.
- inline and the variadic ... are declaration properties, not part of the type; a variadic param enters the type as []t.
5. Variables
- var/final heads a comma list of vardefs; trailing comma allowed; a run of names shares the type that ends it.
- Module vars live in BSS; locals in the frame; both zero-initialised.
- No variable of a type with a non-null under an array element or union payload, nor a module ^t whose pointee holds a leaf.
5.1 Birth rule
- ^t, address, affine and slice locals start unborn. Born by assignment or an into argument; usable after a birth earlier in the same or an enclosing sequence, until that sequence ends. Conditional birth uses the if expression. An empty slice is "" or a[0:0].
- ^t|none starts as none; only a moved one is dead.
- Death: a moved or from-consumed owner is dead until reassigned, on every following path.
- A record holding any of these (a leaf, at any depth) is born whole: by a record expression (7.1) or as an into argument. While unborn: no use of it or of any part holding a leaf; a leaf-free part is usable.
- A ^rec assigned an address points at an unborn record, born by p^ = {...} or into p^.
- into: the callee births the argument before a normal return. var: the argument is born.
- Untracked: no non-null under an array element or a union payload; a slice there starts empty.
- No unborn-capable local in an on handler.
- Module vars of these types are born for good in setup's outermost sequence, above every use. While a birth pends there: no early return, no call that may reach code defined below. A birth after a raising call only if the fault leaves setup, which then has no on handler. At the prompt the top level is setup, and no birth follows a raising call.
- A module ^t or affine value is used in place: deref, plain argument; never copied, returned, moved or consumed.
5.2 Final variables
- final = write-once var, at module scope or among locals (final and var clauses mix).
- Every final starts unborn; born by assignment to the bare name or an into argument (the only way for a record/array). Field or element writes are not births. Birth is positional as above; in a loop body it is made afresh each iteration. Module finals are born in setup's outermost sequence.
- After birth: assignment, +=, -=, bit store, var argument, second into argument, write through a with alias — all rejected.
- No birth in a for step, a defer, or an on handler. A local final may not be used in a handler.
- A final scalar/record/array/union is read-only. A final slice or pointer cannot be rebound but its elements/pointee stay writable as its type allows. An owned final pointer may still be moved or consumed (its death, never reborn). Module finals are never moved or taken with null. Imported finals are fixed.
6. Expressions
- Postfix: index, subrange, field, deref combine freely; a trailing argument list makes a call.
- a[lo:hi]: slice over the same storage, lo inclusive, hi exclusive; on a bit type a bit field.
- fn atom...: a function value (never a call); the designator must be of function type.
- A type name used as an operand is its size in bytes (int), so heap.claim node passes node's size.
- No bounds checks.
6.1 Precedence (high to low)
postfix call, index, field, deref
cast as
unary -
multiply * / mod
add + -
relation == != < <= > >= (non-associative)
assign = += -= (non-chaining)
- Arithmetic and relational operands must have the same type after implicit conversion; a distinct type matches only itself.
6.2 and, or, not
- and / or are forms (at least one argument, not values): over bool, left-to-right short-circuit, yield bool; over integers, bitwise over all arguments, all evaluated. One family per form; integer arguments share one exact type, an untyped literal adopts it.
- not is an ordinary function: logical on bool, bitwise complement within the operand's width on integers.
- length (x): element count of an array or slice, int.
- ram_base: untyped constant, where target memory starts (0x80000000 on aldan/RISC-V, 0 elsewhere).
- These, plus the primitive types, are the whole built-in vocabulary.
6.3 Arithmetic
- + - * / on integers and double; mod on integers; unary - on integers and double.
- Integers wrap: mod 2^64 (int), mod 2^n (bit types). No overflow failure. On bit types unary - is 0 - x.
- / and mod: signed on int (truncate toward zero, mod takes the dividend's sign), unsigned on bit types.
- x / 0 = -1 (all ones on bit types), x mod 0 = x (RV64). double follows IEEE-754.
6.4 Bit fields
- b[i] (bool) and b[i:j] (bits i..j-1, b's type) on bit types; bit 0 least significant. Out-of-width bits read 0.
- Both are places when b is a place: b[i] = bool, b[i:j] = v (v truncated to the field); other bits unchanged. Bounds evaluated once.
6.5 Relations
- Same type, bool result. double IEEE ordering; int and integer signed; bit types unsigned.
- Pointers: == / != only, same base (^t and ^t|none mutually); a ^t compared against none is an error.
6.6 Conversions
Explicit (x as t):
- integer -> integer: to a narrower bit type keeps its low bits; widening sign-extends from int, zero-extends from byte, hword, word.
- integer <-> double: reads the integer by its family (bit types unsigned); double -> integer truncates toward zero, then to a narrow bit type keeps its low bits.
- any scalar -> bool (non-zero is true).
- [n]t -> []t.
- aggregate or slice -> []byte: byte view of its storage, length = byte size. Needs addressable backing (bare scalar values rejected). Never implicit.
- []byte or [n]byte -> []t: same storage, count = bytes / size of t (partial tail dropped).
- []byte -> scalar: unaligned load of the leading bytes.
- The two conversions out of bytes may not target a type holding a pointer, address or affine value at any depth.
- pointer (either kind) -> address.
- address -> ^t: asserts the typing; t's leaves are unborn (5.1).
- integer -> address: the trusted forge.
- address -> integer.
- ^t -> ^t|none.
- distinct <-> its base, and between distinct types of one representation (no runtime cost beyond the base).
- affine <-> its base (into = forge, out = non-consuming read); never affine <-> affine.
- A conversion of a view yields a view.
- Rejected: cast to a union subtype; a non-null pointer except from address or a same-base ^t; a cast to the operand's own type (an alias counts as the same type; an untyped literal is not yet typed, so 0 as byte is fine). Narrowing is only by guard / when.
Implicit (assignment, argument, comparison):
- integer literal, or an expression of untyped constants only (3), -> the integer type it meets (never address, never affine). Bare, it defaults to int.
- [n]t -> []t where a slice is required.
- none -> ^t|none; ^t -> ^t|none.
- address <-> any pointer (typing assertion only).
- []t -> const []t.
- u.v -> u in argument position.
- Value-to-union lift, arguments only: parameter of a liftable union u, argument not u or a subtype. Variant chosen by exact field type first, then by implicit convertibility (literal -> integer, [n]t -> []t). A bare literal is int first. Zero or several matches at one level is an error; lifting into a non-liftable union is an error. A temporary {tag, payload} is built at the call site and passed by reference.
7. Statements
- Simple statements (expr, return, defer, raise, break, continue, guard, with) end in ;. if, when, for end at their } with no ;. Braces are never elided. A function body's } is distinct from its last statement's.
- An ifexpr used as an expression statement ends in ;.
7.1 Assignment
- An expression yielding the RHS; no chaining.
- LHS: variable, or a place by index, field, deref, bit field.
- Arrays are not assignable whole. A slice assignment copies {data, count}. += and -= are for scalars.
- A record takes a record expression, r = {f: v, g: {h: w}}: named fields, any order, once each; nested braces for a record field; no array or union field. Each field is stored as r.f = v, left to right. Left out is zero. Every field holding a leaf (5.1) is given.
- A field may be built in place by a call with a hole, f: (make into, x): an into with no argument after it is the field. One hole per entry, outside any branch; the call returns nothing. This is how a record field is given other than by nested braces.
- A call with arguments as a value is parenthesised when an entry follows: its list would take the entry.
- Only as the RHS of =: no operand, no temporary. The place is a whole binding, p^ of a born ^rec, or a born part; never a part of an unborn record.
7.2 Calls
- Arguments follow the callee without parentheses; the list ends at the first token that is not a comma, an argument marker, or an atom start (literal, qualident, fn, "(").
- An argument is an atom plus non-call postfixes: f a + b is (f a) + b; f a[i], f a.x.y, f a^.x pass the place. Composite arguments are parenthesised.
- Arguments are evaluated left to right before the call.
- A bare function designator is always a zero-argument call, except as the LHS of an assignment or a var/into argument. A function value is written fn d.
- Callable: a named function, or any value of function type — a variable, a parameter, a field, an element, a pointee. A bare designator of function type is a call wherever it stands (r.f a, b; fs[i] 3; p^.step); its value is fn d.
- Marker must match the parameter kind (see 8.1).
- Calling a raising function contributes its failures to the caller.
7.3 If
- Condition is bool; every branch is braced; else-if chains.
- As an expression it needs else; all branches yield one type; a branch yields its last statement's value.
7.4 When
- Scrutinee evaluated once: int, a bit type, enum, or union.
- Labels are compile-time values of the scrutinee type: enum -> its variants or constants of it; others -> integer/hex literals and integer constants, byte also characters. A typed constant matches only its own type. On byte, hword, word a label must fit the width. Labels distinct.
- First matching case runs; no fallthrough; no empty case body; shared labels use one comma list. * else is last.
- Enum: exhaustive or else, otherwise rejected. Other integer types: unmatched without else does nothing.
- Union: scrutinee must be a plain variable (local, parameter, module var); each label is one subtype u.v, narrowing the variable for that case; exhaustive or else; in else it stays u.
- Every case starts with *.
7.5 Guard
- guard x u.v | escape; narrows union x to u.v for the rest of the block, else takes the escape.
- guard p | escape; narrows ^t|none p to ^t. p must be live (guarding a moved-dead optional is rejected).
- escape: return arg, raise f.kind (failure must be in the ! clause), break or continue (inside a loop only).
- Narrowing ends with the block, or when x is assigned a value of its declared type.
7.6 For
- for [cond [; step]] { }: no cond = infinite. step runs after the body and is continue's target. break and continue only inside a loop.
- A for with no cond and no break of its own (a guard escape included; a nested loop's does not count) never falls out: as a body's last statement it is no fall-through (8).
- for with n = seed; advance { }: seed and advance are ^t or ^t|none; stops at none. n is a body-scoped mutable alias of the pointee, not addressable. Seed once; advance after each iteration (continue target). Both are non-consuming reborrows. Walking a moved-dead list is rejected.
7.7 Return
- return expr; always has an expression (none for no-result functions), compatible with the return type.
- Defers run before return completes.
7.8 Defer
- Registers an expression run at return or failure propagation, LIFO. At most 8 per function.
- A deferred expression may not raise. The carried failure is invisible to it and restored after.
- A from argument in a defer consumes at each exit, not at the defer; moving the owner before an exit is a use after death.
- Defers run after an implicit result is computed and must not disturb it.
7.9 Failures
- f failure { k1, k2, ... }: closed, mandatory kind list. The name comes first, as a type's does; failure follows it. g failure as f: alias, same failure and kinds, no own list. Module-local, exported before ..., named m.f from outside. No predeclared failures.
- raise f.k; / raise m.f.k; names a kind (a bare failure is an error); abandons the function after replaying defers.
- Exact clause: the compiler computes the escaping set (raises add kinds' failures, calls add callees' declared failures, handlers remove what they discharge, handler bodies may add). A failure escaping but not declared, or declared but not escaping, is an error. No failures = no clause; a bare ! is a syntax error.
- The unnamed failure joins the set only via calls of open functions (or an asm body's trusted clause); never via raise. Exactness applies to it too.
- Handlers stand at the end of a body, sharing its }. on ref | ref ...: stmts; ref is a failure (all kinds) or a kind. Kind handlers before a failure handler of the same failure win for their kind. Handling every kind individually discharges the failure. A handler runs in the function's frame; completing it is a normal return. A failure raised in a handler body propagates (not caught by siblings).
- on ...: discharges everything, named and unnamed; must be last; cannot be mixed with names. Named handlers never discharge the unnamed failure.
- on ... with f: binds f, read-only, scoped to the handler, of type mirror.fault_kind (10.1). Only the unnamed handler binds.
- Representation: 32-bit word, failure number in the high 16 bits (from 1, in first-declaration order across the program, not stable), kind number in the low 16 (from 1). 0 = no failure. Kind test = word compare, failure test = shift + compare.
7.10 With
- with n = designator; binds n to the place (not a copy), address computed once. Scope: to the end of the enclosing compound. Shadowing an outer name is fine; two of one name in one compound is an error.
- Designator: a variable plus index/field/deref; not a literal, call, operator expression or subrange.
- While n is live, any designator overlapping its place (same element, part, whole, same array with a non-literal index) and a second with over it are rejected. Disjoint places stay usable.
- n is writable exactly when the designator is.
- guard and when narrow n like any binding (the way to narrow a union element).
8. Functions
- name fn signature (name inline fn for an inline one), then any number of var/final local clauses, then a body or an asm body. ... instead marks a deferred definition (no locals, no inline); as m.f makes an alias.
- At the prompt name fn also starts a call passing a function value (apply fn double, 3). It is a definition when ( follows fn: a signature opens with its parameters.
- Locals: frame, natural alignment, zeroed by the prologue; at most 64 (implementation limit).
- Implicit return: when the body falls through, its trailing expression statement is the result; it must convert to the return type and obeys the frame and alias rules like return. Every into parameter must be born on fall-through too. A body ending in raise, break, continue or an endless for (7.6) does not fall through.
- No aggregate (array, record, slice, union) returned by value except a slice; use var or into otherwise.
8.1 Parameters
- Scalars (bool, integers, double, pointers, address) by value; aggregates (arrays, records, slices, unions) by reference whatever the marker.
- Plain: immutable binding; aggregates unwritable; a slice (or one read out of an aggregate parameter) is a view; a pointer is a borrow. Takes views and literals.
- var: inout; the argument is a writable lvalue marked var and fully born. A var []t also takes a writable slice value (subrange, call result) via a temporary. A var pointer is a borrow; the callee may store a new owner into it or take its optional value with null.
- into: out; unborn in the callee, must be born before any normal return, not read first. The argument need not be born and is born after the call. A second into on a born final is rejected.
- from: consumes. Argument born on entry, dead after the call for the rest of the sequence and all following paths. Only for a type with a leaf to consume (^t, address, affine, or a record holding one); not for a slice. A ^rec passed to a from address parameter need not have its leaves born. The root binding must be owned (local, into/from parameter). No consumption across a loop back-edge unless born in that loop.
- One marker per parameter (var, into, from or ...). The call-site marker must equal the parameter's; var/into/from need a writable lvalue.
- Writing through a pointer parameter (p^ = .., var p^) is allowed; only rebinding is barred.
- Argument overlap: no two arguments of one call may overlap when either may be written (var, into, from, or a plain ^t). Scalar arguments are copies and never overlap. A nested call completes before the outer.
- Variadic: last parameter ...t, type []t, immutable. t: scalars, pointers, address, slices, or a liftable union; not record, array, enum, non-liftable union. Call forms: direct (one trailing []t or [n]t argument passed as is) or pack (zero or more t-compatible arguments stored left to right into a caller-frame array; empty pack = count 0, data none). With a liftable union t each slot is lifted. Calls through a function value always take the slice form.
8.2 Inline functions
- name inline fn: expanded at the call site.
- No locals, return, defer, raise, for, break, continue or handlers. Calls to raising functions are allowed under an exact ! clause; the fault skips the rest of the copy into the caller. May be open.
- Not a value, not an alias target, not callable before its definition (no prototype use, no recursion). A prototype whose definition is inline is legal if not referenced in between (this is how one is exported).
8.3 Forward declarations and aliases
- A body-less signature binds the name with no code. A later definition with an identical signature patches it (address, frame, inline flag); a different signature replaces the binding.
- Interface section: prototypes only, no ... marker, no inline. Body section: forward declaration is signature + ...; a body-less signature without ... is incomplete.
- f fn () ! ... ... : first ... closes the clause, second defers the body.
- f fn sig as target: alias of an already-defined function (local or m.f); signature (result, params, markers, clause, variadic) must match exactly. No inline either side. In the interface section it re-exports an imported function.
8.4 Assembly bodies
- asm { ... }: passed to the RV64 assembler. li takes a 64-bit immediate or an integer constant's name, bare or m.name; so does a load or store offset, besides a local's name.
- call f, tail f and la rd, name reach a function (not inline), a module variable or a constant's storage (a string's bytes, an array or record constant), bare or m.name, through the same pc-relative slots as compiled code. call spends ra, so the body is framed unless naked.
- Labels are 0..31, referenced as nb / nf.
- Prologue/epilogue emitted unless the block uses neither fp nor ra and the function has no locals, no with, no by-reference parameter copies: then frameless leaf, ret appended.
- asm naked: always frameless, no ret appended; no locals or with.
- An asm body carries no ! clause.
9. Modules
- Unit of compilation and namespacing. The first bare ... at module scope separates interface (public) from body (private). The interface holds declarations and prototypes only.
- import 'p, 'q: one list, before the first declaration, never in the body. Paths relative, no .alm, no leading /. Resolution: importer's work directory, then the library root (/a). Local name = basename; two imports with one basename collide. Modules are keyed by resolved path. Recursive imports are rejected.
- Only the interface crosses the module boundary.
- Prompt only: importing m also imports m_spec when that file exists (not run).
9.1 Setup and teardown
- setup fn () and teardown fn (), recognised by name at module scope only: no parameters, no result, not inline, not an alias.
- setup runs once, after the module's imports are loaded and set up, before the importer continues. It may raise; a failure fails the import (unit rolled back, modules loaded for it torn down, no teardown for this module).
- teardown raises nothing; runs at reset and on rollback in reverse load order, while the code is still mapped.
- Neither switches fibers nor blocks.
- setup is where module slices, ^t, address, affine values and finals are born.
10. Mirror
- mirror is the module the compiler provides: bound in every module and at the prompt, never imported. It is the only way almac code reaches compiler state; a program that never names it does no reflection.
- Every accessor is total: an unknown name, word or address yields "" or zeros, never a failure.
- Text composed by type_name_of lasts until its next call; what, what_at, locals_at and slot_name_at share one buffer and last until the next of them. Copy to keep. Addresses die at reset.
10.1 Failures
- fault_kind from dword: a failure word (7.9); the type of on ... with f. as dword is the explicit escape.
- fault_owner_of, fault_name_of, fault_kind_of: fn (f fault_kind) -> string — the declaring module, the failure, the kind ("" for a whole-failure word).
10.2 Types
- type_ref from dword: a type handle; no arithmetic, an untyped literal adopts it.
- type_name_of (t type_ref) -> string: the name t is bound under, else its structure as a declaration writes it.
- shape record {kind int, size int, element type_ref, count int}; shape_of (t type_ref, into s shape). kind:
0 primitive 1 array 2 record 3 pointer 4 slice
5 named 6 function 7 incomplete 8 enum
9 union 10 union subtype
- element: a named type's base, the element of an array, slice or pointer, a union's tag enum, a subtype's union. count: fields, labels or variants; a subtype's own index.
- member record {offset int, of type_ref}; member_of (t type_ref, i int, into m member): a field's offset and type, a label's value, a variant's payload. member_name_of string (t type_ref, i int).
10.3 Running source
- The two outcomes, as declared unions:
value union nothing
| number {of type_ref, item int}
| real {of type_ref, item double}
| bytes {of type_ref, item string}
| raised {f fault_kind}
| rejected {report string}
program union
ready {entry dword, size int, of type_ref}
| rejected {report string}
- run (source string, into v value): compile source into the live image, run it, classify the outcome. A raised failure wins over any result; a statement yields nothing; an integer-based scalar a number; double a real; a slice bytes. A source that does not compile, or a run during a compile, is rejected with its report.
- prepare (source string, into p program): compile and flush as run would, without running. Definitions and imports take effect; the code lives until reset. entry is a plain function returning the unit's value (of none for a statement).
- reify (of type_ref, bits int, extra int, real int, f fault_kind, into v value): classify what a prepared unit left (a0, a1, the bits of fa0, the failure word) as run does.
10.4 Code
- code record {start dword, size int, frame int, flags dword}: where the body starts, its size in bytes, its frame size. flags: 1 inline body, 2 host function, 4 module text (no function covers it), 8 data (a module variable's storage).
- code_of (name string, into c code): name as the prompt sees it, or m.f among m's publics. code_at (pc dword, into c code): what covers pc.
- name_at, owner_at, path_at (pc dword) -> string: the covering name, its module ("" at the prompt), the module's resolved source path.
- what_at, locals_at (pc dword) -> string: the covering function's declaration and locals clause as its source writes them.
- line_at (pc dword) -> int: the source line, 0 when unknown.
- purpose_at (pc dword) -> int: what the word is for, 0x80 added on the first word of a run. In order from 0:
none frame argument copy zero tag leave save restore
pass call release forget fault_check fault_out park
clean unpark raise on next_handler keep handled reraise
defer keep_result ret test skip_else loop brk cont when
10.5 Frames
- slot record {start int, size int, flags dword, of type_ref}.
- vars_at (pc dword) -> int: the parameters (first) and locals of the function covering pc. var_at (pc dword, i int, into s slot): the i-th one's fp offset, size, flags and type. var_name_at (pc dword, i int) -> string.
- slot_name_at (pc dword, slot int, inner int) -> string, slot_at (pc dword, slot int, inner int, into s slot): the frame word at fp + slot (inner < 0), or byte inner of what the by-reference parameter at that slot points at, named as an expression (c.size, l[3], length name, &x). Flag 128 marks the word of a by-reference parameter itself.
10.6 Modules and the image
- modules () -> []string: loaded modules in byte order.
- exports (name string) -> []string: the names a module declares publicly in byte order, without the modules it imports; "" lists the prompt's own.
- what (name string) -> string: the declaration of name (or m.name) as the interface section writes it, types only. An aggregate constant reads in its prefix form with the contents elided: t = []string [...].
- image_held, image_code, image_data, image_names () -> int: bytes of pool the image holds; of it flushed code, module variables, and everything named.
- load_count () -> int, load_name (i int) -> string, load_us (i int) -> int: imports in load order, each module's own load time in microseconds.
Appendix — Syntax
EBNF: = defines, | alternative, ( ) group, [ ] optional, { }
repetition, "x" terminal.
module = [ importlist ] { declaration }
[ "..." { definition } ] .
importlist = "import" string { "," string } .
declaration = functionproto | vardecl | constdecl
| typedecl | failuredecl .
definition = fndef | declaration .
functionproto = ident "fn" signature [ "as" qualident ] .
vardecl = ( "var" | "final" ) vardefs .
constdecl = ( ident | ident "." ident ) "=" constval .
constval = element | [ "[" "]" type ] arrayconst
| typename recordconst .
element = constexpr | "fn" qualident | recordconst .
constexpr = constterm { ( "+" | "-" ) constterm } .
constterm = constcast
{ ( "*" | "/" | "mod" ) constcast } .
constcast = constunary [ "as" type ] .
constunary = [ "-" ] constprimary .
constprimary = constatom
| ( "and" | "or" ) [ constatom
{ "," constatom } ]
| "not" constatom .
constatom = "true" | "false" | "none"
| integer | hex | fp | character | string
| qualident [ "." ident ]
| "(" constexpr ")" .
arrayconst = "[" element { "," element } [ "," ]
"]" .
recordconst = "{" [ constinit { "," constinit }
[ "," ] ] "}" .
constinit = ident ":" element .
typedecl = ident
( ( "as" | "from" | "affine" ) typename
| structtype ) .
failuredecl = ident "failure"
( "as" qualident
| "{" ident { "," ident } "}" ) .
vardefs = vardef { "," vardef } [ "," ] .
vardef = ident { "," ident } type .
fndef = ident [ "inline" ] "fn" signature
( "as" qualident | "..."
| { ( "var" | "final" ) vardefs }
( body | asmbody ) ) .
asmbody = "asm" [ "naked" ] compound .
signature = "(" [ param { "," param } ] ")"
[ "->" type ] [ failures ] .
param = ( "into" | "var" | "from" ) ident type
| ident [ "..." ] type .
failures = "!" ( "..." | qualident
{ "|" qualident } [ "|" "..." ] ) .
type = [ "const" ] ( typename | structtype ) .
structtype = "^" type [ "|" "none" ]
| "[" [ constexpr ] "]" type
| "record" recdef
| "enum" ident { "|" ident }
| "union" unionvariant { "|" unionvariant }
| "fn" signature .
typename = qualident [ "." ident ] .
recdef = "{" [ vardefs ] "}" .
unionvariant = ident [ recdef ] .
qualident = ident [ "." ident ] .
body = "{" [ stmts ] { handler } "}" .
handler = "on" ( "..." [ "with" ident ]
| failureref { "|" failureref } )
":" stmts .
failureref = qualident [ "." ident ] .
compound = "{" [ stmts ] "}" .
stmts = stmt { stmt } .
stmt = return | defer | raise | for | forwith
| break | continue | if | guard | when
| with | ( expr ";" ) .
return = "return" expr ";" .
defer = "defer" expr ";" .
raise = "raise" qualident "." ident ";" .
for = "for" [ expr [ ";" expr ] ] compound .
forwith = "for" "with" ident "=" expr ";" expr
compound .
if = "if" expr compound
[ "else" ( if | compound ) ] .
guard = "guard" ident [ typename ]
"|" escape ";" .
escape = "return" arg
| "raise" qualident "." ident
| "break" | "continue" .
when = "when" expr
"{" { case } [ elsecase ] "}" .
case = "*" caselabel { "," caselabel }
":" stmts .
caselabel = integer | hex | character | qualident .
elsecase = "*" "else" ":" stmts .
with = "with" ident "=" designator ";" .
designator = atom { index | field | deref } .
break = "break" ";" .
continue = "continue" ";" .
expr = assign .
assign = compare
[ ( "=" | "+=" | "-=" ) compare
| "=" recordexpr ] .
recordexpr = "{" [ fieldinit { "," fieldinit }
[ "," ] ] "}" .
fieldinit = ident ":" ( expr | recordexpr ) .
compare = addition [ relation addition ] .
relation = "==" | "!=" | "<" | "<=" | ">" | ">=" .
addition = multiply { ( "+" | "-" ) multiply } .
multiply = cast { ( "*" | "/" | "mod" ) cast } .
cast = unary [ "as" type ] .
unary = [ "-" ] postfix .
postfix = primary { index | field | deref }
[ args ] .
args = arg { "," arg } .
arg = [ "into" | "var" | "from" ] atom
{ index | field | deref }
| "into" .
index = "[" expr [ ":" expr ] "]" .
field = "." ident .
deref = "^" .
primary = atom | ifexpr .
atom = "none" | "true" | "false"
| integer | hex | fp | character | string
| qualident
| "fn" atom { index | field | deref }
| "(" expr ")" .
ifexpr = "if" expr compound
[ "else" ( ifexpr | compound ) ] .
ident = letter { letter | digit } .
letter = "a" ... "z" | "_" .
digit = "0" ... "9" .
hexdigit = digit | "a" ... "f" .
integer = digit { digit } .
hex = "0" "x" hexdigit { hexdigit } .
fp = digit { digit } "." digit { digit }
[ "e" [ "+" | "-" ] digit { digit } ] .
character = "'" any-byte-except-quote "'" .
string = '"' { any-byte-except-quote } '"'
| shortstring .
shortstring = "'"
{ any-byte-except-whitespace-or-closer } .
comment = "--" { any-byte-except-newline } newline .