LEVIATHAN vd52e79c4 · d52e79c486

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-native and --native-obj need the output path as the next argument.
  • --run and --ir execute the program in the compiler's own process. The other modes produce an executable or text and do not run the program.
  • --runtime only affects linking. --target also changes what the target:: 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-checks with 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.
  • --batch takes 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, status 2), 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 exits 2.
  • A --batch leg'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 as shared-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 a job id=<id> file=<path>|plan=<path> [cwd=<dir>] [native=1] [arg=<a>]... record followed by its leg 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 (obj for native-obj, bin for build-native). Every path is relative to the job's cwd. Blank lines and lines starting with # are ignored. A malformed file stops the batch before anything runs: error: <jobs-file>:<line>: <reason>, status 2.
  • 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 (k counts the job's legs from 0), then stats jobs=<n> legs=<n> shared-front=<n> refront=<n> errors=<n>, and exits 0. status is exit (rc is the exit status), signal (128+n for death by signal n), timeout, killed or error (125: the leg could not start, and its reason goes to the batch's standard error).
  • A leg's timeout counts 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 own timeout would. With a kill-after greater than 0, rc is what a shell's $? shows for timeout -k <kill-after> <timeout> leviathan …: at timeout the leg's process group gets SIGTERM (then SIGCONT), and rc is 124 (timeout) if the leg ends within kill-after, else 137 (killed) after SIGKILL. With kill-after 0 or absent the group gets SIGKILL at timeout (killed, 137), as timeout -s KILL <timeout> leviathan … gives, so a batch never waits on a leg that ignores SIGTERM. A stopped batch (SIGTERM, SIGINT, SIGHUP) kills every leg's process group first, so no process a program started outlives it.
  • The batch exits 2 for a malformed jobs file or a refused option, and 1 when the standard library cannot be read. --prelude <dir> and LV_PRELUDE_DIR name 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's cwd.

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 --version prints 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 backend for --emit-llvm, --native-obj and --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. --typed is 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 --ir engines ignore --typed.
  • The cache's verify mode 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-rules is a debugging aid. Rules do not fire under it, and a program that calls a macro does not compile.

See also