Development¶
For binding hardening with dependencies already installed, use
pixi run --locked verify-binding --tier core --output .cache/verify-core.
The extended tier adds sanitizer sensitivity, longer lifetime/error/thread
checks, matched memory controls, and stored timing baselines. Neither tier
fetches dependencies. See production validation
for prerequisites, gate selection, scope, and known native findings.
This page is for you if you change the bindings or the generator. Read the design principles first, because they decide what is generated and what may be written by hand.
Environment¶
Set up a checkout as described in installation. The project defines these pixi environments:
| Environment | Contents | Used for |
|---|---|---|
default |
Mojo 1.2.0, APN Mojo 1.0.2 from modular-community, Python, LLVM tools, and a C compiler (glibc ≥ 2.34 sysroot on Linux) | The generator, tests, and packaging |
docs |
Python, MkDocs 1.6.1, and Pygments 2.19.2 | Building and checking this site |
oracle |
Python with PyPI cvc5==1.4.1 |
Differential tests against the official bindings |
APN is a locked channel dependency installed by pixi install --locked. See
APN setup.
The generator, bindgen, uses the Python standard library, the C compiler,
and LLVM’s llvm-readelf, llvm-objdump, and llvm-nm for native library
inventories and exported symbols. The locked llvm-tools dependency can
inspect ELF and Mach-O archives on either operating system.
Detailed implementation notes, validation reports, and release procedures are grouped under Contributing in the navigation. The architecture overview covers the essentials for application authors.
The shared test executable targets Linux: its loader, threading and memory
fixtures use /proc/self, POSIX barriers and ELF library names. The native
package also supports macOS, where those Linux fixtures do not apply. On
macOS, generate may rewrite model outputs; commit generated files from
Linux, as CI checks them.
Repository layout¶
| Path | Contents |
|---|---|
cvc5-version.toml |
The pinned cvc5 release. Only pixi run --locked bump changes it. |
pixi.toml, pixi.lock |
The environment requirements and resolved builds, including APN Mojo. Install them with pixi install --locked. |
bindgen/ |
The generator: fetch, extract, join, report, render, diff, and bump |
bindgen/overrides.toml |
The only hand-maintained generator input, also called the exceptions file |
api/cvc5-api.json |
The snapshot, which holds the extracted facts and the join. It is generated and committed. |
src/cvc5_mojo/ |
The Mojo package: the enums, the raw layer _c/raw.mojo, one module per class, and __init__.mojo. Everything in it is generated except the runtime module _c/ffi.mojo. |
tests/smoke/ |
Raw-layer, API, smoke, lifetime, thread, and leak tests |
tests/cvc5/ |
cvc5's Python unit tests and, in examples/, its examples, translated to Mojo by bindgen.translate. Each translated example comes with what the Python example prints, recorded by bindgen.oracle. translation.json says why the remaining tests and examples do not run. calls.json, written by pixi run --locked cvc5-tests, records which C functions they call. |
docs/content/ |
This site's pages. The navigation is in mkdocs.yml. |
docs/examples/, docs/examples.json |
The runnable examples and their expected output |
docs/theme/, docs/hooks.py |
The site theme and the MkDocs hooks |
scripts/ |
The documentation tooling (the audit, the site check, and the example runner) and the runner of the translated cvc5 tests |
recipes/cvc5_mojo/ |
The conda recipe for modular-community; its tests run programs from tests/smoke/ and docs/examples/ |
third_party/ |
The downloaded cvc5 release and source archive. Git ignores this directory. |
Verification gates¶
Run these commands from the repository root. The --locked flag keeps every
dependency at the version in pixi.lock, as CI does.
Prepare dependencies once with pixi run --locked fetch, then run
pixi run --locked test. It invokes one mojo build for all runnable
Mojo fixtures, with -O0 and assertions enabled. Smoke tests, contracts,
loader scenarios, upstream tests, documentation examples, model sensitivity
controls and benchmark semantic checks use that same executable in fresh
processes. C reference programs and fault-injection libraries build separately.
APN is installed as a precompiled channel package during dependency setup.
The executable is build/shared-tests/tests. Its receipt checks source,
dependency and artifact hashes; unchanged reruns compile nothing. Use
pixi run --locked test --run-only to require reuse or --rebuild to force
one fresh build. test-build builds without running. Reports go under
build/test-results/run-*, or a fresh directory supplied with --output.
Compiler-rejection fixtures, alternate optimization/assertion settings,
sanitizers and package imports require separate builds and are excluded from
this default. A guard rejects any additional Mojo compilation inside it.
The shared build permits the existing upstream translation warnings about
discarded results and constant branches; package builds retain --Werror.
| Command | Checks |
|---|---|
pixi run --locked generate |
Regenerates everything. Afterwards, git status must show no unintended changes under api/, src/, or tests/cvc5/. |
pixi run --locked test |
All runnable suites and documentation examples from one shared Mojo build |
pixi run --locked cvc5-tests --test test_term.test_get_real |
One upstream unit test from the shared executable; repeat --test for a focused group |
pixi run --locked cvc5-tests --only floating_point |
The floating-point example, including model validation and output comparison |
pixi run --locked contracts |
String, null, single-pass formatting, integer, collection-input, returned-collection, retention, ownership, return-conversion, compound FFI, and generated-sequence regressions from the shared executable |
pixi run --locked contracts --only formatting --output .cache/formatting-<n> |
Text, call counts, nulls, returned-string lifetime, and injected formatting errors; single-pass formatting |
pixi run --locked contracts --only strings --output .cache/strings-<n> |
UTF-8 and NUL handling, buffer-size boundaries, and owned copies; shared conversion buffers |
pixi run --locked contracts --only integer_boundaries --output .cache/integer-<n> |
Exact integer values, range rejections, and native constructor selection; literal fast path |
pixi run --locked contracts --only collections --output .cache/collections-<n> |
Input and returned collection fixtures (substring filter): order, duplicates, empty arrays, conversion, and recovery; collection buffers |
pixi run --locked contracts --only returned_collections --output .cache/returned-<n> |
Detached and partial iterators, returned array/string snapshots, statistics filters/order and independent values; return conversion |
pixi run --locked contracts --only ownership --output .cache/ownership-<n> |
Borrowed owners, handle containers, exception cleanup, returned buffers, and owner/result reference accounting; cached-only commands |
pixi run --locked contracts --only return_conversion --output .cache/conversion-<n> |
Partial return conversion, pending-reference cleanup, and recovery; fault protocol and cached-only commands |
pixi run --locked contracts --only compound --output .cache/compound-<n> |
Independent C/raw/public comparisons for numeric outputs, returned arrays, nested inputs, structs, and optional arguments; scope and cached-only commands |
pixi run --locked contracts --only sequences --output .cache/sequences-<n> |
Seeded C/raw/public operation streams checked against an independent exact-arithmetic model; replay and reduction |
pixi run --locked generator-tests |
Fail-closed extraction and expected-failure classification regressions |
pixi run --locked runtime-test |
Library selection, missing symbols, version rejection, native initialization cleanup, and concurrent error isolation from the shared executable; protocol and cached-only command |
pixi run --locked binding-check |
Matched-control memory, reference accounting, and loaded-library identity analysis |
pixi run --locked matched-controls --output .cache/matched-<n> --modes results,proofs,grammar-empty,grammar-rules,commands --operations 20000 --repetitions 1 |
Cached-only C/raw/public ownership subset; see protocol and formatting failure |
pixi run --locked matched-controls --output .cache/families-<n> --modes datatype-declarations,datatypes,statistics,statistics-iter,synthesis,synthesis-copy --lifetime round --operations 100 --warmup 40 --repetitions 1 |
Complete graph cleanup against C; extended family commands and synthesis-growth finding |
pixi run --locked binding-benchmark --output .cache/overhead-<n> |
Cached-only C/raw/public timing baseline, compiled-loop inventory (GNU nm), separate call traces and limited allocation diagnostics; protocol and findings |
pixi run --locked python scripts/benchmark_statistics.py --output .cache/statistics-<n> |
Statistics snapshot timings for every filter combination, with optional paired comparison against a saved baseline; protocol |
pixi run --locked soak --output .cache/soak-<n> |
CAS-style workloads, using cached dependencies without fetching |
pixi run --locked batch-benchmark --output .cache/batch-<n> |
Sequential solver recycling comparisons using cached dependencies |
pixi run --locked soak-check |
Memory-trend, histogram, partial-checkpoint, and batch-selection analysis |
pixi run --locked docs-test --output .cache/docs-<n> |
Every documentation example from the shared executable, with exact output checks |
pixi run --locked -e oracle docs-oracle-test --output .cache/docs-oracle-<n> |
Paired Python examples against the shared expected output |
pixi run --locked -e docs docs-check |
The documentation audit, a strict build, and the rendered links, anchors, and search index |
pixi run --locked package |
Precompiles build/cvc5_mojo.mojoc |
pixi run --locked python -m bindgen.package_native --release third_party/cvc5 --prefix build/native-package-check |
Stages native libraries and license notices in a fresh prefix; packaging explains the inventory and remaining conda checks |
For a plugin-only change, use
pixi run --locked cvc5-tests --test test_solver.test_plugin_unsat --test test_solver.test_plugin_listen,
pixi run --locked contracts --only plugins --output build/plugin-contracts,
and pixi run --locked docs-test --only plugins --output build/plugin-docs.
The output directory for documentation tests must be fresh.
For oracle callbacks and null-object compatibility, use
pixi run --locked contracts --only oracles,null_printing,plugins --output build/api-compat-contracts
and pixi run --locked docs-test --only oracles --output build/oracle-docs.
The result, synthesis-result, proof, and sort upstream tests can be selected
individually with repeated --test arguments. A targeted --update-calls
preserves earlier observations except native functions that have no public
call site left in the generated bindings.
CI runs generate, requires unchanged generated files, and runs the shared
test command once. Its upstream traces must preserve tests/cvc5/calls.json.
The documentation workflow runs docs-check. The separate Linux ARM64
packaging workflow builds and tests the conda recipe; packaging is an explicit
additional build path, outside the shared executable's test run.
For an explicit compiler matrix, invoke the underlying runner directly, for
example pixi run --locked python scripts/run_contract_tests.py --optimization 0,3.
Compiler rejection checks have their own command:
pixi run --locked python scripts/run_cvc5_tests.py --compile-fail-only.
These commands intentionally perform additional compilations.
Rules¶
- Never edit generated files. Change the generator and run
pixi run --locked generate. - Never type a fact about cvc5 by hand when it can be extracted. Add the
extraction to
bindgen/and put the fact in the snapshot. - Exceptions go in
bindgen/overrides.toml. Give an entry anotewhen its reason is not obvious. - The cvc5 version lives in
cvc5-version.toml. Onlypixi run --locked bumpchanges it. The bump also moves the PyPI pin of theoracleenvironment and the conda recipe. - Document in the same change. Design decisions go on this site, not in notes elsewhere. See maintaining the docs.
Working with Mojo 1.2 FFI¶
The generated code and its tests verify these patterns. You can find working
code in src/cvc5_mojo/, which bindgen/gen_raw.py and
bindgen/gen_api.py generate, in src/cvc5_mojo/_c/ffi.mojo, and in
tests/smoke/.
- Loading.
OwnedDLHandle(path)loads a library.lib.get_function[R](name)returns a callable whose argument types are inferred at each call site.Rdefaults toNoneType. The lookup can raise. - Dynamic function loading.
get_functiontakes the native result type, not a complete function signature. To resolve a function once, keep the_DLCallable[R, origin_of(lib)]thatget_functionreturns, which is a private type. Rebind it toMutUntrackedOriginwithrebind, store it next to itsOwnedDLHandle, and call it only from a method with typed parameters. - Callbacks. Declare the function with
abi("C")and its stored pointer type withthin abi("C"). Ordinarydef(...) -> Tdenotes a callable trait and cannot be stored as a concrete field. Never unwind a Mojo error across C. The plugin bridge catches errors and retains both the callback table and its state until native deletion; see the callback implementation. boolarguments. Mojo passes aBoolto C as an LLVMi1without zero extension, asmojo build --emit llvmshows. Pass a Cboolas aUInt8that is 0 or 1, and read aboolresult as aUInt8.- Pointers. Opaque handles are
Pointer[NoneType, MutUntrackedOrigin], and C strings arePointer[Int8, MutUntrackedOrigin].UnsafePointeris deprecated.MutExternalOrigin,ImmutExternalOrigin, andImmutUntrackedOrigindo not exist.
- Indexing.
p[i]is deprecated. Usep[unsafe_offset=i]. - Strings in. Build a nul-terminated
List[Int8]withc_bytes, and pass its.unsafe_ptr(). This helper raises on embedded NUL. SMT string values use the manual escaped-string path to preserve NUL as data. There is noString.unsafe_cstr_ptr. - Strings out.
to_stringcopies into unsigned bytes and validates UTF-8 withString(from_utf8=...); it raises on invalid UTF-8. The zero-terminated UTF-32 getter has no length, sogetStringValuedecodes the lossless printed term after native type validation. - Arrays in. Pass
List[T].unsafe_ptr(), with the length as aUInt. The pointer is aPointer[T, origin_of(list)], so a parameter declaredPointer[T, _]keeps the list alive until the call returns. A pointer cast toMutUntrackedOrigin, such as a string stored in an array of strings, does not keep its buffer alive. Keep that buffer alive yourself, for example with_ = buffer^after the call. - Out-parameters. Pass
Pointer(to=x)for aPointer[mut=True, T, _]parameter. A read-only pointer does not compile there. - Arrays of arrays in. C takes the inner lengths and an array of
pointers to the inner arrays. Build every inner
Listfirst, then take their pointers. Keep the inner lists alive until the call returns. - Iterators.
for x in vcallsv.__iter__(), which may raise. It then calls__next__(mut self) raises StopIteration -> Self.Elementon the result. A generic struct that holds aList[T]needsT: Copyable & Deinitable. - Structs by pointer. Pass
Pointer(to=s), wheresis a Mojo struct with the C struct's size and alignment. AnArray[UInt64, n]field gives alignment 8. Read a field withPointer(to=storage).unsafe_bitcast[T]()[unsafe_offset=offset // size_of[T]()].comptime assert size_of[Self]() == nchecks the size where the struct is built. - Arrays out. A returned array is valid only until the next call, so copy
it into a
Listat once. Its handles are references, received by their ownership mode. Nevercvc5_*_copyanownelement. See runtime. - Global state. Mojo rejects a module-level
varwith "global variables are not supported".std.ffi._get_global[name, init, destroy](), a private function, keeps a runtime global keyed by name:initmust not raise, and it returns an opaque pointer. Box the value withOwnedPointer(value)and pass.unsafe_take_allocation().unsafe_leak(), rebound to the opaque pointer type.destroyreceives that pointer back.OwnedPointer[T](unsafe_from_opaque_pointer=p)re-adopts and frees it.- Initialization is not serialized. Concurrent first calls may each run
init. One result is kept for every caller, and the others go todestroy. - A lookup costs about 10 ns.
- POSIX threads. A
def f(arg: T) abi("C") -> Uis a C function pointer.external_call["pthread_create", Int32](Pointer(to=tid), UInt(0), f, arg)starts it, whereUInt(0)stands for a null attribute pointer. Apthread_barrier_tfits in 32 bytes.std.algorithmhas noparallelizein 1.2. - NULL pointers. A
Pointercannot be constructed null. An emptyOptional[Pointer[T, ...]]is NULL in memory, soffi.null[T]()reads one throughunsafe_bitcast.tests/smoke/test_raw.mojochecks that cvc5 receives NULL. Compare with==, asffi.is_nulldoes. - Checking generated code.
mojo precompiledoes not instantiate every type. Build and run programs against the package as well as precompiling it. Mojo 1.2 fixes the earlier false recursive-layout error for structures whose recursion is behind a pointer. - Integer bounds. In one context,
Int(UInt32.MAX)evaluated wrongly: it rejected1as out of range when it was a variable. Write bounds as integer literals. - Copies. A type with a custom copy constructor may still be
ImplicitlyCopyable. Passing a value as anOptional[T]parameter needs an implicit copy. - Docstrings under
--Werror. A summary starts with a capital letter and ends with punctuation.Args:documents every parameter, in order, or is left out. Every section body ends with punctuation. - Measuring memory. Build a program that measures its own memory with
mojo build. Undermojo run, allocations reuse memory the JIT compiler freed, and growth does not show. - Lifecycle. The destructor is
def __deinit__(deinit self), and__del__is deprecated. The copy constructor isdef __init__(out self, *, copy: Self). Neither can raise, so wrap a raising lookup intry, andabortin theexcept. - Destruction timing. Values are destroyed right after their last use. A C object that depends on another must hold its own reference. See runtime.
- Printing.
print(x)andString(x)needWritable, so implementdef write_to(self, mut writer: Some[Writer]). There is noRepresentable.repr(x)callswrite_repr_to, whichWritableprovides and a type may override.String's ownreprdiffers from Python's: it gives'it\'s'for"it's".ffi.write_python_reprtherefore quotes as Python does. - Constant tables. A
comptimeArraycannot be indexed at run time unless it isImplicitlyCopyable. AcomptimeStaticStringcan, so the enums keep their member names in one space-separated string. Slice a string by bytes withs[byte=start:end].InlineArrayis calledArray. - Big integer literals. A literal that does not fit an
Intis converted to one without a diagnostic. A parametern: Intreceives 0 for2**70, andString(2**100)is"0". Ann: IntLiteraloverload is preferred for literals and keeps them exact, asInteger(n)does in apn_mojo. Generated width/index overloads callchecked_int_literalbefore conversion. Variadic operator indices acceptIntegerso mixed dynamic values and large literals remain exact until range checking. - Small gotchas.
fnis reserved and cannot name a parameter. A docstring summary that breaks the rules above makesmojo precompilewarn, so--Werrorfails. - Packaging.
mojo precompile <pkg> -o <file>.mojocbuilds a package. Mojo 1.2 has nomojo package. - Stack traces.
mojo build -debug-level=line-tablesgives symbolized traces. See troubleshooting.
Documentation tooling checks¶
The documentation workflow also runs renderer unit tests, verifies the local
math bundle, and checks Chromium at desktop and mobile sizes. Dependencies
are pinned under docs/qa/; documentation maintenance
lists the commands and the behavior they verify.