Command line
jihoo fmt <paths> [--check|--write] [--width N] format source or check its layout
jihoo deps <file.jh> [--tests] [--manifest] print the loaded source files
jihoo deps --manifest-batch <files...> write one manifest result per file
jihoo check <file.jh> [--lib] check without generating code
jihoo lsp [-I dir] [--target t] serve the Language Server Protocol on stdio
jihoo run <file.jh> [link inputs] [-- args] compile and run a program
jihoo build <file.jh> [-o out] [link inputs] compile a program
jihoo test <file.jh> [link inputs] [-- names] run the file's #[test] functions
jihoo emit-mir <file.jh> print the compiler's MIR
jihoo emit-llvm <file.jh> [-o out] print LLVM IR
jihoo emit-obj <file.jh> [-o out.o] emit an object with LLVM
jihoo emit-tokens <file.jh> print the tokens of one file
jihoo emit-ast <file.jh> print the syntax tree of one file
jihoo emit-program <file.jh> print every module a program loads
jihoo --version print the compiler's version
jihoo --version (or -V) prints jihoo and the release the compiler
belongs to, such as jihoo 0.2.0; jihoo --help prints the usage.
emit-tokens prints one token per line (its byte range, whether a newline
came before it, the token), and emit-ast the syntax tree as
S-expressions with byte ranges, and emit-program every module the
program loads (its name, file and imports, then its tree); they exist to compare the compiler with the one
written in jihoo (Self-hosting).
A program with errors gets all of them in one run, in source order (the first 20 are shown), each with notes: where a moved value went, where a conflicting borrow started, and which generic instance, used where, an error is in. Type errors come first. Move and borrow errors are reported once the program has none.
| option | |
|---|---|
-O0 … -O3 |
LLVM optimization (default -O2) |
-g |
line tables for debuggers and profilers (build, run, test, emit-llvm, emit-obj) |
--release |
integer overflow wraps instead of trapping |
--no-cache |
disable reads and writes for the compiler caches |
--target x86_64|aarch64 |
the machine to compile for (Linux, or UEFI for a #![uefi] program) |
-I <dir> |
also look for modules in <dir> |
-o <file> |
the output |
--keep-ll |
keep the LLVM IR next to the output |
--lib |
omit the entry point, using check, emit-obj or emit-llvm |
-mno-red-zone |
never keep data below the stack pointer (kernels) |
-mgeneral-regs-only |
use no floating-point or vector registers, and reject floats (kernels) |
--sanitize=address|thread |
check memory or data races as a native program runs (sanitizers) |
--error-format=text|json |
diagnostic format for every failure (default text) |
--comptime-report <path> |
write interpreter resource measurements as a separate JSON file |
--time-passes |
report the time and memory of each phase on standard error |
Link inputs are C sources, object files and -l/-L flags, passed to the
C compiler when linking a native program.
Source formatting
jihoo fmt src/main.jh # formatted source on stdout
jihoo fmt src/main.jh --check # verify layout without printing it
jihoo fmt src/main.jh --width 80 # a different soft width
jihoo fmt src tests --check # every .jh file under src and tests
jihoo fmt src --write # rewrite the files that need it
fmt parses one file and prints its formatted source. Given several files
or a directory, it requires --check or --write. A directory contributes
its .jh files and those of the directories in it, in sorted order; entries
whose names start with . are skipped, and a directory reached again through
a symbolic link is visited once. Files named on the command line are
formatted whatever their extension. It indents four
spaces per line that leaves a delimiter open: several delimiters opened on
one line, as in f(match x { or Ok(S {, add one level together, and a
line that starts with closing delimiters returns to the indentation of the
line that opened them. A continuation line inside a delimiter whose first
element is on the delimiter’s line is indented by that delimiter alone.
It normalizes spaces between tokens, removes leading and trailing blank
lines and retains at most one empty line between source elements.
Nonempty and empty files end with one LF. Comments retain their exact
bytes, including whitespace inside comment bodies; literals keep their
original spelling and escapes.
Existing line breaks between tokens remain in place because newlines can
end statements or separate list elements. Lists that exceed a soft width
of 100 byte columns expand with a break after the opening delimiter, after
each separator and before the closing delimiter. This covers arguments,
parameters, arrays, tuples, struct fields and variant lists identified by
the parser, and blocks and matches written on one line, whose statements
(separated by ;) and arms (by ,) go on lines of their own; the blocks
of an if ... else chain expand together. Outer lists expand first; nested lists are reconsidered at their
new indentation, and only the lines holding a list’s own delimiters and
separators make it overflow, with any ?, closing delimiters and calls
without arguments that follow it, as in f(a, b).as_str()). Parameter
lists also expand for a long return type after them. A list whose only
element is a call or struct literal, as in Err(err(span, message)), lets
that element expand instead (Err(err( … ))), and a single element
that would not fit on a line of its own either is left in place; a block’s
statement goes on its own line either way, where its lists can expand.
A line still wider than the width once its lists fit, such as a long
string concatenation or condition, breaks after binary operators: those at
the line’s outermost level of nesting that bind most loosely (||, then
&&, comparisons, |, ^, &, shifts, + and -, then *, / and
%), as few as make each line fit, each continuation indented once:
let m = msg.as_str() +
" while loading the imported module and its dependencies"
if (int_kind && !is_int_name(name)) ||
(spec.kind == 'e' && name != "f64" && name != "f32") {
Blocks expand before operators break, so if a != 1 { return x } opens
its block first and breaks the condition only if if a != 1 { is still too
long. A line where a block opens outside the operators’ parentheses keeps
its operators. Commas and semicolons retain their
original spelling.
--width N accepts decimal integers from 20 through 1000. It counts UTF-8
bytes, like diagnostic columns. It is a soft target: long literals, comments
and expressions without a list or an operator to break at may exceed it. Short
lists remain compact. Function and statement blocks are not expanded just
because they contain a comma, such as a for index. Inline comments keep
their bytes and remain before the token they originally preceded; a new
break may follow an inline block comment. Multiline block comment bodies
are not reindented. Reformatting with the same width produces the same bytes.
Before returning any source, the formatter re-lexes it, requires the same
token kinds and spellings, and checks that no existing newline flag was
removed. It then reparses the result and compares the complete syntax trees
with source positions omitted. A changed tree is rejected. It formats
modules without loading imports, type checking or running compile-time
expressions, and needs neither LLVM nor a linker. Syntax errors use normal
source diagnostics, including --error-format=json when selected.
--check uses the selected width, writes nothing and exits with status 0 when every file is formatted.
When layout differs, it exits with status 1 and prints FILE: needs formatting
to standard error for each such file, or a format diagnostic with
--error-format=json. --write replaces the files whose layout differs
and leaves the others untouched. With either option, every file is
processed before failures are reported, in file order: files that need
formatting, syntax errors, and files that cannot be read or written, all
in one JSON document when it is selected. Invalid syntax also exits with status 1; invalid
options exit with status 2. fmt rejects -o, --keep-ll, link inputs and
program arguments. Without --write it reads the source files without
modifying them; it never creates files or build artifacts.
Checking without code generation
jihoo check app.jh
jihoo check -I src src/main.jh --target aarch64
jihoo check --lib src/parser.jh
check loads the root module and its imports, checks types, evaluates
compile-time expressions, elaborates moves and drops, and checks borrowing
and effect attributes.
As with a build, non-generic functions are checked even when unused;
generic bodies are checked for the instances the program requests.
By default the root module must have a main; --lib removes that requirement.
A successful check exits with status 0 and writes nothing by default. Source errors
exit with status 1 and use the same diagnostics as compilation. A name,
type, field, function, method, variant or module member that does not exist gets a note
naming the closest one that does, when one is within a third of its length
in edits (note: did you mean `count`?). Invalid
command options exit with status 2. check rejects -o, --keep-ll, link
inputs and program arguments because it produces no output file and does
not run the program.
Checking does not emit LLVM IR, load libLLVM, or invoke a C compiler or
linker. External function declarations need no linked implementation for
checking. Compile-time obligations still execute and may fail or reach the
interpreter’s limits. Checking does not establish that backend code
generation or linking will succeed. JIHOO_NO_ELAB applies only to
emit-mir, where it prints MIR before move, borrow and attribute checking.
Source dependencies
jihoo deps <file.jh> loads the program and prints the entry and all
transitive source files as sorted, deduplicated absolute paths. It includes
the implicit standard prelude and derive module. It uses the same
--target, -I, JIHOO_PATH and root profile selection as compilation.
--lib is accepted with the same source discovery as a library compile.
--tests uses test loading, including imports for the generated harness.
--manifest writes one JSON object with its schema version, target, profile,
root, ordered module graph, and SHA-256 digests of the source bytes as loaded.
Module records include their original and canonical paths and their resolved
imports. Generated harness snippets have no physical dependency path. A
load error is reported as it is for the other commands.
jihoo deps --manifest-batch [--target T] [--lib] [--tests] [-I DIR] -- <files...>
writes one JSON line per entry, in argument order. Successful lines have
the same bytes as the corresponding single-file manifests. Failed lines
contain path and error, and processing continues with the next entry.
The batch shares a snapshot of file contents, parsed imports, digests and
resolution probes for its flags. Start a new batch after editing sources.
Tests
jihoo test parser.jh # every #[test] function of parser.jh
jihoo test parser.jh -- number string # those whose names contain `number` or `string`
fn add(a: i64, b: i64) -> i64 {
a + b
}
#[test]
fn adds() {
assert(add(2, 3) == 5, "2 + 3 is 5")
}
#[test] marks a free function that takes no parameters and returns
nothing. jihoo test builds the file with a harness in place of main
(the file needs none, and its main does not run) and runs each test
function in a process of its own: the file’s, then those of the modules
it imports, directly or not, outside the standard library. Those are
named with their module, as in util.text.trims, and may be private:
each module calls its own. A test passes when it
returns. It fails when it panics (assert included), traps or exits with
another status, and only that test fails: the others still run. Output:
running 2 tests
test adds ... ok
test fails ... FAILED
failures:
---- fails ----
panic: 2 + 2 is not 5
signal 6
test result: FAILED. 1 passed; 1 failed; 0 filtered out
Each test’s standard output and standard error are kept and printed only
when it fails, followed by its exit status or signal. jihoo test exits
with status 0 when every test chosen passed and 1 otherwise. Arguments
after -- choose the tests whose names contain one of them.
The standard library’s tests run when one of its files is the one given:
jihoo test lib/std/string.jh. A file of the library given to any command
is that module (std.string), with the access to the library’s private
items it has when imported. Tests run in
native and freestanding programs; UEFI programs cannot run here. Elsewhere,
#[test] functions are ordinary functions, checked by check and build.
With -o, the test program is kept; given the name of a test as its one
argument, it runs it and exits with status 0, or with 2 for a name it does
not know.
Compile-time resource reports
jihoo check app.jh --comptime-report resources.json
jihoo build app.jh --comptime-report resources.json -o app
--comptime-report writes a versioned JSON document after semantic checking,
including when an interpreter invocation failed. It records the target,
arithmetic mode, evaluator limits and an evaluations array. Each invocation
has its obligation’s source span, success status, execution/validation steps,
cumulative simulated allocation bytes, allocation count, maximum active MIR
calls and per-function costs. Function costs are exclusive: their steps,
allocation bytes and allocation counts add up to the invocation’s totals.
Calls to the provided allocator are counted separately from their callers.
Repeated evaluation of the same expression appears as separate invocations.
Allocation bytes include retained local storage and heap allocations, even after their lifetimes end. They measure the evaluator’s cumulative allocation budget, not compiler process memory. The report excludes parsing, lowering, borrow checking, optimization and linking costs. Measure compiler time and process memory separately when comparing complete compilations.
The option works with check, build, run, emit-mir, emit-llvm and
emit-obj. It does not change interpreter limits or generated code. Reports
use a separate file, so successful checks remain silent and JSON source
diagnostics remain one document on stderr. A source-loading or syntax error
before semantic checking does not produce a report. Existing report files
are replaced; a loaded source file cannot be used as the report destination.
Phase timings
jihoo build compiler/main.jh --time-passes -o out/jihoo
phase elapsed cpu peak
load 0.074s 0.073s 47.1 MiB
sema 0.256s 0.254s 170.4 MiB
elaboration 0.112s 0.112s 172.9 MiB
effects 0.168s 0.168s 185.0 MiB
borrows 0.618s 0.617s 258.0 MiB
attributes 0.000s 0.000s 258.0 MiB
IR generation 0.193s 0.192s 258.0 MiB
LLVM parse 0.462s 0.460s 258.0 MiB
LLVM optimize 11.765s 11.693s 274.6 MiB
LLVM emit 1.962s 9.492s 373.5 MiB
link 0.216s 0.214s 373.5 MiB
total 15.831s 23.280s 373.5 MiB
--time-passes measures each phase inside the compiler and writes a table
on standard error when compilation ends: load (reading and parsing every
module), sema (names, types, generic instances, compile-time evaluation
and lowering to MIR), elaboration (moves and drops), effects (what each
function’s borrows may store or return), borrows (the borrow checks),
attributes (checking #[no_alloc] and #[no_panic]), IR generation (llvm.jh), then LLVM’s parse, optimize and emit (object
emission, in several threads for a large module), and link. check stops
after attributes, emit-llvm after IR generation and emit-mir after
MIR text; with JIHOO_BACKEND=clang, clang replaces the LLVM phases
and the link. Writing a --comptime-report is a phase of its own.
elapsed is wall-clock time; cpu is the user and system time of every
thread of the compiler and of the programs it waited for (the linker), so it
exceeds elapsed where a phase runs in parallel. peak is the compiler’s
peak resident memory once the phase ended. total covers the compiler from
loading on. Times are truncated to milliseconds.
Nothing else changes: standard output, the files written, exit statuses and
diagnostics are the same with or without the option. When compilation fails,
the phases that ran come first and the diagnostics, text or JSON, follow
unchanged; run reports before the program starts, so the program’s own
output comes after the table. The option works with check, build, run,
test, emit-mir, emit-llvm and emit-obj.
Compiler caches
Set JIHOO_CACHE_DIR to a private local directory to reuse LLVM object files. The compiler creates the directory if its parent
exists. Leaving the variable unset or empty disables caching. --no-cache
disables both reads and writes even when the directory is set.
The object cache keys exact emitted IR, target, profile, optimization,
sanitizer, codegen units and the resolved LLVM installation. An explicit
JIHOO_LLVM file is identified before loading it by its canonical path and
file metadata, including size and modification time. Soname search bypasses
the object cache. Cached objects can be used by emit-obj, build, run
and test. The clang pipeline continues to compile and link as before.
Linking and execution still happen on an object hit.
Entries are published atomically and validated before use. An unreadable or
corrupt entry falls back to compilation. The --time-passes table shows
LLVM cache when it materializes cached objects, and object store when
it looks up and records a missed object set.
Structured source diagnostics
jihoo check app.jh --error-format=json
jihoo check --lib src/parser.jh --error-format=json
--error-format=json writes one JSON document to standard error when a
source error is reported. Loading, lexing, parsing, type checking,
compile-time evaluation, move checking and borrow checking use the same
diagnostic data as the default text format. It works with all compiler
commands. --error-format=text explicitly selects the default; if repeated,
the last format option before -- wins.
For example, a module without main produces a document with this shape:
{
"version": 1,
"diagnostics": [
{
"severity": "error",
"kind": "source",
"message": "the program has no `main` function",
"span": {
"file": "input.jh",
"start": { "byte": 0, "line": 1, "column": 1 },
"end": { "byte": 0, "line": 1, "column": 1 }
},
"notes": []
}
],
"error_count": 1,
"truncated": false
}
versionidentifies this document schema. Each diagnostic has akind, a message, primary span and orderednotes. Each note hasmessageandspan; notes include move origins, conflicting borrows and generic-instance context.- A span contains the source path as loaded and its start and exclusive end.
byteis a zero-based byte offset;lineandcolumnare one-based, with columns measured in bytes, matching text diagnostics. Editors using UTF-16 positions must convert from the source text. Ranges are clamped to the available source; zero-width ranges are valid. A missing source or an unlocated note hasspan: null. - Strings are escaped as JSON, with invalid UTF-8 replaced by U+FFFD. The numeric offsets still refer to the original source bytes.
- Errors retain text diagnostic order and the limit of 20 displayed errors.
error_countincludes omitted errors;truncatedsays whether any were omitted. Related notes are not counted as separate errors.
Every unsuccessful invocation writes one document of this schema, and
kind says what failed:
| kind | exit status | |
|---|---|---|
source |
1 | an error in the program’s source, with its span and notes |
usage |
2 | an invalid command line, such as an unknown option or command; the usage text is left out |
io |
1 | a file that cannot be read or written, or a program run cannot start |
backend |
1 | LLVM, object emission or the linker failed; the message keeps the tool’s output |
format |
1 | fmt --check found a file that needs formatting; the zero-width span is at the first byte that differs |
A failure other than source has one diagnostic with no notes, and its span
is null unless stated above. The option applies wherever it appears before
--, including after the option that failed. Success remains silent in
check mode. A running program’s own standard error and exit status are not
the compiler’s and remain unchanged. Standard output retains the selected
command’s normal output, such as emitted IR or program output.
Language server
jihoo lsp
jihoo lsp -I src --target aarch64
lsp speaks the Language Server Protocol
on standard input and output, for editors that start it as a server. It
takes no files; -I and --target apply to every document. It provides:
- Diagnostics. Each open document is checked as
check --libwould check it, with the editor’s unsaved text used for every open document in place of the file on disk, so a document checks against the open versions of the modules it imports. Checks run when a document is opened, changed or saved, once the server has no further messages waiting, so a burst of edits is checked once, and without delaying replies (below). An error is published at its own range when it is in the checked document; otherwise at the first note located there, such as the use of a generic instance, with the error’s own location inrelatedInformation; otherwise in the file it belongs to. Notes becomerelatedInformation, and notes without a location are appended to the message. - Go to definition, from the syntax trees the loader builds: a local
binding in scope (a parameter,
let/var, afor,matchor closure binding), then items of the module and of its imports, the prelude and the modules it makes visible, then variants, fields and methods by name.module.namelooks in that module andType.nameamong that type’s variants, fields and methods. The member ofx.nameorx.name(...), with any receiver (a local, a path of fieldsself.items.name, a callf().name, an indexv[i].name), is the field or method the compiler resolved it to while lowering the program (through borrows andderef, in every instance of a generic function, a trait’s default method such asto_stringincluded), as far as the program could be lowered. When it was not lowered (it comes after an error in its function, or the program does not get that far), every field and method of that name is found instead; such a request may return several locations. - Hover, on what go to definition finds (so
value.methodis the receiver type’s method): a local or parameter shows its type as the compiler inferred it, from the checked program (total: f64; in a generic function, one line per instance), and an item, field or method shows its declaration up to its body, with the//comment just above it. When the program does not check, a local shows its declaration’s line instead. - References: the uses of what go to definition finds, with its
declaration when the client asks: the members the compiler resolved to
it (
x.name,f().name) in every loaded file, and the names of the document that resolve to it, a local or an item of any module. - Rename: an edit of every declaration and reference found that way, in each file. It is refused when the new name is not a name or already appears in a file it would change (where it could capture or be captured), when a declaration or use is in the standard library, and when a program that checked would not check renamed, as when a use it cannot see remains (a module that uses an item of another, neither of them the document).
- Completion of the word before the cursor, also on typing
.. Afterx., wherexis a local or parameter: the fields and methods of the type the compiler gave it (public ones outside its module, trait methods included), found with the.wordbeing typed left out, so as far as the rest of the program checks. Aftermodule.: the module’s public items; afterType.: its variants and functions. Elsewhere: the locals in scope, the module’s items, the modules it imports, the prelude’s items, and keywords. Each comes with its kind and declaration. - Signature help inside a call’s arguments, also on typing
(and,: the declaration of the function the innermost open(calls (f(,x.method(,module.f(), found as go to definition finds it, with its parameters and the one being written. A method’sselfand a type parameter that calls infer (comptime T: type) are not among them. The call is analyzed asf()with the rest of its line left out. - Highlights: the occurrences in the document of what the name at the cursor stands for, found as references are.
- Inlay hints: after the name of each
let x = ...andvar x = ...written without a type, the type the compiler inferred (: Vec(String)), as far as the program could be lowered; a name whose type differs between generic instances has none. - Quick fixes (code actions) for the diagnostics the client sends:
for “
xcannot be changed; declare it withvar”, theletthat bindsxwhere the error is, madevar. - Document symbols: the outline of a document from its own syntax
tree, so also while it does not check: its functions, structs (with
their fields), enums (with their variants), traits and impls (
impl Show for Point, with their methods), constants, statics and type aliases. A document that does not parse has none. - Formatting of a whole document with
fmt’s default width, as one edit. A document with syntax errors is left unchanged.
Positions use UTF-8 byte offsets when the client lists utf-8 among its
positionEncodings, and the protocol’s default UTF-16 code units otherwise.
Documents are synchronized in full. Other requests return the protocol’s
MethodNotFound error. Checks run in a child process, one at a time, so
requests are answered while a document that takes long to check (the
compiler itself takes about a second) is checked; an edit that arrives
meanwhile stops that check, whose result would be for the old text, and
the document is checked again. Hover and go to definition on value.name
lower the document themselves, on the server’s thread. The server exits with status 0 after shutdown
and exit, and 1 when its input ends or exit comes first.
Debug information
-g writes DWARF 5 debug information: the line and column of the
statement, call or check every instruction comes from, and every named
variable and parameter with its type, so that gdb and lldb show values as
well as places, and perf and valgrind name source lines:
jihoo build -g -O0 prog.jh -o prog
gdb -batch -ex run -ex bt -ex 'frame 5' -ex 'info args' ./prog
#3 abort () at /…/lib/std/sys.jh:70
#4 panic (msg=...) at /…/lib/std/prelude.jh:363
#5 Vec(i64).index (self=..., i=5) at /…/lib/std/vec.jh:105
#6 pick (v=..., i=5) at prog.jh:2
#7 main () at prog.jh:8
self = @0x7fffffffa840: {ptr = 0x55555555b010, len = 1, cap = 4}
i = 5
Each function is a DISubprogram named as in error messages (area,
Vec(i64).push), without a linkage name, so that break area finds it;
break main.area.1 finds its symbol. Code that comes from another file,
such as an inlined closure or derived code, keeps that file’s name. The
entry block, where the arguments are stored, has no location, so a
breakpoint on a function stops where its arguments have their values.
Types come from the same layouts as the code (types.jh): integers,
floats and bool are base types (u8 an unsigned char, so str data
prints as text); pointers and fn pointers are pointers and borrows
references; structs, tuples (fields __0, __1, …) and closures’
captures are structures with their real offsets; str and slices are
{data_ptr, length}, closures {code, env}; arrays are arrays. An enum is
a structure with its tag and a variant part, one variant per case with its
fields (__0, …), so a debugger shows only the variant a value has:
some = {tag = 0 '\000', Some = {__0 = 42}}
r = {tag = 1 '\001', Rect = {__0 = {x = 0, y = 0}, __1 = {x = 2, y = 3}}}
With -g, native and freestanding executables also embed gdb pretty
printers for the standard library (lib/gdb/jihoo.py, in the
.debug_gdb_scripts section, as Rust’s compiler does), so that str and
String print as text, Vec and slices as their elements and Map as
its entries; print/r shows the fields:
$1 = "héllo"
$2 = Vec(String) of length 2 = {"a", "bc"}
$3 = Map(str, i64) with 2 entries = {["two"] = 2, ["one"] = 1}
gdb loads embedded scripts only from its auto-load safe path: allow a
directory (gdb -iex 'add-auto-load-safe-path .', or the same line in
~/.config/gdb/gdbinit), or load the file by hand with
source /path/to/lib/gdb/jihoo.py.
Each variable is in a lexical block from its declaration to the end of
its block, as Rust’s compiler writes them, so where a later let x hides
an earlier one, or an inner block’s x an outer one, print x shows the
one in scope there (info locals lists the hidden ones too, as for C). At
-O2 the optimizer keeps what it can: inlined
functions and variables in registers may be gone. Native and freestanding
executables keep the information; UEFI images do not (lld’s COFF linker
would put it in a PDB). Without -g the IR is unchanged, so -g does not
affect self-hosting comparisons. Paths relative to the working directory
are recorded with it ($PWD).
Sanitizers
--sanitize=address and --sanitize=thread build a native program with
LLVM’s AddressSanitizer or ThreadSanitizer: every function the compiler
writes gets the attribute (sanitize_address, sanitize_thread), the
instrumentation runs after the optimizations, and clang links the runtime
(-fsanitize=...; cc is not used then, since the runtime must be LLVM’s).
The program then stops with a report at the first memory error (a use
after free, an access out of bounds, a double free; leaks when it exits)
or data race.
Safe jihoo cannot write either; they come from unsafe code and from C
linked in, which is where the sanitizers help:
out/jihoo run --sanitize=thread tests/ffi/sanitize_race.jh
# WARNING: ThreadSanitizer: data race ...
out/jihoo run --sanitize=address tests/ffi/sanitize_use_after_free.jh
# ERROR: AddressSanitizer: heap-use-after-free ...
Every native program of tests/run runs under each without a report.
Freestanding and UEFI programs are refused, since the runtimes are built on
libc. At -O2 LLVM may remove an access it can prove out of bounds before
the instrumentation sees it, as it may for C; -O0 keeps every access.
Environment
| variable | |
|---|---|
JIHOO_LLVM |
path to LLVM 23’s shared library; otherwise search libLLVM-23.so, libLLVM.so.23.1, libLLVM.so |
JIHOO_CC |
native linker driver and compiler for C source inputs (default cc on the host, clang for cross compilation) |
JIHOO_LD |
freestanding and UEFI linker (default ld.lld; UEFI images use its COFF linker, -flavor link) |
JIHOO_BACKEND |
llvm (default), or clang for comparison with the previous backend |
JIHOO_CODEGEN_UNITS |
override the number of code generation units for build, run and test (the default is one per 20,000 LLVM instructions, at most eight) |
JIHOO_THREADS |
cap active compiler workers including the calling worker. Unset or unparseable values use the online CPU count. Integers are clamped to 1 through that count |
JIHOO_CACHE_DIR |
optional local compiler cache directory |
JIHOO_PATH |
more directories to find modules in, separated by : |
The compiler builds LLVM IR in memory, parses and verifies it through LLVM
23’s C API, runs default<O0> through default<O3>, and emits an object
with a target machine. Loop and SLP vectorization are enabled at -O2
and -O3. It uses portable x86-64/generic CPUs and PIC code.
build and run optimize the whole module at once, so inlining sees every
function, and then emit a large module as several objects on separate
threads: consecutive functions of about 20,000 instructions each, at most
eight units, linked in their original order. The units are formed by
halving, each half on a thread with its own LLVM context, so that a few
copies of the module are in memory at once rather than one per unit. The number depends only on
the module, so every host writes the same objects; a program small enough
for one unit is emitted exactly as by emit-obj. In split modules, local
functions and variables become hidden symbols, which the linker makes
local again in the executable; unnamed constants are copied into each unit
that uses them. emit-obj always writes a single object.
JIHOO_THREADS controls scheduling while keeping the units and link order
the same. It also limits workers in elaboration, borrow-effect inference
and borrow checking. Linkers and compiled programs manage
their own workers.
Native objects are linked by JIHOO_CC, including libc startup code, libm
and libdl. Freestanding objects are linked directly with JIHOO_LD,
statically, with unused function sections removed. UEFI programs are COFF
objects that JIHOO_LD -flavor link links into an EFI application
(/subsystem:efi_application /entry:efi_main); build names the image
<file>.efi unless -o says otherwise, and JIHOO_BACKEND=clang does not
build them. emit-obj needs only
libLLVM and can cross-compile without a linker or target libc. Native
cross linking additionally needs a suitable linker driver and target
libraries; a GCC cross driver supplied in JIHOO_CC selects its own target.
emit-llvm still writes the original IR and needs no LLVM shared library.
emit-obj --lib accepts a module without main, exposes its export fn
symbols and emits no startup wrapper. Link the object from C, put it in
an archive with ar, or build a shared library with cc -shared.
--keep-ll preserves that IR alongside an executable. JIHOO_BACKEND=clang
uses the previous IR-file/clang pipeline (JIHOO_CC defaults to clang
in that mode); the compiler does not silently fall back when LLVM is missing.