Compiler
The leviathan command line
Every option of the leviathan compiler, grouped by what it does, with the exit statuses and how arguments reach your program.
since 0.1.0-alpha.1linux
Description
leviathan [options] <source-file>
leviathan [options] --plan <build-plan>
leviathan [options] --batch <jobs-file> [--jobs <N>]
leviathan --version
The compiler reads one source file, or the set of files named by a build plan (see
trident.overview), checks the whole program at once, and then does whatever the mode option
asks for. With no mode option it only checks the program: it prints a description of the
declared types and exits with status 0, or prints the diagnostics and exits with status 1.
Diagnostics carry source positions, and the compiler keeps going after the first error so that
one run reports as many problems as it can.
Put every option before the source file. The compiler treats any argument it does not recognise as the source file name and the last such argument wins, so a misspelled option written before the file is silently ignored and an option written after the file is read as a file name.
Running and building
| Option | Meaning |
|---|---|
--run |
Check, then execute with the tree-walking evaluator. |
--ir |
Check, lower to bytecode, and execute the bytecode. |
--build-native <out> |
Check, generate code with the LLVM backend, and link the executable <out>. |
--native-obj <out> |
Like --build-native, but stop after writing the object file <out> without linking. |
--emit-llvm |
Print the program as LLVM IR text on standard output. |
--target <triple> |
The machine the program is built for. It selects the code --native-obj and --build-native generate and what the target:: constants report in every mode; see lang.cross-compilation. |
--opt-level <0|2> |
Optimisation level for object generation: 0 is a quick debug build, 2 (the default) optimises. |
--runtime <path> |
Link against this runtime library instead of the one installed beside the compiler: liblvrt.a for an executable, or liblvrt_pic.a for --lib shared. |
--profile debug|release |
The build profile (default debug). --profile release drops every @Debug contract check (@Debug pre, @Debug post, @Debug assert, @Debug invariant): the dropped predicates are not evaluated. Always-on checks are unaffected. Any other value is a usage error (status 2: error: unknown profile '<x>' (expected debug or release)). See lang.contracts. |
--debug-checks |
Keep the @Debug checks even under --profile release. |
--no-columnar |
Store arrays of structs row by row (see lang.columnar-arrays). |
--trust-check |
With --build-native, --native-obj or --emit-llvm: check, while the program runs, every place where the generated code relies on a value having its declared type (a non-optional string, class, array, map, set or function value is never None and never another kind). A value that breaks this stops the program with trust violation: <function> pc<N>: expected tag <K>, got <T> on standard error and exit status 70. Such a value means a bug in the compiler's type checking; without the flag, the program can crash or misbehave instead. The checked build is slower. It also re-checks, after each field read the compiler lent without a reference count, that the field still holds that value. With --run or --ir the flag is a usage error (status 2). |
--native |
Allow a source file compiled without a build plan to declare foreign functions (@extern, @export) and call the raw-memory parts of ffi (see lang.ffi). Trident grants the same permission through the plan, from the package's [[native]] tables; --native together with --plan is an error. |
--lib shared|static |
With --build-native: build a library of the program's @export functions instead of an executable — a shared object (<out>.so, .dll on Windows) that already contains the runtime, or a static archive (<out>.a) whose consumer links the runtime library itself (the compiler prints that link line). The runtime comes in two builds side by side: a shared object contains liblvrt_pic.a, the position-independent one, and a consumer of the static archive links liblvrt.a (the printed line) into an executable or liblvrt_pic.a into a shared library of its own. A compiler with no liblvrt_pic.a beside it stops with no shared-library runtime at '<path>' — rebuild the toolchain. No main is linked; the C side brackets the runtime with leviathan_init / leviathan_shutdown, and the first leviathan_init runs the entry file's top-level code. |
--header <file> |
With --build-native or --native-obj: write a C header declaring every @export function, the @repr("C") structs they use (as lv_S_<Name> typedefs) and the leviathan_init / leviathan_shutdown prototypes. |
-- <args> |
Everything after a lone -- is handed to the program. |
--batch <jobs-file> |
Run every job the jobs file lists, each in a child of one compiler process that has checked the standard library once. A job names one program, a source file or a build plan, and one to six legs: run, ir, ir-verify, check (no mode option), native-obj and build-native. Each leg's standard output, standard error and exit status are those of a fresh leviathan run of that mode with the same options, working directory and standard input; the batch prints one result line per leg. See the rules below. |
--jobs <N> |
With --batch: run at most N jobs at once (default 1). |
The two build options print built <out> on standard error when they succeed. On a Windows
target --build-native appends .exe to the output name and on a WebAssembly target it
appends .wasm.
A program whose foreign functions pass @repr("C") structs by value makes --build-native
write and compile a small C file beside the output (<out>.lvffi.c, regenerated on every
build; the C compiler supplies the struct calling convention). The libraries the foreign
functions come from are linked from the build plan's link rows; without a plan, --native
adds -l<nickname> for every library an @extern names other than c and m.
The object cache
--native-obj and --build-native keep the object files they generate in a per-user cache
and reuse one when the same program is built again with the same options and the same
compiler. The front end always runs, so diagnostics, warnings and comptime console output are
the same whether or not the object was reused; only code generation is skipped. A reused
object is byte-for-byte what a fresh build would have produced.
| Option / variable | Meaning |
|---|---|
--cache-dir <dir> |
Use this cache directory for the build. |
LEVIATHAN_CACHE_DIR |
The cache directory. Default: $XDG_CACHE_HOME/leviathan, else ~/.cache/leviathan. |
LEVIATHAN_CACHE |
on (default), off, refresh (build and store, never reuse), verify (reuse, build anyway, and fail with status 1 if the two differ). |
LEVIATHAN_CACHE_POLICY |
Size and age limits, as key=value pairs joined by :. Default cache_size_bytes=5g:prune_after=168h. |
LEVIATHAN_CACHE_DEBUG |
1 prints one line per build saying whether the object was reused; 2 also prints what the reuse decision was based on. |
LEVIATHAN_PRELOWER |
on (default) lowers the prelude once per process, in the prelude phase, and links each program against it; off lowers everything per program in one pass; verify does both and exits 70 with prelower verify: … on stderr if the modules or diagnostics differ. The output is identical in every mode. Any other value is a usage error (exit 2). Under --batch, the parent prelowers once and every job inherits it. |
LEVIATHAN_PRELOWER_STATS |
1 prints one line on stderr per link: [prelower] records=<n> installed=<n> relowered=<n> absent=<n> invalid-atoms=<n> invalid-sites=<n> invalid-cascade=<n> unrecordable=<n> fallback=<none|reason>. |
--cache-stats |
Print how many builds reused an object, how many stored one, and the cache's size. |
--cache-stats-zero |
Reset those counters. |
--cache-clean |
Empty the cache. |
Looking at what the compiler sees
| Option | Prints |
|---|---|
--tokens |
The token stream, one token per line with its line and column. |
--ast |
The syntax tree as parsed, before rules and macros have run. |
--expand |
The program after rules, macros and comptime evaluation, as ordinary source you can compile again. |
--ast-after-rules |
The syntax tree of that expanded program. |
--rules |
Every rule that fired and where, including the ones the standard library defines. |
--resolve |
The declared types after name resolution, without type checking. |
--dump-ir |
The lowered module (the bytecode the IR interpreter and the LLVM backend start from) in a canonical text form: one line per function, register, constant and instruction. It is meant for debugging the compiler and is not a stable format. A program that fails to compile exits as with --ir. |
--no-rules |
Turns the rule and macro stage off for the run. |
--comptime-budget <n> |
Raises or lowers the step limit for the program's compile-time evaluation: its comptime code, macros, attribute arguments and rule where clauses (see lang.comptime). Exceeding it is a compile error. The standard library's rules applied to the standard library's own declarations always run under the default limit, whatever this flag says. |
--reentrant-budget <n> |
Changes the round limit for rules that re-trigger each other (default 8). |
Projects and namespaces
These options answer questions about how a multi-file program fits together. They work on a single file too, which they treat as a project of one file.
| Option | Prints |
|---|---|
--plan <file> |
Compile the project a build plan describes instead of one source file. |
--imports |
For each file, the namespaces it declares, the ones it uses, and every namespace visible to it. |
--graph |
Which files depend on which through uses, any cycles, and the order the files build in. |
--namespaces |
Every namespace, the files that open it, and its members. |
--why <name> [in <file>] |
Where a bare name could come from and which candidate wins, for one file if you name it. |
--lint-namespaces |
An opt-in check that each file sits in a folder matching the namespace it opens. It exits with status 1 when a file does not. |
--assets |
The files that comptime import() calls read: path, size, hash when a plan supplies one, and owning module. |
Standard library and documentation
| Option | Meaning |
|---|---|
--prelude <dir> |
Read the standard library from this directory instead of the one that ships with the compiler. The directory must contain every standard library file. |
--check-prelude |
Type-check the standard library itself and print a summary of what the checker found. Exits with status 1 if it found errors. No source file is needed. Permanent tooling (perf-epic D8): the prelude is type-checked on every compile; this is the standalone gate. |
--type-audit |
Type-check the file and print [type-audit] summary lines: how many expressions, calls, binary operators, parameters and locals the checker proved a concrete type for (the coverage the typed LLVM lowering consumes). Permanent tooling (perf-epic D8): the instrument for "why is this not typed?". The last line, [type-audit] unknown plain=<n> tparam=<n> dependent=<n>, splits the untyped expressions: tparam are values of a type parameter, dependent are values computed from one (a member, call, index or operand of a T value), and plain are values with no type at all, which the type_audit_no_plain_unknown lane keeps at 0 for the prelude, the in-tree packages and the corpus. |
--contract-audit |
Type-check the file and print one line per contract fact, for the program's own code only, sorted by position, before the program's output: <file>:<line>:<col>: contract-audit: <text>. A callable with clauses prints function <name>: <p> pre, <q> post, <d> @Debug, followed by ; inherits <base>, ... when it has bases. A class with invariants prints class <name>: <n> invariant, <d> @Debug. A call of a contracted function, or a construction or member access that checks an invariant, prints call <name>: <outcome>, followed by ; invariant check when the site checks an invariant. The outcomes are satisfied: unchecked entry, satisfied by narrowing: unchecked entry, satisfied (receiver call): checked entry, satisfied by narrowing (receiver call): checked entry, violated, checked at run time under @Violates, unknown: '<param>' is not a constant: checked entry, unknown: the precondition reads '<name>': checked entry, unknown: the precondition is not pure: checked entry, unknown: dynamic dispatch: checked entry, unknown: inherited precondition groups: checked entry, no always-on precondition: checked entry and no precondition. Nothing is printed when the check fails. See lang.contracts. |
--numeric-audit |
Type-check the file and print one numeric-audit: line, with its location, for every literal-only expression (numeric literals combined with -, ~ and the arithmetic and bitwise operators) whose value changed when literals began adopting their target type, and for every one whose adoption narrowed the working type of the operator beside it. For example, float f = 7 / 2; prints '7 / 2' is 3.5 as 'float' (was 3). It is the migration audit of numeric strictness: every other change to the numeric rules is a compile error. |
--doc-json |
Print the documented symbols of the standard library as JSON. Given a source file or plan, it needs --package-name <name> and --package-root <dir> and dumps that package instead; --package-version <v> records its version. |
The standard library files are looked up in this order: --prelude, the LV_PRELUDE_DIR
environment variable, a prelude directory beside the compiler, and finally a copy built into the
compiler. A directory named by --prelude or LV_PRELUDE_DIR that is missing or incomplete is an
error, never silently skipped.
Checking memory behaviour
--ownership, --ir-verify and --mem-verify examine how a program allocates; they are
described in lang.ownership-analysis.
Program arguments, exit status and the program's own output
Arguments after -- reach the program through env::args(). The first element is the program
name, so the real arguments start at index 1. Natively built programs receive their arguments
from the operating system as usual, and the -- form is only needed with --run and --ir.
The compiler exits with 0 when the program ran to completion, with 1 when compilation failed or
an exception went uncaught (it prints Uncaught <Type>: <message> on standard output), and with
2 when it was invoked wrongly or could not read the file. A program can choose its own status
with env::exit(n), and --run, --ir and natively built programs all report it.
A program to inspect with the compiler
use io::console;
namespace Meta {
macro bump(e) => `(($e) + 1)`;
}
uses Meta;
int base = 41;
console.writeln(bump!(base));
42
Rules
- Options must come before the source file name.
- Exactly one mode option takes effect when several are given: the one written last.
--build-nativeand--native-objneed the output path as the next argument.--runand--irexecute the program in the compiler's own process. The other modes produce an executable or text and do not run the program.--runtimeonly affects linking.--targetalso changes what thetarget::constants fold to, in every mode, including--run.- A source error stops the build and leaves no output file.
- The cache is keyed on the program text and every file it reads at compile time, the standard library text, the build options, and the compiler binary itself; a different compiler build never reuses another's objects. A compiler rebuilt from identical sources may or may not reuse earlier objects, and either is correct.
- A cache directory that cannot be created or written turns the cache off for that build with no message.
- The build profile is part of the object-cache key:
--profile release, and--debug-checkswith it, build different objects, so changing either rebuilds rather than reusing an object from the other profile. - Setting any compiler trace or test variable (for example
LV_D11_STATS) turns the cache off for that build. --batchtakes every option except the per-job ones. A mode option,--plan,--native, a source file and--belong in the jobs file (error: --batch: <option> is a per-job setting; put it in the jobs file, status2), and the cache commands cannot be combined with it. The other options apply to every leg, and a leg whose options a fresh run would refuse prints that run's error and exits2.- A
--batchleg's standard output, standard error and exit status equal those of the fresh process( cd <cwd> && leviathan <mode-option> [<out>] [options] <program> -- <args> < <stdin> > <out> 2> <err> ), and its program sees the same descriptors, signal dispositions and environment. The legs of one job check the program once when nothing printed while checking it (counted asshared-front); otherwise each leg checks it again (refront). - The jobs file is UTF-8 text with one record per line and one TAB between fields: the header
leviathan-batch<TAB>1, then for each job ajob id=<id> file=<path>|plan=<path> [cwd=<dir>] [native=1] [arg=<a>]...record followed by itsleg mode=<mode> stdin=inherit|null|path:<p> out=null|path:<p> err=null|path:<p>|merge [timeout=<s>] [kill-after=<s>] [obj=<path>] [bin=<path>]records (objfornative-obj,binforbuild-native). Every path is relative to the job'scwd. Blank lines and lines starting with#are ignored. A malformed file stops the batch before anything runs:error: <jobs-file>:<line>: <reason>, status2. - When every job has finished, the batch prints, in jobs-file order, one
result job=<id> leg=<k> mode=<mode> rc=<n> status=<s> ms=<wall>line per leg (kcounts the job's legs from0), thenstats jobs=<n> legs=<n> shared-front=<n> refront=<n> errors=<n>, and exits0.statusisexit(rcis the exit status),signal(128+nfor death by signaln),timeout,killedorerror(125: the leg could not start, and its reason goes to the batch's standard error). - A leg's
timeoutcounts from the start of its job, so the time spent checking (and lowering) a program its legs share counts toward each leg, as a fresh run's owntimeoutwould. With akill-aftergreater than0,rcis what a shell's$?shows fortimeout -k <kill-after> <timeout> leviathan …: attimeoutthe leg's process group getsSIGTERM(thenSIGCONT), andrcis124(timeout) if the leg ends withinkill-after, else137(killed) afterSIGKILL. Withkill-after0or absent the group getsSIGKILLattimeout(killed,137), astimeout -s KILL <timeout> leviathan …gives, so a batch never waits on a leg that ignoresSIGTERM. A stopped batch (SIGTERM,SIGINT,SIGHUP) kills every leg's process group first, so no process a program started outlives it. - The batch exits
2for a malformed jobs file or a refused option, and1when the standard library cannot be read.--prelude <dir>andLV_PRELUDE_DIRname one standard library for the whole batch, which the batch process reads once: a relative directory is resolved against the batch's working directory, not a job'scwd.
Examples
Saved as meta.lev, the program above can be looked at in several ways. --tokens shows what the
lexer made of the first lines:
$ leviathan --tokens meta.lev
1:1 KwNamespace namespace
1:11 Identifier Meta
1:16 LBrace {
2:5 Identifier macro
2:11 Identifier bump
2:15 LParen (
--ast shows the tree before the macro runs and --expand shows the source after it has:
$ leviathan --ast meta.lev
Program
Namespace Meta
Macro bump(e) => ($e + 1)
Uses Meta
Var base : int = 41
Expr console.writeln(bump!(base))
$ leviathan --expand meta.lev
namespace Meta {
}
uses Meta;
int base = 41;
console.writeln((base + 1));
Handing arguments to a program. This source reads its arguments:
A program that reads its arguments
use env;
use io::console;
Array<string> args = env::args();
console.writeln("program name and ${args.length() - 1} argument(s)");
for (string a in args.skip(1)) {
console.writeln("arg: ${a}");
}
Saved as args.lev, it is run with:
$ leviathan --run args.lev -- red "dark green"
program name and 2 argument(s)
arg: red
arg: dark green
Building and inspecting a project through its plan (see trident.overview for how the plan is
made):
leviathan --imports --plan build/plan.lvplan
leviathan --why Link in ./main.lev --plan build/plan.lvplan
leviathan --build-native app --plan build/plan.lvplan
Running two programs, the second with two legs that share one check, as one batch (the fields are separated by TABs):
$ cat jobs.txt
leviathan-batch 1
job id=hello file=hello.lev
leg mode=run stdin=null out=path:hello.out err=merge
job id=app plan=build/plan.lvplan
leg mode=ir stdin=null out=path:app.out err=path:app.err timeout=60 kill-after=5
leg mode=native-obj stdin=null out=null err=path:app-obj.err obj=app.o
$ leviathan --batch jobs.txt --jobs 2
result job=hello leg=0 mode=run rc=0 status=exit ms=38
result job=app leg=0 mode=ir rc=0 status=exit ms=212
result job=app leg=1 mode=native-obj rc=0 status=exit ms=1306
stats jobs=2 legs=3 shared-front=1 refront=0 errors=0
Generating code for another machine:
leviathan --build-native app.exe --target x86_64-pc-windows-gnu --runtime runtime/x86_64-pc-windows-gnu/liblvrt.a main.lev
Notes
leviathan --versionprints the compiler's name and version. It must be the only argument.- The compiler is built with or without the LLVM backend. A compiler built without it reports
this build has no LLVM backendfor--emit-llvm,--native-objand--build-native, and the other modes still work. - The LLVM backend (
--emit-llvm,--native-obj,--build-native) lowers with typed registers (unboxed scalars, a typed internal ABI, elided checks) by default.--typedis still accepted and is a no-op.--no-typed(the previous untyped lowering's bisect switch) was removed at the performance epic's close-out and now fails with a clear message (exit 2). The oracle and--irengines ignore--typed. - The cache's
verifymode is for checking a cache after a change to the compiler's inputs; it doubles build time and is not meant as a default. --no-rulesis a debugging aid. Rules do not fire under it, and a program that calls a macro does not compile.
See also
- Implementation status and execution modes — What the reference promises, what
unreleasedmeans on a page, and the four ways to run a Leviathan program. - The execution engines — The three ways the compiler runs a program, why they always agree, and the few places where one of them has to refuse a program.
- The native backend: LLVM — How the LLVM backend turns a program into a native executable, what it covers, and the runtime limits of natively built programs.
- Cross-compilation: --target and per-target runtimes — Building executables for another operating system or processor, what the build needs for each target, and what a target can reject.
- Ownership analysis and memory verification — How the compiler decides which allocations die with their function, and the options that report and verify that analysis.
- Two tools: trident and leviathan — How the package manager and the compiler divide the work, what the build plan between them is, and the commands that build and run a project.
- comptime — run the language at compile time —
comptimevariables, expressions andifstatements evaluate ordinary code during compilation and fold the result into the program. - import() — comptime file inclusion —
std::import(path)reads a project file at compile time and folds to its contents as acomptimestring. - Imports — uses and use — Every library, the standard library included, reaches a file only through an import:
usefor one name or a namespace,usesfor all of a namespace's names. - Namespaces — Group declarations under a name, reopen a namespace to add to it, nest namespaces, and reach members with
::. - Rules — match a shape, inject code — A rule matches declarations by shape and injects quasiquoted code at a named anchor, with
match,where, andinject … at. - Procedural macros — comptime code returns code —
macro name(string payload) comptime { … }runs at compile time, receives a string, and returns the code that replaces the call.