509 Commits
Author SHA1 Message Date
waozi 3fb0214c4d Register machine-archive explain code and fix Darwin errno
Build check / check (push) Successful in 13m36s
Build check / Publish a new Ziran version (push) Successful in 0s
2026-11-24 11:01:56 -03:00
waozi f72fb1f8cc Move the compiler host runtime to bootstrap/runtime and close S18
Build check / check (push) Failing after 18m35s
Build check / Publish a new Ziran version (push) Skipped
Move every remaining host C file and compatibility header out of cmd/zir into bootstrap/runtime (removing cmd/zir) and make bootstrap/runtime/ziran_bootstrap_runtime.h the single compiled contract across all 19 runtime C files without mixing hand-written and generated type views in one translation unit.

Shrink the Makefile and assembly.mk compiler source lists to generated modules plus bootstrap/runtime, wire the generated header prerequisites for all runtime C objects, enable --runtime bootstrap/runtime on check-bootstrap and update-bootstrap, update test/script paths (including explain_cases.zi scanning bootstrap/runtime and stubbing FrontendCacheDiagnostic in standalone diagnostic fixtures), refresh bootstrap/zi2c/zi2c.c for committed 41b5c006, and record S18 completion in plans/2026-11-14-self-hosting.md.

Proof: validate_runtime_boundary reports 0 problems; standalone fixtures (compiler_files_portable, sha256, diagnostic_android, compiler_runtime_windows, bootstrap_fixed_point) pass; make check-bootstrap JOBS=2 passes all 88 roots (stage 2 reproduces stage 1 byte-for-byte with --runtime bootstrap/runtime); make check JOBS=2 CHECK_JOBS=2 passed 266/269 with explain.sh and package_darwin.sh passing on rerun (remaining site_pages failure is another lane's uncommitted docs/ZX.md edit).
2026-11-24 10:59:35 -03:00
waozi 41b5c00628 Fix the three red master checks at their source
Build check / check (push) Failing after 22m46s
Build check / Publish a new Ziran version (push) Skipped
native_cache_parallel: the Ziran zi2c driver pruned stale generated
sources in a defer that ran after CompileExecutable, while the C driver
it replaced pruned them after lowering and before the compile step.
CompileExecutable collects every top-level C file in the output
directory, so a stale generated file from an earlier layout was compiled
and failed the build before the prune could remove it; the parallel native
build never reached its link gate and the fixture timed out. Prune before
the compile step again.

semantic_edit: the canonical-patch case used / as the edit root, so the
tool opened every system directory above the checkout for reading. A CI
lane under /var/lib/gitea-native-build (mode 0711) cannot read that
ancestor, and the tool correctly rejected the request. The case now uses
the test's work directory as the root with a nested relative path.

site_pages: regenerate site/guide/usage.html from the committed
docs/USAGE.md.
2026-11-23 22:25:11 -03:00
waoziandCommandCodeBot 611fc150f3 Document and wire the thorough and quickest build modes
Build check / check (push) Failing after 23m28s
Build check / Publish a new Ziran version (push) Skipped
--thorough builds the most checked program: --checks plus every optional
compile-time verification. --quickest skips only the optional compile-time
verification: the optimizer's input and per-pass re-verification and the
encoder's re-check of the program the allocator just verified. The
pre-optimization verification, the allocator's own post-allocation
verification and the .zx loader's verification of the bytes it receives stay
in both modes, and law evaluation is never cached. Default and --quickest
outputs are identical.

The policy lives in compiler_lowered_verify and
compiler_machine_verify_allocated; zi2zx, zx2native, zi2c and zi2go take the
switches, and the native build forwards the chosen one to zx2native.
tests/check_control.sh checks identical ZX, native and C output for the
default and quickest modes, the recorded runtime checks in thorough, and the
run results. plans/2026-11-24-check-control.md lists every optional step;
Alpha costs are still to be measured.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:41:24 -03:00
waoziandCommandCodeBot 5e3d47ab5f Keep every compiler cache out of the script cache's fingerprint
The script cache keys reuse over a content fingerprint of the source tree and
publishes only when the key is unchanged before and after the build. It
ignored its native directory alone, so a cache directory another compiler
cache creates under the same root (the frontend parse cache) changed the
fingerprint and the ready marker was never written. Ignore the whole cache
root, which is build output wherever it sits.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:41:11 -03:00
waoziandCommandCodeBot 6454f15dd1 Report a declaration's value at its own column
Declaration values and assignment targets now start at their own span
instead of the statement start, so `t := TextTrim(42)` reports the argument
at 3:19 with the caret under it. The change was reverted before because the
saved-IR codec shared a literal's text with its statement's source slice, so
editing diagnostic text changed the program and editing the typed literal
rejected the IR.

A literal's text is a value, not diagnostic text: the codec now writes it as
its own string instead of a slice of the statement, and the retained flow
checks (saved_binary_cases.zi) exercise both edits again. tests/caret_columns.sh
checks the exact column and caret for a value and for a statement.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:41:06 -03:00
waoziandCommandCodeBot dfab1aefe5 Keep the runtime move out of the archive build fix
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The previous commit took assembly.mk's whole working copy, including the
selfhost lane's in-flight cmd/zir -> bootstrap/runtime object paths. That
lane has not committed the files those paths name, so restore them here;
the move stays its owner's change. The archive module line remains.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:36:27 -03:00
waoziandCommandCodeBot 509a0445dd Build the archive module into the native runtime
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
compiler_x86_archive provides the ELF archive loader the machine pipeline
calls. Add it to ASSEMBLY_NATIVE_MODULES so libziran, and not only the
zx2native driver, carries it; without this a clean build of any program
that links libziran alone fails on the archive symbols.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:36:12 -03:00
waoziandCommandCodeBot 60da11a198 Trace the k-nucleotide fixed-array value copies
The for-each over the local [16384]s64 counts array loads the whole array
and allocates a second 128 KiB block for the view; the native image has two
movups copy loops before the digest loop, and the LIR shows the load and
allocate directly. Record the addresses, the LIR ids and the fix direction,
including the mutation/alias twin needed before changing the lowering.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:35:24 -03:00
waoziandCommandCodeBot 0909e33acd Describe native ELF images with sections and symbols
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The Linux x86-64 executable now carries a section header table after its
segments: .text, .rodata, .data, .bss, .symtab, .strtab, .dynamic and
.shstrtab. _start and every program function get a global function symbol
with its linked virtual address and byte extent, so disassembly, debuggers
and profilers can name what they see instead of relying only on the map
sidecar. The program headers still map the same bytes, and no section data
is mapped.

tests/machine_elf.sh checks the section table and the _start/main symbols;
tests/machine_elf_cases.zi checks the table describes the complete file.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:33:54 -03:00
waoziandCommandCodeBot 7921e6f9c5 Note the archive row in the target coverage plan
A Linux host registration may name an ar(1) archive; the executable links
the reached members and stays static, and everything outside that subset is
assembly.gap.machine-archive. The execution matrix already refuses emulated
or cross-compiled results as row evidence.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:27:16 -03:00
waoziandCommandCodeBot 6bd03a44ff Run a series of ziran commands in one foreground session
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
ziran serve reads one command line per line and runs each through the same
dispatcher, so check, build, run, test and the rest behave as they do from a
shell without paying the launcher's startup for each one; the frontend cache
keeps repeated compiles fast. The greeting and prompt go to standard error so
a piped session's standard output is only the commands' own, Exit or the end
of input leaves, a failing command does not end the session, a nested serve is
refused, and version keeps the launcher's spelling. It is never a daemon.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:20:38 -03:00
waoziandCommandCodeBot 4cb99e5476 Reuse a module's parse from a digest-keyed frontend cache
Parsing is the frontend's largest repeated cost: every build parses every
imported module again although its bytes and the inputs a parse can observe
rarely move. A clean parse is written in the saved-IR format under a digest
over the toolchain executable, the module text, its root, the import site's
parameter binding, the defines, the module paths, the package map and the
target, with a sidecar for the facts the codec leaves out, and the next build
loads that entry instead of parsing.

Only whole self-contained modules are reused; checking always runs on the
loaded parse. A module that splices another file with #load or #insert, or
that consults an imported module while parsing, is never stored, and nothing
is published unless the process ends without a diagnostic. --lint needs a
fresh parse and bypasses the cache. ZIRAN_FRONTEND_CACHE=0 disables the
cache and ZIRAN_FRONTEND_CACHE_DIR moves it. Profiling counts hits, misses
and stores. tests/frontend_cache.sh checks hits, misses, identical
diagnostics and IR, staleness, the exclusions and a damaged entry.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:20:05 -03:00
waoziandCommandCodeBot 8e43c2b378 Link static host archives into native ELF images
Build check / check (push) Failing after 2m2s
Build check / Publish a new Ziran version (push) Skipped
A NAME.library registration may name an ar(1) archive of ELF64 x86-64
relocatable objects instead of a shared object. The Linux executable
links the members its capabilities reach, once each, with their text,
read-only data, writable data, zero fill, GOT entries and relocations,
and each capability's veneer calls its member directly, so the image
stays static with no interpreter or dynamic record.

An unsupported section, relocation or symbol is the stable
assembly.gap.machine-archive diagnostic naming the capability, member
and symbol, and the previous output is kept. Windows images link no
archive yet.

Veneer groups now record their own end, so the write-time check accepts
the alignment padding before the next group instead of treating it as a
misplaced veneer.

tests/machine_elf.sh links and runs an archive, rejects a member with an
undefined symbol, and keeps the shared-library and Windows parity cases
green. The M5/M6 plan review is recorded in ASSEMBLY/milestones.md.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 21:18:09 -03:00
waoziandCommandCodeBot 98c5fdeec0 State the bootstrap runtime boundary
bootstrap/runtime/README.md names the only C the generated compiler may keep
behind it: process and argument startup, the call into the generated zi2c
root, checked allocation and release, panic and recovery transfer, and the
file, environment, process, time, thread and dynamic-library callbacks. It
also records that the host files still live under cmd/zir and move here when
the parser recovery port lands, so the boundary check can then run over this
directory in the fixed-point proof.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 19:16:07 -03:00
waoziandCommandCodeBot 410e968963 Build the compiler runtime for the Windows target again
Build check / check (push) Failing after 25m30s
Build check / Publish a new Ziran version (push) Skipped
The zi2c worker helpers included sys/wait.h and called pipe/fork/waitpid
unconditionally, and the editor host named O_NOFOLLOW/O_DIRECTORY/openat,
fchmod, fsync, pread, realpath, renameat and unlinkat unconditionally. The
Windows cross build could not compile or link the compiler archive.

The worker helpers now keep their POSIX bodies behind _WIN32 with ENOSYS
stubs, and the editor host reports every POSIX path walk as unavailable on
Windows while providing failing definitions for the POSIX calls the generated
editor module names. compiler_runtime_windows.sh compiles and links the
complete runtime again; semantic_edit still passes.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 19:15:56 -03:00
waoziandCommandCodeBot bd18274cdc Write the zx2native driver in Ziran
Build check / check (push) Failing after 56m57s
Build check / Publish a new Ziran version (push) Skipped
cmd/zx2native.zi replaces cmd/zx2native/main.c. It reads one verified .zx,
selects host providers (including the ZX Runner's built-in file and clock
services), runs the no-fallback machine pipeline, writes the platform ELF or
PE32+, and renders the text-relative map JSON. Host discovery walks
ZIRAN_HOST_PATH and the XDG host directories in name order, reads each
.library registration and links the first library that defines a capability.
The generated copy uses the assembly set's unprefixed entry points and links
assembly-core.o plus libziran.a, like zi2zx.

cmd/zir/zir_command.h lost its last user with this driver and is deleted.

Proof: a 104-case differential against the reference C driver over six ZX
programs (ELF, PE, map stdout and files, x86_64/aarch64/armv7, fuel,
selectors, JSON diagnostics, host gaps, preserved outputs, produced
executables' exit status) has identical stdout/stderr bytes, exit status and
output files; tests/machine_elf.sh and tests/print.sh pass with the ported
binary.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 19:06:04 -03:00
waoziandCommandCodeBot fa2cafab38 Prove the bootstrap fixed point from a manifest
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
bootstrap/manifest.txt lists every generated compiler root in dependency
order with its expected generated files, including the Darwin and SIMD copies
and the zi2c driver. scripts/bootstrap_fixed_point.py reads it, regenerates
each root, compares the checked-in seeds (and rejects stale seed files),
builds the next compiler from the generated stage through a BOOTSTRAP_ROOT
indirection, and proves that compiler reproduces the same C byte for byte.
validate_runtime_boundary rejects a runtime C function its header does not
declare, and atomic_update publishes a proved stage from a fsynced .next tree.
check-bootstrap and update-bootstrap call the script; update refuses unless
its own make check passes, and BOOTSTRAP_ONLY gates named roots while another
lane's seed is stale.

Proof: tests/bootstrap_fixed_point.sh passes through the check runner and
covers a clean match, a stage-2 mismatch, a stale seed file, a forbidden
runtime function, update refusal, a failed proof stage and recovery from a
leftover pending tree. In an isolated HEAD tree the script matches scan,
text and source, and names compiler_zir_lower as stale; the stage-root
bootstrap build compiled and linked.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 18:52:05 -03:00
waozi 3d407b9093 Carry the ZX Runner's file and clock services in x86-64 executables
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
A program that imported std/guest_files or std/guest_clock stopped at a
host-capability gap: no library provides host_api, and the ZX Runner was
the only thing that did. The x86-64 linker now recognizes the nine
services by function name and signature and provides them itself
(MachineX64HostBuiltin), apart from library imports: the ELF stays static
and the PE imports only what a veneer calls. Each veneer is emitted after
the library ones. Linux veneers make the system calls with the path in a
4 KiB stack slot; Windows veneers widen UTF-8 paths to UTF-16 and convert
listed names back, through kernel32 imports the image takes only when a
program uses the service. A read or a listing grows a heap block through
the runtime's resize entry and shrinks it to the final length. The
built-in veneers carry no unwind records.

tests/machine_elf.sh builds a program that writes, reads, renames and
removes files, lists a directory and reads both clocks, as a static ELF;
tests/zx_windows_parity_cases.zi runs the same program under Wine and
checks the exact kernel32 import list.
2026-11-23 18:45:29 -03:00
waoziandCommandCodeBot 2a2f1ad709 Take the editor's C declarations from the generated module
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
cmd/zir/zir_edit.h was the last hand-written declaration of the
ZiranEdit*/ZiranTool* interface. tests/semantic_edit_runtime.c now includes
compiler_edit.h, compiler_document.h and compiler_overlay.h from the built
module directories beside libziran, and the zi-edit rule no longer lists the
deleted header. semantic_edit passes with the same --wrap=renameat/fstat
boundaries.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 18:41:27 -03:00
waoziandCommandCodeBot 5c6b4ee7b9 Write the ziran api driver in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
cmd/zi_api.zi replaces cmd/zir-api/main.c: option order, checked program
loading, module selection by checked or imported name, the bounded JSON and
text surfaces, semantic identities, document spans, ownership and laws, the
std/vec builtin table and the KIND<TAB>SELECTOR<TAB>FILE.zi example sidecars
are Ziran. The one host call the driver needs, a regular-file sidecar read
with O_NOFOLLOW and an fstat regular check, joins zir_files_host.c.

Proof: 33 reference-driver differentials (scoped, symbol, id, imports-only,
limits, defines, saved IR, options after inputs, text mode, vec builtins,
error and framing cases, five example-sidecar failures) have identical
stdout bytes, stderr bytes and exit status; tests/zir_api.sh and
tests/api_discovery.sh pass with the ported binary while the old C main is
deleted.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 18:37:13 -03:00
waozi d1de9152a0 Add ziran test and unused-name lints
Build check / check (push) Failing after 43m16s
Build check / Publish a new Ziran version (push) Skipped
ziran test FILE.zi ... runs every file the way ziran run --target=c does, prints one PASS or FAIL line per file followed by ziran test: N passed, M failed, exits 1 when any file fails, and keeps running after a failure. ziran check --lint now warns about a local that is never read and a named import or foreign declaration its module never spells (lint.unused_local, lint.unused_import); open and using imports are not judged by spelling, and unused NAME keeps a deliberate local quiet. Both codes are in the explain registry, tool_diagnostics covers the driver and the lints in text and JSON form, and docs/USAGE.md describes both. The lints over cmd/ found seven unused imports and five unused locals outside the self-hosting drivers; those are removed or marked.
2026-11-23 16:50:37 -03:00
waozi 8eb8bf24a4 Give Windows consoles each line once it ends
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The PE32+ runtime wrote buffered standard output in whole buffers, so a
program that printed before working showed nothing until it exited. The
buffered runtime now asks GetConsoleMode once, as the Linux runtime asks
ioctl TCGETS: a console gets each line once it ends and a redirected
descriptor keeps whole buffers. An image with more than one console call
imports GetConsoleMode beside GetStdHandle, WriteFile and ExitProcess.
The Windows parity test runs a paced program under a pseudo-terminal on
both systems and times its first line.
2026-11-23 16:36:33 -03:00
waozi 7fb6a9f878 Report several parse errors per file and explain the ambiguity codes
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
ParserWithRecovery now blanks the top-level declaration that failed and parses the file again, so one damaged file lists every broken declaration (up to eight regions per file) instead of only the first. Each retry keeps the file line numbers; a retry that reaches the same unterminated construct again prints nothing twice. A recovered parse still fails the command: the blanked text only gathers diagnostics. Recovery copies are allocated outside the operation memory scope so its failure cleanup cannot free what the retry still reads.

module.ambiguous and package.ambiguous join the explain registry (both diagnostics already list the matching modules), and tests/explain.sh asserts them.
2026-11-23 16:05:54 -03:00
waozi daac1b4668 Write x64 unwind data in Windows PE32+ images
Build check / Publish a new Ziran version (push) Canceled after 0s
Build check / check (push) Canceled after 3m24s
Every function with a prologue now carries a .pdata RUNTIME_FUNCTION and a .xdata UNWIND_INFO record that walks the pushed frame pointer and the stack allocation. The record starts where the frame does, after an early return that leaves before any frame exists. The Windows parity test decodes each record against the prologue bytes.
2026-11-23 15:53:12 -03:00
waoziandCommandCodeBot c885ed06a2 Write the zi2zx driver in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
zi2zx's command decisions, library linkage text, retained roots, assets,
ZX/LIR/optimization-report outputs, .zx inspection and run preflight are a
Ziran main compiled against the assembly set's own headers, matching
assembly-core.o's unprefixed entry points. The old C driver is deleted.

Proof: build modes, runs on the native and engine backends, source runs and
.zx inspection are byte-identical to the previous binary; zx_module_build,
package_zx, compile_targets, cli_defines, machine_elf, global_owned_storage,
local_owned_fields and all nine zx_* checks pass.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 15:43:36 -03:00
waoziandCommandCodeBot 6f4f4c9cb7 Write the zi2c and zx2wasm drivers in Ziran
Build check / check (push) Failing after 22m19s
Build check / Publish a new Ziran version (push) Skipped
zi2c becomes a Ziran main: option tables, context, loading, linking,
capability checks, entry selection, emission workers, SIMD helper finish
and pruning are Ziran. fork/pipe/read/write/waitpid with EINTR and error
text stay in zir_command_host.c. Its own driver is generated by the
bootstrap compiler and checked in as bootstrap/zi2c/zi2c.c for BOOTSTRAP=1;
check-bootstrap and update-bootstrap compare and refresh it.

zx2wasm becomes a Ziran main that names the engine-prefixed Wasm lowerers
directly, replacing the engine_names.h object include.

Proof: 133 tests/spec files, old vs new binaries, identical diagnostics,
exit codes and emitted .zir/.go/C bytes; 48-file worker batch; --exe,
--release, --checks, --prune-stale and bad-input parity. zx2wasm matches
on the retained ZX corpus, stdout, --unbounded and defaults. zx_wasm.sh,
compile_*, c99_target, go_*, simd_go, tool_names and cli_defines pass.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 15:36:09 -03:00
waozi ebe455c8ea Name the portable scalar subset in the ZX target contract
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
Pointer-sized isize and usize lower as 64-bit scalars with size_of 8, and a
#c_call procedure type stays native-only and rejected on this target. Record
both beside the target contract, where the subset is described.
2026-11-23 15:28:19 -03:00
waoziandCommandCodeBot 39956661b4 Write the zi2zir and zi2go drivers in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
Both tools now build from a Ziran main compiled by zi2c: option tables
come from compiler_cli, program loading/linking/capability checks call
the existing generated entry points, and the backends are unchanged.
The old C drivers are deleted.

Proof: 133 tests/spec files, old vs new binaries, identical diagnostics,
exit codes and emitted .zir/.go bytes; --exe, --minify, --checks,
--prune-stale and bad-entry diagnostics match. compile_targets, simd_go,
go_codegen, go_semantics, go_exports, tool_* and cli_* checks pass.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 15:26:38 -03:00
waoziandCommandCodeBot 17a6dbf636 Bootstrap command-line mechanics and source editing in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
compiler_cli replaces the inline rules of zir_command.h; the header keeps
the C drivers' call syntax as wrappers over the generated module. Process
niceness stays behind zir_command_host.c.

compiler_edit replaces zir_edit.c with the same ZiranEdit*/ZiranTool*
symbols. POSIX open flags and struct stat fields stay in zir_edit_host.c,
so one seed serves every host; path walking, overlay validation, semantic
ranges and atomic replacement are Ziran. tests/semantic_edit.sh now takes
the symbols from libziran.

Both seeds regenerate byte-identically; cli_defines.sh, atomic_cli_link.sh,
tool_names.sh, tool_diagnostics and semantic_edit.sh pass.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 15:16:36 -03:00
waozi 300bcbaf24 Document std ZX library boundary and verify std/utf8 shared library build
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
2026-11-23 15:07:25 -03:00
waozi 7417dcf6ae Lower isize and usize as 64-bit scalars on portable ZX
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
2026-11-23 15:05:45 -03:00
waozi 5ee3854568 Add per-library host capability grants to ZxModuleLoaderConfig
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
2026-11-23 15:01:18 -03:00
waozi 72319359da Write standalone ARMv7 ELFs from native ZX
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
zx2native --target armv7 --platform linux|android now writes a static ELF32
EM_ARM EABI5 executable for verified ZX, matching the AArch64 writer, with
no loader, libc or foreign object. compiler_armv7_runtime.zi emits the exit
and write-all routines as A32 words in Ziran source: the EABI call number
goes in r7 and the kernels are reached with svc 0, and the writer uses only
the registers a call may clobber.

compiler_armv7_elf.zi lays out the headers, entry stub, code, trap stub,
runtime, read-only globals and a page-separated writable segment, then
resolves each image relocation: MOVW/MOVT halves take the absolute address
of their symbol, and a BL takes its displacement from pc + 8. The entry stub
sets the stack limit from the process stack, calls each initializer, calls
the entry and ends through the runtime's exit; the trap stub stores the code
and exits 125.

A program whose image needs a facility this row does not carry fails before
output with assembly.gap.machine-platform-service-unavailable naming the
row. tests/machine_elf.sh now checks both ARM images' headers and keeps the
named-gap check on a formatter program.

Verified on the Moto e6 play: hello and a looping sum run as ELFs for both
linux and android, recorded in
bench/results/zx-armv7-elf-moto-2026-11-23.json. Local make check and make
check-bootstrap pass. M4's rows are all closed.
2026-11-23 10:20:12 -03:00
waozi cd43ef4610 Write standalone AArch64 ELFs from native ZX
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
zx2native --target aarch64 --platform linux|android now writes a static
ELF64 executable for verified ZX, with no loader, libc or foreign object.
The runtime is Ziran source: compiler_aarch64_runtime.zi emits the exit and
write-all routines as AArch64 words, so the console path is the same
maintained code the x86 image uses, not a byte blob.

compiler_aarch64_elf.zi places the entry stub, code, trap stub and runtime,
page-aligns the data segment so its virtual address follows its file offset,
and resolves every image relocation at link time: MOVZ/MOVK halves take the
absolute address of their symbol, and a BL takes its PC-relative
displacement. The stub sets the stack limit from the process stack, calls
each initializer in order, calls the entry, and ends through the runtime's
exit with the entry's status; the trap stub stores the code and exits 125.

A program whose image needs a facility this row does not carry - a
formatter, a host binding, the resize allocator - fails before output with
assembly.gap.machine-platform-service-unavailable naming the row instead of
emitting a broken image.

Verified on the Pixel 4a: hello and a looping sum run as ELFs for both
linux and android, recorded in
bench/results/zx-aarch64-elf-pixel-2026-11-23.json. Local make check and
make check-bootstrap pass. ARMv7 keeps its named gap until it has the same
runtime and an ELF32 container.
2026-11-23 10:03:52 -03:00
waoziandCommandCodeBot 9f0288b60f Bootstrap compiler profiling in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
cmd/compiler_profile.zi replaces zir_profile.c: opt-in phase, allocation
and counter samples, the JSON-lines report, its lock and its one-time
state. zir_profile_host.c keeps only the OS side: the monotonic clock,
peak RSS, the process id, the EINTR-safe one-append write and the exit
hook that flushes the report. The generated seed is
bootstrap/compiler_profile.

Proof: for the same zi2c run with ZIRAN_PROFILE set, the Ziran report has
the same keys, the same six phases with the same call counts, the same
five counters and the same 179 workspace allocation calls as the C
build. check-bootstrap matches the seed. The full retained suite ran 257
of 264 while the assembly lane was rebuilding the shared tools; every
failure belongs to that churn or to that lane's machine-ELF work:
install_user, direct_assembly, verified_loading_cases, zx_windows_parity
and checks_granularity_cases pass when rerun alone.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 09:57:04 -03:00
waoziandCommandCodeBot 321a82ab6e Bootstrap the executable ZX engine facade and its Wasm provider in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The executable engine's bundle reader, host-call translation, instances
and module state now build from Ziran (compiler_zx_exec_bundle.zi,
compiler_zx_exec_hosts.zi and compiler_zx_exec_instance.zi, loaded into
compiler_zx_exec), and its WebAssembly tier is compiler_zx_exec_wasm.zi.
The Linux i386 block compiler stays C as zir_exec_i386.c, and
zir_zx_wasm_install.c keeps the load-time provider install.
zir_host_exec.c, zir_zx_wasm.c and zir_zx_module_internal.h are deleted;
the host-call thread slot is S15ThreadEngine in zir_atomics.c.

compiler_check lays a procedure value out as its context and code (16
bytes, alignment 8), so a record holding one has a size.

Proof: a reference build with the C facade and this build gave identical
bundles, diagnostics and engine and native run results for all 185
programs with a main entry (121 rejected alike, 64 bundles). The full
retained suite passes 263 of 264; the only failure is another lane's
in-flight machine_elf test, which an isolated HEAD-plus-this-change tree
passes. check-bootstrap matches every module, the Windows runtime
compile and link check passes, and the wasm32 lifecycle host passes all
13 checks.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 09:37:46 -03:00
waoziandCommandCodeBot 570ab22464 Target Android SDK 33 so current Play Protect accepts the APK
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The Pixel 4a refused the SDK 28 package with
INSTALL_FAILED_VERIFICATION_FAILURE, saying the app was built for an older
Android. Min SDK stays 28; the console and Kryon pixmap bundles still run on
the Moto E6 Play (Android 9), a Pixel 3a (Android 12) and the Pixel 4a
(Android 13), and the runner is installed on all three.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 09:33:44 -03:00
waoziandCommandCodeBot 82004ab6e4 Release Ziran 0.8.0
ZX Runner installs the `zx` command: `make install-user` registers the
.zx file type and a desktop entry, so file managers open bundles with
the toolchain's runtime. Linux wraps the window, drawing and input
capabilities and Android ships the same runner as an APK. Hosted ZX
applications can open from a read callback with a smaller instruction
store, and `ziran run app.zx` hands a bundle only to a runtime provider
built by the same toolchain.

The compiler now builds mostly from Ziran source, bootstrapped from
generated C seeds: parsing, module discovery, compile-time evaluation,
IR cleanup, the frontend IR, diagnostics, SHA-256 and law checks, the
checker with generic linking and borrow analysis, the C and Go backends
with their SIMD and x86-64 assembly emitters, the checked IR codec,
module loading, locked package resolution, ZX asset collection, entry
linking and inline assembly. Native AArch64 and ARMv7 images build with
indexed relocation lookup.

The section also records the removals: std/rss_scan and
std/http_get_linux are gone in favor of std/net_http, with migration
notes. update_version.sh set VERSION, the site version strings and the
standard-library inventory (137 modules), and site_pages.py regenerated
the module pages for 0.8.0 and now links releases at the Gitea origin.
Its webp filter matches the package README's plain test command, so the
published page carries no legacy comparison.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 09:19:36 -03:00
waoziandCommandCodeBot 6031c3e35c Keep the Android runner to one program per process
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
RunnerActivity runs in the :runner process, and that process ends after a
run or after the error dialog is dismissed. A console bundle, and a failure
before the first frame, paint one plain frame when the bundle never did, so
the activity no longer waits on an undrawn starting window and blocks input
dispatch. The launcher keeps its own process, its picker and its recent
list, so a finished run cannot spoil the next launch.

Verified on the Moto: a picked console bundle runs from the app-private
copy, exits 42, and returns to the launcher; the Kryon button bundle still
renders and counts a tap.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 09:18:42 -03:00
waoziandCommandCodeBot c58823f2a9 Host ZX bundles in a ZX Runner Android app
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
packaging/android builds the same runner sources as `zx` into an APK for
armv7 and aarch64. cmd/zx_runner_capabilities.zi selects a window host by
build; zx_runner_window_android.zi answers std/guest_window through a
NativeActivity's EGL surface, and zx_android.c presents each RGBA frame as
one letterboxed texture, maps touch and key input back into the bundle's
pixels, logs the runner's output, and shows a failure in a dialog. The
launcher picks a program and keeps a recent list, and the app registers
application/x-ziran-bundle and *.zx for VIEW and SEND.

Verified on a Moto (armv7, Android 9) and a Pixel 3a (aarch64, Android 12):
the console bundle prints and exits 42, and Kryon's pixmap button bundle
renders its page and increments its counter on a tap. The APK is installed
on both.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 09:12:49 -03:00
waozi f52d16dff5 Index native image relocations on ARM
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The shared ARM image builder looked up each image relocation's machine
operand by scanning every machine relocation in the program, while x86-64
already walked a per-instruction index. Build MachineRelocationIndex once
per image and let ImageOperand visit only the relocation's own instruction,
so building an AArch64 or ARMv7 image costs relocations plus the instructions
that carry them, not their product. Both devices pass the 81-program parity:
bench/results/zx-android-parity-moto-2026-11-23.json and
bench/results/zx-android-parity-pixel-2026-11-23.json.

Closes M4 rows 5 and 6; row 7 remains in plans/2026-11-15-m4-native-arm.md.
2026-11-23 08:56:25 -03:00
waozi 7d80c7bb2a Build a ZX library from a project
Build check / check (push) Failing after 23m52s
Build check / Publish a new Ziran version (push) Skipped
`ziran bundle --library NAME --export module:function` now works in a
project: the manifest's [exports] files are the module inputs,
--require-module and --import pass through to zi2zx unchanged, and no app
entry is injected. A build that names both --library and --entry keeps
zi2zx's one diagnostic naming both flags, including when -o's .zx value is
the final argument.

tests/zx_module_build.sh builds the standalone and project images, checks
the forwarded linkage, loads the project image from a module root with
`ziran run --module-root`, and covers the refusal.
2026-11-23 08:48:49 -03:00
waozi fa29de923b Add generated ZX Runner app and .zx file-type icons
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
Export matching generated artwork for ZX Runner (org.ziran_lang.zx) and
the .zx file type (application-x-ziran-bundle) to Linux hicolor sizes
16x16 through 512x512 and Android adaptive icon layers. Install the
hicolor icons in install-user and verify them in tests/install_user_cases.zi.
2026-11-23 07:36:28 -03:00
waoziandClaude Opus 5.5 4787a8d35c Fit another module's procedure to a slot; keep same-named records apart in ZX
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
A procedure taking *Vec(Item) did not fit a slot type
RunProc :: #type (args: *Vec(Item)) -> bool declared in another module:
callback_type_equal took the two modules' copies of Vec(Item) for two
types because they are two records. It now accepts copies under one name
that apply the same template to the same types, as same_declared_type
does.

Two modules with their own file-private State each have a Vec(State)
under one instance name and with the same body text. Lowering took name
and text for one type, so the second module's states[0].dir looked for
dir in the first module's State: "record member has no lowered field
identity" in ziran bundle and zi2zx, while ziran check and C passed.
Lowering now aliases an instance only when it applies the same template
to the same argument types.

tests/tool_diagnostics_cases.zi adds slot_vec and private_records, which
also run as ZX bundles. Seeds for check_value and zir_lower; the
zir_lower seed also carries c041afb6's change to compiler_zir_lower.zi.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 06:18:22 -03:00
waoziandClaude Opus 5.5 4b70f4db7d Refresh the check_program seed for the zi_ generated-name prefix
c041afb6 changed cmd/compiler_check_program.zi without its seed, so make
check-bootstrap failed on check_program.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 06:18:22 -03:00
waozi bb8e9b1b92 Give zx bundles a window: std/guest_window on SDL2
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
A bundle opens one window, draws its own RGBA pixels and presents them,
and takes pointer, wheel, key (GLFW numbering), text, resize, focus and
close events, with cursor, text input and clipboard. It runs its own
loop. cmd/zx_runner_window.zi answers the set on SDL2; zx is built with
it when pkg-config finds sdl2, and without SDL2 a window bundle is
refused with its capabilities named.

The install_user check opens a window through the installed zx on a
private Xvfb and reads its size back.
2026-11-23 06:12:08 -03:00
waoziandCommandCodeBot c041afb6de Reserve the whole zi_ generated-name prefix
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
`reserved_declaration` rejected only `zi_default_`, so a program could still
declare `zi_new`, `zi_ref` or a `zi_` SIMD helper name the compiler and its
backends spell themselves. It now rejects every `zi_` name.

Two families stay allowed because the compiler writes them itself: the
default-parameter helpers (`zi_default_<_field_>`), and the declarations marked
generated in the IR, which cover nested local procedures (`zi_local_`), enum
member adapters (`zi_enum_name_`) and the C backend's own `zi_print_` helpers.
The saved-IR path re-checks those, so exempting only the source parser's
spelling failed there; `lowered_exec` caught it.

The seven file-local kind helpers in `cmd/compiler_zir_lower.zi` move off the
prefix, and the explain entry now describes the wider rule.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 06:03:45 -03:00
waozi 64de51ca06 Release whatever tested VERSION is untagged and keep master checks current
Build check / check (push) Failing after 31m5s
Build check / Publish a new Ziran version (push) Skipped
The release step published only when VERSION changed in that exact push and
master still equalled the tested commit when the check ended. On a busy master
behind a 40-minute check, that release would never publish. It now publishes
when no v* tag holds VERSION, VERSION is above the newest tag and the tested
commit is on master, so any later passing master check can publish it.

Each master push queued another full check on Build's one native lane, so
results fell hours behind. One check now runs per ref, and a newer push
replaces the check still waiting. Cancelling the running check instead would
let frequent pushes stop every check before it finishes.
2026-11-23 06:01:28 -03:00
waozi 6a2e04fca0 Bootstrap the ZX console services in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
cmd/compiler_zx_exec.zi now holds the platform console services of
revision-28 executable ZX (zir_exec_console.h): ZxPlatformService,
ZxConsoleOpen/Write/Flush, ZxBindConsole with one print procedure per
service, and ZxExecProblemText. They leave cmd/zir/zir_host_exec.c.

The module is the first stage of the engine execution facade. It is
generated with the instruction engine from the same command and defines,
and its object is compiled under the engine's private names, so its calls
reach the engine libziran carries while its own entry points keep their C
names. This completes the Makefile rules that d6cf0432 already carries.
CompilerStandardOutput joins CompilerStandardError in zir_diagnostic_host.c.
2026-11-23 05:59:15 -03:00
waozi d6cf04323c Host bundles in-process in zx and give them files, clock, arguments and assets
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
zx now opens the bundle with the linked runtime (std/bundle_host), binds
every capability it imports from its own table and runs it natively. A
capability it lacks is named in the error; nothing else runs the app.

The base capabilities are declared in std/guest_assets (the bundle's own
embedded files), std/guest_clock, std/guest_files and std/guest_process
(arguments and environment), and answered by
cmd/zx_runner_capabilities.zi. Before this a bundle could only print.
The install_user check runs a bundle that copies an embedded asset to a
file named by its argument and reads it back.
2026-11-23 05:56:43 -03:00
waozi 777116fd67 Regenerate the AVIF package page
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
Its README shows the test commands without the build-queue wrapper.
2026-11-23 05:55:54 -03:00
waozi 39c99ca6ff Say what changed when an artifact is not published
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
`ziran pkg artifact` refuses to publish when a recipe input, the
package's ziran.toml or the source of a package in the graph changes
while the provider runs. It reported that as "artifact provider failed
or omitted a declared output", which sent AVIF's `make test` after a
provider that was fine: its ten-minute native build ran while the Ziran
checkout it uses as an override was being edited.

The message now names what changed and asks to run again. The fixture
provider can edit its checkout during the build and package_artifacts
expects the new message; the package guide says so.
2026-11-23 05:51:01 -03:00
waozi a097975fae Bootstrap the hosted ZX module runtime in Ziran
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The runtime of include/ziran_zx_module.h now loads into compiler_host_api
from two files and replaces cmd/zir/zir_zx_module.c:

- compiler_host_api_linkage.zi reads a module's linkage text and its
  dispatch and runtime-service ABI, finds libraries under the loader roots
  or through its resolver, and checks the dependency graph with an
  explicit stack.
- compiler_host_api_modules.zi holds the loader, application programs,
  library instances behind handles, export calls through the dispatcher,
  hot replacement with state migration, and the zx_module services.

The C interface and its diagnostics are unchanged. Only the stat identity
check stays in C, as S15FileIdentity in zir_files_host.c beside the other
file probes.
2026-11-23 05:50:12 -03:00
waoziandCommandCodeBot 2ad2bc45c2 Assert that ziran init keeps the project's toolchain ref
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The merge rule already keeps a project's own `[toolchain] ref` and reports
`kept ref = ...; the template has ...`, but nothing exercised it: the template
fixtures all share `ref = "master"`, so keeping and adopting looked the same.
Set the project's ref to a distinct value, run `init`, and require both the
report and the surviving value, then restore the fixture and relock it.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 05:38:23 -03:00
waozi 310ef0f841 Regenerate the WebP and CLIP tokenizer package pages
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
Their READMEs no longer wrap the test commands in build-queue, which is
gone; the rendered package pages follow.
2026-11-23 05:33:22 -03:00
waozi 3e6c195401 Run the quick Ziran build on Build's primary host slot
Gitea's native admission refuses every job to a shared runner that carries
a build-native-* label, so the primary slot's label is now build-primary.
ccache is installed on the Debian host, where ci_packages.sh cannot run.
2026-11-23 05:33:15 -03:00
waoziandCommandCodeBot b82a57df11 Run the ten one-line check launchers from the check plan
Build check / check (push) Canceled after 0s
Build check / Publish a new Ziran version (push) Canceled after 0s
The launchers only started one Ziran check program, so each becomes a
`check_programs` row that takes the compiler path the same way: `gzip` keeps
its `zi2c` argument (a new `compiler` field) and `executable_bundle` keeps the
`LDLIBS` library and `cmd` module path. `constant_time` and `queue` shared the
check-bundle-run shape, so `spec_selftest` bundles both source and saved
checked IR for each and compares the printed result, which is stricter than the
scripts it replaces. The suite is 263 checks, down from 273.

Also records the owner's queue decisions in plans/open-work.md: check control,
`ziran serve` after the cache, metaprogramming last, and the three dropped
items.

Co-authored-by: CommandCodeBot <[email protected]>
2026-11-23 05:32:46 -03:00
waozi 9c343e3f84 Check master pushes on Ziran's native Build runner and add the release job
Build check / check (push) Failing after 1h30m19s
Build check / Publish a new Ziran version (push) Skipped
5db3d3c3 routed master pushes to the repository's native Build runner
and added a release job; 51e4505d dropped both again by accident while
the working copy kept them. They are back, with the shared slot named
build-primary for other events: Gitea reserves the build-native- prefix
for repository lanes, so no runner served build-native-primary.

On a master push the check runs through gitea-native-build on
build-native-ziran, whose host already has the packages the install step
would fetch. The release job needs that check and runs
scripts/release_gitea.py, which publishes a version only when VERSION
advanced in the push; VERSION is unchanged here, so this push publishes
nothing.
2026-11-23 05:31:38 -03:00
waozi 3f8c4b99bf Bootstrap the ZX command runner in Ziran
Build check / check (push) Canceled after 0s
cmd/compiler_zx_run.zi replaces cmd/zi2zx/zx_exec_run.c: console-bound
command runs on the instruction engine, NAME=SHA256=PATH module images
checked by digest, dependency module loading from roots or the image map,
the portable entry check, and the lowering, optimization and executable
ZX writing behind zi2zx's ZX, LIR and optimization-report views. Its
records match cmd/zi2zx/zx_exec_run.h field for field, so zi2zx/main.c and
the web bundles call it unchanged.

The native tools generate it with the assembly set; the web playground
compiles its bootstrap seed beside the lowering seed, under the engine's
private names.
2026-11-23 05:29:02 -03:00
waozi d47761f38c Expect the reworded missing-provider message in direct_assembly
Build check / check (push) Canceled after 0s
5ec1bf02 split the rejected --bind message into its cases. The direct
assembly check still looked for the old combined wording; it now expects
"exported Ziran provider is missing: ...; no module missing exports
Provide", the case it sets up.
2026-11-23 05:17:44 -03:00
waozi 399160b629 Add ZX Runner: the zx command, the .zx file type and its opener
Build check / check (push) Canceled after 0s
zx app.zx runs any bundle with the toolchain's runtime, as Linux runs
an ELF file, and hands it to no other program. It explains a file that
is not a ZX program or uses an older or newer ZX format, names a bundle
that needs capabilities it lacks, and shows failures in a dialog when
started without a terminal.

make install-user installs zx, the application/x-ziran-bundle type
(*.zx and the ZX\0\0 header), the org.ziran_lang.zx desktop entry and
makes it the default opener. The install_user check covers all of it.
plans/2026-11-23-zx-runner-platform.md holds the remaining stages.
2026-11-23 05:05:12 -03:00
waozi 5ec1bf02f5 Say which side of a rejected --bind is missing, or who already binds it
Build check / check (push) Canceled after 0s
A --bind that failed said only "host capability or exported Ziran provider
is missing or already bound". It now names the case: a host capability
the module does not declare, a provider the module does not export, or a
capability already bound by another provider, with both providers and
their files. A model that had two files exporting Frame could not tell
which one competed.

tests/host_bindings_cases.zi checks all three messages.
2026-11-23 05:01:14 -03:00
waozi 4499383fb7 Bootstrap the ZX embedding API in Ziran
Build check / check (push) Canceled after 0s
compiler_host_api replaces zir_host.c, the implementation of
include/ziran_host.h: opening bundles from files, bytes, owned bytes and
read callbacks, their SHA-256 code identity, capability ABI comparison,
binding validation and backend selection, instances on the instruction
engine, native code or a wasm provider, run control, module state export
and import with its 16 MiB budget, and hot-swapped components. It is one
module read from compiler_host_api.zi and compiler_host_api_state.zi; its
records mirror ziran_host.h field for field and it exports the same C
functions, so embedders, zi2zx and the hosted module runtime link it
unchanged. libziran builds it beside the engine, native and wasm layers it
calls; its seed is under bootstrap/compiler_host_api.

Only the target checks stay in C: zir_host_native.c now answers
BundleNativePlatformBackend and BundleAutoPlatformBackend, the
__EMSCRIPTEN__ and Linux CPU #if tests the embedding API asked before.

libziran built with zir_host.c and with the port exports the same 65
Bundle* and ZxRunControl* functions, every one ziran_host.h declares.

C's long is pointer-sized on wasm32, so ftell and fseek here and strtol
in compiler_inline_asm are declared with isize; a 64-bit declaration made
wasm-ld replace those calls with traps in the web builds of libziran.
2026-11-23 04:57:14 -03:00
waozi ccc44bd825 Test and document nested rows, the stopped-check note and package API queries
Build check / check (push) Canceled after 0s
tool_diagnostics builds and runs a nested array literal, expects the
note under a syntax error and that another file's errors are not listed
with it, and checks that `ziran api` text lists fields and members.
package_zx queries `css/Api` and `kit/Kit` in a project, puts an option
after the file and expects the error for a module that does not exist.

The reference documents `using X :: #import`, nested array literals and
`ziran api PACKAGE/MODULE`; the API discovery guide describes the
project forms. Guide pages and llms.txt regenerated.
2026-11-23 04:52:46 -03:00
waozi a595d4400d Print a package module with ziran api PACKAGE/MODULE
Inside a project `ziran api` needs no --project, and a module is named
as an import names it: `ziran api kryon/button` or `--module
kryon/button`. The launcher turns the dependency alias into its package
identity, so the same module name in two packages stays apart; a
standard module is `std/NAME`. Options may follow the input files, which
used to be read as more files. A name that selects no loaded module is an
error listing the modules instead of an empty result. Text output lists a
record's fields and an enum's members on the type's line.
2026-11-23 04:52:46 -03:00
waozi 07533fba59 Say under a syntax or import error that checking stopped there
A syntax or import error ends `ziran check` before any other file is
checked. A model probing one file read the missing errors of that file as
a clean result when an earlier file had such an error. The error now
carries a line, like its excerpt and fix lines: "note: checking stopped
at this error; errors after it, in this file and in other files, are not
listed until it is fixed". JSON output keeps one record per diagnostic.
2026-11-23 04:52:46 -03:00
waozi fd895bcf5e Type a nested array literal row by the element type
`table: [3][3]string = .[.["a", "b", "c"], ...]` failed with one "array
initializer element type mismatch: [3]string" per element. An untyped
`.[...]` is given the declaration's type when it is parsed, and a row
inside another literal kept that whole type instead of the element type.
The array literal check now gives such a row the element type, so nested
literals work at file scope and in procedures, as the `.{.{...}}` form
already did. Seed for compiler_check_expr.
2026-11-23 04:52:46 -03:00
waozi 95187576c9 Put the guide pages back to the committed docs
The previous commit rendered usage and zx from docs/USAGE.md and
docs/ZX.md edits that are still uncommitted in the working copy, so the
pages ran ahead of the committed docs. They are back to what the
committed docs render; the pages change with those doc edits.
2026-11-23 04:29:56 -03:00
waozi f82b47982a Regenerate the guide pages for the inline assembly and link docs
docs/USAGE.md and docs/ZX.md changed with the self-hosted entry linking
and inline assembly commits; their rendered guide pages were left stale
and the site check failed on them.
2026-11-23 04:29:28 -03:00
waozi 1866499455 Bootstrap inline assembly checking and C emission in Ziran
Build check / check (push) Canceled after 0s
compiler_inline_asm replaces zir_asm.c and zir_asm.h: reading #asm
variants as the source reader keeps them and resolving their constant
arguments, the register, clobber and template checks, block bindings and
the checked operand metadata the Go assembler reads, and GNU C emission
with isolated feature helpers, cached runtime selection and the
ZIRAN_ASM_CHECK comparison build. It is one module read from three files
(compiler_inline_asm.zi, compiler_inline_asm_check.zi and
compiler_inline_asm_emit.zi) and keeps the C names its Ziran callers bind
to. zir.h and zir_emit.h drop the declarations no C file calls any more.

Two stage-0 compilers built from the same seeds, one with zir_asm.c and
one with the port, generated identical C, diagnostics and exit codes for
all 13 sources that use #asm, covering block and procedure variants, x86,
AArch64, ARMv7 and WebAssembly guards, feature helpers and the check
build.
2026-11-23 04:15:40 -03:00
waozi 8c6605ef09 Bootstrap entry linking for the C, Go and native backends in Ziran
compiler_zx_link replaces zir_link.c: host capability binding, the
private copy of the checked program, dead statement and constant-branch
pruning, unused record field pruning, and the reachability closure that
decides which functions, types, constants, globals, imports and modules
an entry keeps. It is one module read from three files
(compiler_zx_link.zi, compiler_zx_link_prune.zi and
compiler_zx_link_reach.zi) and exports the same C entry points
BindHostProvider, BindHostModule, NativeLink, NativeGoLink and
ProgramUsesFunction, so zi2c, zi2go, zi2zir, zi2zx and the bundle link
test link it unchanged. Both compiler stages build it; its seed is under
bootstrap/compiler_zx_link.

A reference build with zir_link.c and a build with the port produced
identical C, Go and saved IR, diagnostics and exit codes for all 552
--entry links over the 184 programs with a main in examples/ and tests/.

The self-hosting plan records the port and gives zir_zx_module.c its
row; the rest of S16 and S17-S18 remain.
2026-11-23 04:15:40 -03:00
waozi 8a64a61a84 Restore the ccache symlink skip in the check cache's tool lookup
Build check / check (push) Canceled after 0s
5db3d3c3 made the check cache skip a compiler name that is only a ccache
symlink, so cached checks key on the real compiler. 51e4505d, a commit
about loop optimization, dropped that hunk again while the working copy
kept it. This puts it back unchanged.
2026-11-23 04:14:00 -03:00
waozi f754f6441c State the shared-index commit rule and ignore zi2c's directory lock
Build check / check (push) Canceled after 0s
AGENTS.md told lanes to stage through a private GIT_INDEX_FILE. The
owner's rule is the shared index: add only your own paths and commit
with `git commit -- <those paths>`; no private index, plumbing, rebase,
reset or stash.

zi2c writes .build.lock into the directory it emits, which left one in
bootstrap/compiler_c_emit after a seed regeneration.
2026-11-23 04:12:41 -03:00
waozi 390c94b85b Record the Rill row and emulator measurement runs
Raw samples from the Rill row-kernel variants (before, after, 32-bit
division and word forms, paired and C baselines), the compact-engine run
and the local emulator run of 2026-11-21.
2026-11-23 04:12:24 -03:00
waozi a1fcbe9bef Record the widget native comparison and profile runs
Raw samples of the Kryon widget native-versus-C comparisons and SIGPROF
profiles taken on Omega while the native x86-64 record, call and
allocation changes were tried, one file per experiment. They are
development measurements, not site figures.
2026-11-23 04:12:24 -03:00
waozi a200101561 Pass the module build to ZxExecBuild in the web bundler and playground
ZxExecBuild takes the module link description before the assets. The two
web entry points still called it without one and no longer compiled;
they pass an empty description.
2026-11-23 04:12:23 -03:00
waozi 025e29c5c9 Add site pages for the six new standard modules
Build check / check (push) Canceled after 0s
bundle_guest, list, pool, rune_text, tuple and zx_conc get their API
pages, rows in the module index, sitemap entries and the count of 132
standard modules on the home and module pages.

The pages are generated for this commit's VERSION (0.7.0). The working
copies of index.html and modules.html that carry unreleased 0.8.0 text
stay uncommitted with the rest of the release preparation.
2026-11-23 04:11:18 -03:00
waozi b605ffe25a Show only measured figures with units on the targets page
/targets dropped its lead text, pipeline strip, "Verified" state labels,
ratio-to-C columns and the method and provenance paragraphs: each example
cell now shows its run time per call and opens the generated output, and
the benchmark tables show times only. The benchmark and target generators
write that form, and the page's script and styles lose what the removed
parts used.

tests/site_targets_cases.zi adds SiteTargetsPresentation, which refuses
those removed parts in the page's main content.
2026-11-23 04:08:35 -03:00
waozi 96ac611dd0 Add the Limbo replacement plan and its migration scanners
The plan covers replacing Limbo and Dis with Ziran and ZX in TaijiOS.
scripts/scan_limbo_migration.py reproduces its counts of Limbo constructs
across a source tree, and scripts/m2zi.py drafts Ziran declarations from
Limbo module interfaces.
2026-11-23 04:08:12 -03:00
waozi f706bb19bb Add standard modules for porting Limbo programs
std/list is an arena-backed singly linked list for Limbo's `list of T`,
std/pool a generational slot pool for cyclic and reference-graph
structures, std/tuple the generic Tuple2 and Tuple3 records, and
std/rune_text UTF-8 rune operations with Limbo's string semantics
(invalid bytes decode to U+FFFD with width 1). std/zx_conc declares the
portable channel and task services a ZX host may grant, and
std/bundle_guest the child-execution capabilities of a portable
coordinator.
2026-11-23 04:08:12 -03:00
waozi 6920f1551f Add the widget native comparison and profile to the benchmark runner
Build check / check (push) Canceled after 0s
bench/bench.zi lists widget-native, which freezes public two-frame Kryon
Text, Input and Button builds and measures matched native and C runs, and
widget-profile, a SIGPROF profile of the warmed widget entry through its
native runner. The native-speed plan points at the i386 execution plan
and records that its preliminary gains were not reproduced on Alpha.
2026-11-23 04:07:38 -03:00
waozi 26a5e035fa Check typed pointer indexing and heap growth between neighbors
native_instance runs heap_arena_reuse's typed model memory on every
backend and expects a pointer or bounds trap for a negative index and one
past the extent. lowered_exec grows a block that fits between its two
neighbors when no single hole could hold a replacement, keeping the arena
size and both values.
2026-11-23 04:07:38 -03:00
waozi 67c4681f0a Copy less when native x86-64 code loads, returns and passes records
A loaded record snapshot that only constant extracts read copies just the
first-level members those extracts reach, named by an immediate mask the
machine verifier checks; whole-value uses keep the full load. Several
returned record values share the caller's result memory when each is
built and used only in its own terminal return block. Records up to the
vector cutoff are copied and cleared with straight-line vector moves
instead of a counted loop. The register allocator places a join after a
connected predecessor whose allocation is known rather than beside an
unrelated cold block.

native_large_global_fields checks exact copy and zero tails on both
sides of the vector and loop cutoffs, with sentinels and aliased caller
storage; the machine field, place and x86 encoder cases cover the new
forms.
2026-11-23 04:07:38 -03:00
waozi d1ae0da903 Skip the grapheme tables for ASCII text
Between two ASCII scalars only CR+LF forms a cluster, and an ASCII
scalar's break property is control, CR, LF or none. NextGrapheme and the
property lookup answer those directly; a following non-ASCII scalar still
goes through the full rules.
2026-11-23 04:06:59 -03:00
waozi 4666d3f938 Point the cli and lib templates at the Gitea toolchain
Gitea is the primary repository and GitHub a mirror. A project made from
these templates now pins its toolchain from git.waozi.xyz, like the
other templates.
2026-11-23 04:06:59 -03:00
waozi ff583fe0f0 Give mirror URLs of one overridden checkout one module namespace
Two dependencies that name one repository by different URLs, such as its
Gitea and GitHub addresses, are two lock entries. A local override that
selects one checkout for both made the compiler load each source file
once but under two package identities, so the build failed on the second
namespace. An overridden package now takes the identity of an earlier
entry that selects the same checkout.

tests/package_pin_cases.zi adds OverrideMirrors: the app builds and the
saved lock keeps its bytes.
2026-11-23 04:06:59 -03:00
waozi bac564d64a Declare Go's uintptr as a foreign builtin type
A Go function that takes or returns uintptr, such as (*os.File).Fd, could
not be declared: only `any` and `error` were accepted from go:builtin, and
`uint` is a different Go type. `#type #foreign builtin "uintptr"` now names
it, and an explicit cast converts it to a Ziran integer.

The Go foreign-types fixture reads a file descriptor through it. The
guide documents the declaration; seed for compiler_type.
2026-11-23 04:06:44 -03:00
waozi 9629368999 Give one type application one C name in every module
Build check / check (push) Canceled after 0s
0fe03609 gave Vec(Entry) in one module and Vec(C.Entry) in another the
same instance name. When a third module has its own Entry, its Vec(Entry)
shares that name too, so all three are mangled, and the mangled name
hashed the module and the place the application was written. The two
spellings of one application then had two C types: Harmony's
workspace_ledger.c failed with "invalid initializer" on the Vec(Entry)
that token_collection's Selected returns.

A mangled type application is now named by what it applies: its template
and each argument type, where those are declared. Every module that
spells one application emits one native type, and another module's own
Entry still gives another. Declared types keep their names.

tests/tool_diagnostics_cases.zi adds shared_vec, a build case with two
more modules that fails without this. Seed for c_emit.
2026-11-23 04:04:06 -03:00
waozi 203800c091 Hash check inputs in batches and remove make check-incremental
Build check / check (push) Canceled after 0s
check-runner --incremental fingerprints every input of the suite before
and after a run. It started one sha256sum for each of about 3,300 files
and dropped duplicate paths with a quadratic scan, so a run spent
11-12 s on Omega before any check started. It now hashes 256 files per
sha256sum run and drops duplicates after sorting: 0.6-0.8 s per run,
and the runner's self-test still passes its cache invalidation cases.

make check-incremental is removed. The fingerprint covers every input,
so after any one-file edit no result is reused (measured: 1 executed,
0 reused), and only fuzz_regressions.sh is audited for reuse. The
target could not beat make check after an edit; make check
CHECK_FILTER=<name> serves that rerun. make check is unchanged.

plans/2026-11-23-go-check-groups.md records the numbers and maps every
removed Go check to its replacement.
2026-11-23 03:06:24 -03:00
waozi ebf1c642be Group the two Go assembly checks into go_codegen
go_assembly.sh and go_direct_assembly.sh only launched
go_assembly_cases.zi and go_direct_assembly_cases.zi. Their main
procedures became GoAssemblyMain and GoDirectAssemblyMain, and
go_codegen_cases.zi runs both as parallel cases of one check through
the GoChildren pool in go_case_support.zi. The suite has 263 checks.

The native.assembly feature now names the two case programs as its
evidence; docs/FEATURES.json is regenerated from `ziran features --json`,
and the guide, its site page, the assembly feature matrix and the
self-hosting plan name the case programs instead of the wrappers.
2026-11-23 03:06:01 -03:00
waoziandClaude Opus 5.5 0fe03609a9 Give one application one type across modules; keep C names off the runtime's
Build check / check (push) Canceled after 0s
A pointer to Vec(Db.Match) could not reach a procedure of Db that takes
*Vec(Match), nor Vec(*Db.Frag) one that takes *Vec(*Frag): the two
spellings got different instance names, and same_type_application also
required the expanded bodies to match as text (*Match against *Db.Match).
Instance names now hash a qualified argument type the way its own module
spells it whenever the bare name means the same type here
(type_application_identity), so both spellings name one type for the
checker, C, Go and ZX alike. same_type_application compares the template
and the resolved arguments under pointer, slice and array shapes instead
of the body text. The checker accepts two spellings of one application
only when they share that name, because only then do the backends emit
one type; a module whose own Match hides Db.Match is still rejected.

A constant becomes an object-like C macro, so String :: 2 rewrote the
runtime's String typedef, length :: 3 every .length member, and a
file-private constant in one module a parameter of the same name in
another. Constants spelled like a runtime header name, a runtime member,
a record field, or a parameter or local anywhere in the program now take
the mangled zir_d_ name; globals and types spelled like a runtime header
or libc name are renamed the same way.

The "::" inside a multi-line file-scope string was already fixed by
c2ef7933; colon_text now also uses a typed table and the "x ::1 y" text
the TaijiOS port reported. tests/tool_diagnostics_cases.zi adds
runtime_names and module_vec, a case with a second module. Seeds for
c_emit, check_link, check_value, frontend_ir and zir_lower.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 02:55:21 -03:00
waozi a007a9cb73 Refresh checked package entries saved under another toolchain
Build check / check (push) Canceled after 0s
A ziran.lock kept across a Ziran upgrade holds checked-library entries
for the earlier toolchain. `ziran lock` refused them with "saved checked
package requires a different toolchain or profile", `ziran update` did the
same, and builds said only "invalid checked packages in ziran.zx.lock",
so the project had no way forward (Kryon's zx-test, cursor-api-test and
zx-canvas-test).

`ziran lock` and `ziran update` now look such a library up again for the
current toolchain under its saved profile; with nothing published for it
the package goes back to its source, as an unpinned package does. Builds,
`--locked` included, still stop, and name the package and `ziran lock`.
An invalid saved profile, an entry naming another package, a bad digest
and a ziran.zx.lock pin are refused as before.

tests/package_zx.sh covers the build message, both refreshing commands,
the fall back to source and the entries still refused. Its "descriptor
naming another package" case replaced the id's last digit with 0, a no-op
for one id in sixteen; it now always changes the digit.
2026-11-23 02:38:02 -03:00
waoziandClaude Opus 5.5 612bd6133a Run Ziran's shared checks on Build's native primary label [skip ci]
alpha-ziran and build-ziran already ran on Build's primary host executor;
they were container-era names. build-native-primary names the same lane.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 02:21:39 -03:00
waozi 7e0000bd41 Add make check-incremental
Build check / check (push) Canceled after 0s
make check-incremental runs the check runner with --incremental: a check
audited in tests/check_cache_audits.json keeps its passing result while no
input of the suite has changed, and every other check runs. make check
still runs the complete suite.

Only fuzz_regressions.sh is audited, and computing the input fingerprint
takes 12-15 s on Omega, so today the target is slower than make check.
plans/2026-11-23-go-check-groups.md records the measurement and what would
make it pay for itself.
2026-11-23 02:20:45 -03:00
waozi 25b81f30ce Group fourteen Go target checks into go_semantics and go_exports
Each tests/go_*.sh wrapper compiled the same helpers and started the Go
toolchain for one fixture. Two Ziran check programs now run those fixtures
as parallel cases of one check: go_semantics (bind, defer, error values,
fields, foreign types, many parameters, maps, results, select, slice nil)
and go_exports (C headers, method exports, named exports, package init).
The suite has 264 checks instead of 276.

Fixtures moved file to file into tests/fixtures/go/<case>/. Every command
and rejection table moved into its case procedure, and go_case_support.zi
states a command the way the shell line did. A command that must be
rejected now has to exit with a diagnostic, so a crash no longer counts as
a rejection.

case_pool.zi holds the parallel child pool that packages_cases.zi used;
both now share it. saved_ir.zi holds the saved IR edits so a case applies
them in process, and saved_ir_mutations.zi stays as their command-line
form for the shell checks that still call it.

The two Go assembly wrappers stay until the feature evidence names their
case programs. plans/2026-11-23-go-check-groups.md maps each removed check
to its replacement and lists the open work.
2026-11-23 02:20:08 -03:00
waozi e225a4fe6a Name a #program_export that two package revisions define in C builds
Build check / check (push) Failing after 2m32s
A Kryon app pinning Kryon at one commit and a CSS package pinning it at
another links both revisions, as packages allow. Generated C gives a
#program_export procedure one symbol, so the build died in the C compiler
with "conflicting types for LightPalette".

zi2c now checks the linked program before writing C: when two modules
define one exported symbol it reports the procedure and both modules, and
for two revisions of one package says the dependencies that pin it must
agree. Procedures the program never calls are already dropped from a
linked program and each module's `main` has its own C name, so only real
clashes are reported. ZX qualifies exports by module and is unaffected.

tests/package_zx.sh locks the two-pin graph, checks it, expects the
build error without the C compiler's message, then agrees the pins and
runs the built program.
2026-11-23 02:10:32 -03:00
waozi dd829704b1 Bootstrap checked IR persistence and package resolution in Ziran
Build check / check (push) Canceled after 0s
compiler_zir_serial, compiler_load, compiler_package_resolve and
compiler_zx_assets replace zir_serial.c, zir_load.c, zir_packages.c and
zir_assets.c. Both compiler stages link the Ziran modules, and the seeds
under bootstrap/ build stage 0.

zir_persistence_host.c supplies host paths and streams and keeps the
existing C entry points, so the tools and embedders call the same
functions. ProgramSet, ZxAsset and ZxAssets now come from the generated
headers. The checked IR format stays version 66; the saved-binary fixture
reads the version from the codec instead of the deleted C file.

Still open in the self-hosting plan: the rest of S16 (portable linking,
the ZX command runner, the embedding and execution APIs, the Wasm
provider), S17 and S18.
2026-11-23 02:09:52 -03:00
waozi 1f6cbf0775 Refresh the parse seed for the caller-location change
Build check / check (push) Failing after 1m30s
cmd/compiler_expr_ir.zi gained file reads for #caller_location without
bootstrap/compiler_parse/compiler_parse.c being regenerated, so
check-bootstrap failed on that one seed. It is regenerated from the
current sources; the header is unchanged.
2026-11-23 01:58:40 -03:00
waozi 856950ad5f Remove the link-stage #program_export uniqueness check
Build check / check (push) Failing after 1m31s
The check added for two linked revisions of one package also refused
programs that are valid: a ZX bundle qualifies each export by its module,
so several modules of one build may export the same name, and
assembly_compare, host_bindings, standalone and target_diagnostics do.
Those four checks failed on master.

Only generated C makes a #program_export one linker symbol. The link
stage is back to what it was, the package test no longer expects the
error, and docs/PACKAGES.md and the reference say what is true: two
revisions coexist, and in generated C their pins must agree when both
define one exported procedure.
2026-11-23 01:57:02 -03:00
waozi 5bf3eaa569 Regenerate stale site pages and add the Tcl and Tk package pages
Build check / check (push) Canceled after 1m29s
The committed site no longer matched its own sources. docs.html,
index.html and modules.html counted 128 standard modules where std/ holds
126. Five std pages (bundle_host, gzip_linux, image, jpeg, png_linux)
lacked declarations that std/ already exports, and nine package pages
trailed their READMEs.

site_pages.py now checks a package whose inventory URL is on
git.waozi.xyz against its Gitea origin and links its sources there, so
the inventory lists tcl and tk and each gets a page.

Every page comes from the generator run on this commit's own inputs
(VERSION 0.7.0 and the tracked std modules); site_pages.py --check
passes on the result and reported 17 stale pages on the parent.
2026-11-23 01:55:32 -03:00
waozi ac3116d543 Order the guide from everyday language to low-level code
Build check / check (push) Failing after 1m33s
docs/USAGE.md opened with inline assembly and filed language rules under
the standard library. It now starts by pointing at docs/REFERENCE.md, then
runs: commands, literals, strings, constant tables, shadowing, conditional
record construction, returned views, checks, imports, the standard
library (vectors, text, maps and files before temporary storage, SIMD and
the native adapters), then building the toolchain, output routes,
generated C and Go, saved IR, foreign functions and assembly.

Every section moves whole and keeps its heading text, so links to its
anchors hold. Constant tables, conditional record construction, audio and
the closing pointers get headings of their own. Sentences that described
an earlier compiler ("no longer", "now", "remains", "retained") state the
current rule instead. No rule is dropped: the only lines that differ from
the old file are those sentences, four headings and the opening.

The site renders the reference as a guide page now that the guide links
to it.
2026-11-23 01:49:25 -03:00
waozi b110b16a9a Note what replaces the removed std/rss_scan and std/http_get_linux
Build check / check (push) Failing after 1m32s
The only user outside Ziran is the atr project's legacy/research folder,
which its manifest's module roots, Makefile and tests do not build, so
both modules stay removed. The changelog names the replacement and the
last commit that has each module.
2026-11-23 01:45:27 -03:00
waozi cceecbbe5d Report a #program_export defined by two linked package revisions
Build check / check (push) Canceled after 1m41s
A Kryon app pinning Kryon at one commit and a CSS package pinning it at
another linked both revisions, as packages allow. Both define the
`#program_export` procedure LightPalette, so `ziran check` passed and the
C compiler then died with "conflicting types for LightPalette".

The link stage now refuses a #program_export symbol that two modules
define, naming the other module; for two revisions of one package it
says so and that the dependencies pinning it must agree on one revision.

Production locks keep each declared exact pin (docs/PACKAGES.md), and
the package tests assert both revisions coexist, so a root pin still does
not replace a dependency's pin. tests/package_zx.sh locks the two-pin
graph, expects the check error, then agrees the pins and checks again.
2026-11-23 01:43:52 -03:00
waoziandClaude Opus 5.5 2523610f6d Name caller locations the same on every machine
Build check / check (push) Failing after 1m47s
#caller_location recorded the absolute canonical path of the call site, so a
library that defaults a location parameter, such as Kryon's widgets, built
different bytes in every checkout and package cache. The file is now named
relative to the module root, or by the package from the nearest ziran.toml
and its path inside that package when the module root lies inside a
package. Other files keep their path. call_argument_cases builds the same
sources from two folders into identical bundles and checks a caller in
another package.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 01:27:48 -03:00
waozi 86db9c6295 Run bundles only on a runtime provider of the same toolchain build
Build check / check (push) Failing after 1m37s
`ziran run app.zx` handed a bundle that needs host capabilities to the
first installed provider whose --check passed, whatever toolchain built
it. Kryon's player in ~/.local/bin/zx, built from an older Ziran, then
ran bundles from a newer one: frame tests aborted silently or hung.

A registration's optional second line, `ziran IDENTITY`, records the
build of the toolchain that installed the provider; `ziran version
--identity` prints it (a digest of the toolchain's zx runner, which holds
the engine and runtime). `ziran run` skips providers of another or an
unrecorded build, and when none of its own build remains it names the
provider and both identities and exits 2 without running anything.

tests/bundle_provider_cases.zi records identities and covers both
refusals; package_zx.sh's provider records its identity. docs/ZX.md and
its guide page describe the line.
2026-11-23 01:24:18 -03:00
waozi c450e3a3f2 Add rooted child file handles and multi-member gzip decoding
Build check / check (push) Failing after 2m54s
file_tree_linux opens a configured root directory and its single-name
children with openat, mkdirat, renameat and unlinkat, never following
links or path components, so a server can confine its file stores to a
root. OpenChildRegularFile refuses FIFOs and non-regular files.
GzipDecompressMembers decodes one or more complete gzip members into a
bounded output. Both have tests, and the backend_process bootstrap
(Linux and Darwin) is regenerated for the new file_tree code.
2026-11-22 22:31:19 -03:00
waozi 8133bd41ef Resolve from source when a checked library names another toolchain
Build check / check (push) Canceled after 0s
ziran lock and add discover a package's checked .zx library at its
revision and profile. The descriptor there names the toolchain it was
checked under, and any other toolchain failed resolution with "checked
package metadata does not match its repository revision, toolchain or
profile", so moving a project to a new Ziran commit needed every package
republished first. Kryon's starter (css, image-codec, webp, avif) could
not leave toolchain 5db3d3c3.

A well-formed descriptor for the same package and profile but another
toolchain now leaves an unpinned package on its ordinary source workflow,
as a missing descriptor already did. A saved pin, an explicit profile
request, or a descriptor naming another package or a malformed digest
still fails. tests/package_zx.sh covers both; docs/PACKAGES.md and its
guide page state the rule.
2026-11-22 22:22:48 -03:00
waozi 1b27d10552 Query paths on Android without statx
Build check / check (push) Failing after 1m33s
Bionic exports statx only from API 30 and errno as __errno, so Android
apps that reached PathQuery failed to link. On Android StatxRaw fills the
same statx record from fstatat, reading each ABI's struct stat offsets.
2026-11-22 18:35:07 -03:00
waozi 2a4f6ff0da Say which std module to use for each layered job; close the audit plan
Build check / check (push) Failing after 2m19s
docs/REFERENCE.md (and site/llms.txt) name the module to reach for where
several cover one job: text, JSON, dates, HTTP and audio. They are
layered APIs, not duplicates, so none is removed.

The LLM authoring audit's last two open items both wait for other lanes
(per-declaration parse recovery for the parser port, exact value carets
for the saved-IR codec); they move to plans/open-work.md as one line each
and the audit plan is deleted.
2026-11-22 17:32:44 -03:00
waozi 1758248473 Name the Gitea toolchain URL in the packages guide
Gitea (git.waozi.xyz) is the primary host; the [toolchain] example in
docs/PACKAGES.md now names it, and site/guide/packages.html is regenerated.
2026-11-22 17:31:37 -03:00
waozi aa6998fcf4 Remove 24 benchmark run logs that no receipt cites
These .log files under bench/results/ (sigprof captures, validation and
publication test runs, zx-loops profiles) are named by no receipt, site
table, check or document. The seven logs that compiler-build receipts
name ("log": "build.log" or "first-run.log") stay with their receipts.
2026-11-22 17:30:42 -03:00
waozi adc26dac04 Remove std/http_get_linux in favor of std/net_http
std/http_get_linux.zi (39 lines) fetched HTTPS through curl beside
std/net_http, the host-capability HTTP API with Linux and curl
implementations. Its only user was the GetHttpsCapped URL case in
tests/std_input_cases.zi, whose net_http half already refuses the same
file:///etc/passwd URL; that case goes with the module. Kryon and Harmony
do not import it. Its site page and its modules.html and sitemap.xml
entries are removed.
2026-11-22 17:29:52 -03:00
waozi 4c62f8b838 Remove std/rss_scan, a module nothing imports
std/rss_scan.zi (149 lines) had no importer in Ziran, Kryon or Harmony and
no test. Its site page and its modules.html and sitemap.xml entries go
with it.
2026-11-22 17:28:33 -03:00
waoziandClaude Opus 5.5 c3ef9fb291 Let ZX embedders stop an active guest run from another thread
Build check / check (push) Failing after 2m12s
A ZxRunControl is a sticky, thread-safe stop request. Pass it to
ZxModuleProgramOpenControlled/RunControlled, or to
BundleInstantiateControlled/BundleInstanceRunControlled for a plain
bundle. The instruction engine polls it at fuel, jump, branch, call and
host-call checkpoints, in the fast and packed tiers too, so it stops
entry loops, global initializers, guest-loaded library initializers and
imported library calls. A host callback that returns after a stop
reports ZX_RUN_CANCELLED. A stop seen before entry skips the run and
leaves the program usable; one seen during execution retires it. Only
the engine backend accepts a control. Uncontrolled callers and finite
step budgets behave as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-22 17:15:27 -03:00
waozi a1ce537bb0 Key package artifacts by checkout content, not by HEAD
Build check / check (push) Failing after 2m44s
`ziran pkg artifact` mixed each checkout's HEAD into the artifact key
before and after the provider ran, and refused publication when the two
differed. Another lane committing to a local override mid-build (Kryon's
renderer-desktop) moved HEAD without changing a file, and the build
failed with "artifact provider failed or omitted a declared output".

PkgArtifactContent keys each checkout by its checked-out content: a git
tree id written from a private copy of the checkout's index after
`git add -A`, so committed and uncommitted files count alike and the
checkout's own index is untouched. Any real change to the files during
the build still refuses publication.

The fixture provider can commit to its checkout while it builds; the new
last case in tests/package_artifacts_cases.zi passes, and fails when the
key uses HEAD again. docs/PACKAGES.md and its guide page describe the key.
2026-11-22 16:43:39 -03:00
waozi debc381ccb Let checks run from a private BUILD_DIR inside the repository
Build check / check (push) Canceled after 0s
NativeStart refused any work directory outside <repo>/build/, so with
BUILD_DIR=work/NAME the five checks that put their work under the build
directory holding the compiler (zx_web_lifecycle, go_assembly,
go_direct_assembly, host_bindings, portable_entry) failed with "test
outputs must stay inside this repository's build directory". The guard
now also accepts the BUILD_DIR whose bin/ holds the compiler under test,
when that directory lies inside the repository; outputs still never
leave it. All five pass from work/llm-diag.
2026-11-22 16:37:43 -03:00
waozi d9d8764d32 Summarize every std module and read the whole s64 range in TextInteger
Build check / check (push) Canceled after 0s
ziran std --list now gives every one of the 134 modules a one-line
summary: the first sentence of its leading comment, read past imports;
for a module that only forwards to a platform module, "This platform's
std/X_linux:" and that module's summary; otherwise the public names it
declares. The test requires a summary for every module.

TextInteger read at most 18 digits, so not the whole s64 range its
comment promised. It now accumulates negatively with a constant bound,
accepting -9223372036854775808 and 9223372036854775807 and refusing one
past either end; tests/spec/std_number_text.zi covers both ends on every
target. docs/REFERENCE.md drops the workaround. Seeds that embed
text_tools (backend_process for Linux and Darwin, simd) are regenerated.
2026-11-22 16:34:43 -03:00
waozi c2ef7933a6 Read "::" inside a string literal as text in file-scope declarations
Build check / check (push) Canceled after 0s
A file-scope initializer spanning lines, such as a table of records whose
strings hold "NAME :: value" or "main :: () -> s32 { ... }", was split at
the "::" inside the string: the line classifier took it for a constant
("invalid file-scope constant") or a procedure header ("unterminated
declaration at end of file"). The classifier now finds "::" outside
string literals (code_colons in compiler_parse_source, FindCode in
compiler_source for procedure headers).

tests/tool_diagnostics_cases.zi keeps its hint table at file scope again
and builds a record table whose strings hold "::". Seeds for
parse_source and source. Multi-error recovery stays open in the audit:
it waits for the parser port.
2026-11-22 16:31:11 -03:00
waozi 9a5d17123e Accept three forms models reach for instead of explaining them
Build check / check (push) Canceled after 0s
These were top measured causes of programs not compiling; each now works
with no run-time cost:
- `for TextLines(s) { }` and `for line: Call(...)`: the loop lowering
  binds a call result to its loop_items_N temporary inside the loop's
  block, as it already did for literals, so an owned result is freed
  when the loop ends, exactly like `lines := TextLines(s)`. Slicing a
  call result still needs a local and says so.
- `LIMIT :: cast(s64)9223372036854775807;`: a cast of an integer
  constant to an integer type evaluates to the constant when the type
  holds it; a value it cannot hold is still rejected.
- `x := OwnedCall()` then `TextView(x)`: the := binding holds a string
  that keeps its bytes, and TextView of a string is that string, so the
  checker rewrites the call to its argument.

docs/REFERENCE.md (and site/llms.txt) stop teaching the workarounds.
tests/tool_diagnostics_cases.zi checks, builds as strict C and runs each
form. Live stages: compiler_ir_cleanup, compiler_check_value,
compiler_check_expr, compiler_check_statement; seeds for those only.
2026-11-22 16:23:42 -03:00
waozi e597f6052e Record why ziran init keeps a project's floating toolchain ref
Build check / check (push) Canceled after 0s
kryon init now adopts its template's exact toolchain pin. ziran init's
merge keeps the project's own values by rule, already reports the
template's ref next to the kept one, and ziran.lock pins the commit
either way, so the change is not made; plans/open-work.md says why.
2026-11-22 16:14:54 -03:00
waozi f314c9b6b6 Name the bundle option that supplies a missing host capability
"missing host capability: frame_capture:RecordFrameFailure" now goes on
to say the host does not provide it and that the bundle can supply it
with --bind frame_capture:RecordFrameFailure=MODULE:FUNCTION (an exported
Ziran function with the same signature) or --bind-host MODULE, or run in
a host that grants it. host_capability.sh runs such a bundle in a host
with no bindings and checks the message.
2026-11-22 16:14:53 -03:00
waozi 7eac27ba16 Build every program that passes ziran check as strict C
Three programs passed ziran check but failed to compile as C:
- An empty .{} global initializer emitted {}, which ISO C before C23
  rejects under -pedantic; it now emits {0}, keeping {} only for a type
  whose trailing array has zero length.
- A field or local named like a predefined C macro (bool, true, false,
  linux, unix, i386, NULL, EOF, assert, offsetof) reached the C as that
  macro; such names are now renamed like C keywords.
- A global [MONTHS]T with a named constant length was rejected against
  its [12]T initializer; the global check normalizes the declared length
  first, as locals already did.

Live stages: compiler_c_emit_call, compiler_c_emit, compiler_check_program.
Seeds regenerated where generated C changed: runtime_emit (Linux and
Darwin), context, c_emit, c_emit_call, check_program; check-bootstrap
matches every module. tests/tool_diagnostics_cases.zi checks, builds,
compiles with -std=c11 -pedantic -Werror and runs each case.
2026-11-22 16:14:53 -03:00
waozi 527c3d0b18 Keep declaration value spans at the statement start for saved IR
Build check / check (push) Failing after 1m29s
The previous commit started declaration values and assignment targets
at their own column. Saved IR then stored a typed literal such as 42 as a
diagnostic source slice, so the retained standalone check that changes
diagnostic text without changing the program (flow-text, flow-typed)
rejected the rewritten IR. Spans inside a declaration's value count from
the statement start again; the text-mode excerpt and its goldens are
unchanged. Exact value columns need the saved-IR codec to stop reading
those slices first.
2026-11-22 16:07:46 -03:00
waozi 0afcf938e0 Show the source line, a caret and the fix under text diagnostics
Build check / check (push) Failing after 1m46s
Text mode now prints, under the unchanged "path:line:column: message"
line, the source line indented by four spaces with a caret under the
span (tabs kept so it lines up), "expected X, found Y" when the message
does not already name both types, and "fix: replace OLD with NEW" when
the diagnostic carries a name edit. JSON output is unchanged.

A parse diagnostic names its root-relative path, so the excerpt finds
the file through the new DocumentWithSuffix lookup in the document
store, and works from any working directory. Declaration values and
assignment targets now get spans from the line start instead of the
statement start: `t := TextTrim(42)` reports column 19 for 42, in text
and in JSON. Type mismatch details carry the written type names.

Live stages: compiler_diagnostic, compiler_document, compiler_check and
compiler_expr_ir (loaded by compiler_parse); seeds regenerated for those
modules only. Goldens in tests/tool_diagnostics_cases.zi cover a name
fix, a parse hint and tab indentation; operators.sh counts one diagnostic
by its unindented line, and the diagnostic probes stub DocumentWithSuffix.
2026-11-22 16:03:49 -03:00
waozi f2ff55ad99 Regenerate the mesh-client package page from its compacted README
The mesh-client repository's README and AGENTS files were compacted
(mesh-client 17f9e49); site/packages/mesh-client.html is regenerated from
them with scripts/site_pages.py. The tcl and tk pages wait for their
package inventory entries, which are not committed yet.
2026-11-22 16:01:07 -03:00
waozi 02c7847641 Point the milestone open-work note at plans/open-work.md 2026-11-22 15:47:41 -03:00
waozi 54aeaba518 Delete finished and superseded plans, keep open work consolidated 2026-11-22 15:47:39 -03:00
waozi d3f6874326 Compact the performance report and machine IR documents
performance-report.md keeps every schema table and contract; the pending five-core delivery-gate checklist moves to plans/open-work.md and its zx_compare link targets the Older receipts anchor instead of the removed pointer-dispatch section. machine-ir.md drops the encoder Still-required list, now tracked as M4/M5/M6 open work, and the stale broader-M2-open clause. All module, ABI and test references were verified against the tree.
2026-11-22 15:23:00 -03:00
waozi 4ac82147c3 Compact the ZX comparison document around the current receipts
Interim comparison 1 and the pointer-dispatch cohort keep their headings as short subsections pointing at the raw bench/results receipts instead of duplicated tables; the harness, provenance, Moto and visual sections are tightened without dropping facts. Superseded numbers remain in the receipts; no claim was removed.
2026-11-22 15:22:53 -03:00
waozi 835fc9230c Track pending measurement work and delete the finished checks plan
The checks plan was consolidated into tests/check_plan.zi in 241d817f and its scripts (compiler_declaration.sh, wasm_enums.sh, zip.sh) no longer exist, so the plan is finished. plans/open-work.md gains the strict five-core campaign item moved out of ASSEMBLY/performance-report.md and an item to document the 2026-11-16 release receipt.
2026-11-22 15:22:47 -03:00
waozi 9acf8693d8 Bootstrap frontend IR and compiler services in Ziran
Build check / check (push) Failing after 1m9s
2026-11-22 15:14:15 -03:00
waozi 3bdd7c6b7f Leave only the open LLM authoring gaps in the audit plan
Gaps 1, 3, 4, 5, 7, 8, 10 and 11 landed. What stays: multi-error parse
recovery and the file-scope '::' string bug, text-mode caret output
(planned in cmd/compiler_diagnostic.zi after the self-host port lands),
TextInteger's 18-digit limit and the std modules without a summary.
2026-11-22 15:03:16 -03:00
waozi 1b7608b82e Lower typed pointer indexing in portable ZX
Build check / check (push) Failing after 1m44s
2026-11-22 14:54:04 -03:00
waozi b378ac14ad Show signatures, infer the check root, add ziran std and API builtins
Build check / check (push) Failing after 1m25s
Smaller message fixes: an argument-count mismatch now prints the
parameter list, as in "TextFind (a required argument is missing; it
takes (text: string, needle: string, from: s64 = 0))"; a statement that
only reads <<p says to store with <<p = value or bind the read; the
artifact build path says to run ziran lock when the lock is missing.
ziran check FILE.zi outside a project uses FILE's folder as the root,
as ziran build FILE.zi already did, instead of printing zi2zir usage.

ziran check --lint warns on / and % by the constant -1 (lint.divide,
with an explain entry): arithmetic keeps no runtime check, so the lint
names the overflow for the smallest integer. S64_MIN already prints
correctly on C, the engine and native; tests/spec/std_number_text.zi
covers it.

Discovery: ziran std --list [--json] names every standard module with
the first sentence of its leading comment, and ziran api lists the Vec
and builder operations the compiler implements (VecPush, VecPop,
VecSlice, BuilderFinish, ...) under std/vec as builtin lines and a JSON
builtins array.

Live stages: compiler_check, compiler_check_function and
compiler_check_program (seeds regenerated for those modules only), the
launcher (package.zi, package_guide.zi, package_explain.zi) and the C
zi-api tool. tests/tool_diagnostics_cases.zi covers each change.
REFERENCE.md, site/llms.txt, API_DISCOVERY.md and its guide page are
updated.
2026-11-22 14:50:50 -03:00
waozi 0983c2cebc Regenerate the diagnostics guide page for the authoring hints
Build check / check (push) Failing after 1m14s
docs/DIAGNOSTICS.md gained the foreign-syntax and import-hint paragraphs
in the previous commit; site/guide/diagnostics.html is generated from it
by scripts/site_pages.py and is regenerated here so site_pages passes.
2026-11-22 14:48:56 -03:00
waozi 94bab2bb5b Name the Ziran spelling for foreign syntax and suggest names and imports
Build check / check (push) Failing after 1m42s
Habits from C, Go, Rust, Python and JavaScript now get one message that
names the Ziran form instead of a cascade: let/var/const, fn/func/def/
function/pub, for i in a..b, C for (;;), *p = value, .len()/.length/.size,
printf conversions in print and BuilderPrint formats (only when the whole
format is printf style, so v%.4s and %x% stay valid), and a loop or slice
over a Vec a call returned. Errors about names generated for a broken
loop, about operands whose type already failed, and about a local whose
declaration failed are not repeated. Type mismatches print Vec(string)
instead of __type_<hash>.

Unresolved names now consider public procedures of unqualified imports
(TextLins -> TextLines, with suggested_name and a replace_name edit), and
a name declared by a common standard module that the file does not import
says which #import to add.

All edits are in the live Ziran stages (compiler_parse_discover,
compiler_parse_source, compiler_check, compiler_check_expr,
compiler_check_function, compiler_check_statement, compiler_declaration);
only those modules' bootstrap seeds are regenerated. Table-driven cases
in tests/tool_diagnostics_cases.zi cover each hint, a JSON suggestion and
similar spellings that must stay valid.
2026-11-22 14:38:21 -03:00
waozi dec3944830 Add a checked prompt-sized language reference and site/llms.txt
Build check / check (push) Failing after 1m11s
docs/REFERENCE.md teaches Ziran to an author who has never seen it, in
547 lines: syntax by example in writing order, string versus Text, Vec
and HashMap, multiple results, a moves-and-views page, pointers,
modules, % formatting, tests, commands, a "you would guess X, Ziran is
Y" table for C, Go, Rust and JavaScript habits, a std signature table
and arithmetic edges.

Every zi block is a whole file. The site_pages check now writes each
block out and runs ziran check on it, keeps the file at 600 lines or
fewer, and verifies site/llms.txt, which scripts/site_llms.zi generates
from the reference. ziran guide and AGENTS.md point at the reference.
The LLM authoring audit records Top gaps 1 and 8 as landed.
2026-11-22 14:19:56 -03:00
waozi f17d6915f2 Bootstrap declaration parsing and IR cleanup from Ziran
Build check / check (push) Canceled after 5s
2026-11-22 14:13:39 -03:00
waozi 5769bdf699 Fix stale source links in the assembly documents
Links to C sources removed by the bootstrap-from-Ziran ports now point
at their Ziran modules: compiler_zir_lower.zi, compiler_ir_cleanup.zi,
compiler_machine_elf.zi, compiler_simd_metadata.zi, compiler_bundle.zi,
compiler_zx_wasm.zi, compiler_c_backend.zi, compiler_c_range.zi,
compiler_vector_x86.zi, compiler_go_asm_x64.zi, and cmd/inspect.zi.
Links to pruned shell tests point at the retained cases. The assembly
README test block runs plain make targets instead of the removed
build-queue wrapper and the removed make assembly target, and its status
section points at plans/open-work.md instead of dated milestone
narrative.
2026-11-22 13:56:54 -03:00
waozi 7ced8e858b Consolidate open work into plans/open-work.md and delete finished plans
plans/open-work.md holds one line per undone item with its location and
test. Deleted finished plans: 2026-11-13-native-optimizations (all items
landed; cmd/compiler_lowered_x64.zi is gone), 2026-11-15-manual-safety
(--checks and #checks shipped; the optional untrusted-bundle refusal
moved to open work), 2026-11-17-code-size (24 cuts landed; the shell
harness absorption moved to open work), 2026-11-17-standard-benchmarks
and 2026-11-17-site-benchmark-cohort (open items moved to open work),
and the four 2026-11-18 learn-from-lean lane inventories (verified and
triaged into the merged verdict). plans/2026-11-18-learn-from-lean.md
keeps the adopted items, baselines, and the do-not-adopt list. Stale
references to the deleted plans were removed from assembly-remaining,
m4-native-arm, and native-zx-players.
2026-11-22 13:56:54 -03:00
waozi 6651443eab Compact authoring docs and move open proof work to plans/open-work.md
docs/AUTHORING.md drops the build-queue wrapper (not a repository tool)
and lists the direct test commands. docs/FEATURES.md states the
incremental scope without stale not-yet phrasing. docs/LAWS.md and
docs/LANGUAGE_DIRECTION.md point induction and future proof work at
plans/open-work.md instead of restating it.
2026-11-22 13:56:54 -03:00
waozi 5130aaf56c Rewrite AGENTS.md and README.md as compact agent entry points
AGENTS.md gains a layout map, working commands, a question-to-document
index, and shared-checkout rules in 78 lines. README.md drops the stale
0.6.0 version claim (VERSION is 0.8.0), keeps the quick start and tool
table, and indexes the documentation by question.
2026-11-22 13:56:54 -03:00
waozi 62d90ff97d Verify and reuse exact Ziran setup caches
Build check / check (push) Failing after 59s
Restore and verify exact toolchain caches before prebuilt downloads, bound setup jobs, and check build prerequisites. Declare the existing borrowed-slice host ABI in the Ziran standard bindings so the retained hosted module test can run from committed source.
2026-11-22 13:17:42 -03:00
waozi 1eef0a811a Add cancellable PNG and JPEG decoding progress
Build check / check (push) Failing after 1m26s
2026-11-22 13:08:24 -03:00
waozi 7ad836764e Bootstrap source parsing and module discovery from Ziran
Build check / check (push) Failing after 1m25s
2026-11-22 07:26:19 -03:00
waozi 3a5c775ad8 Bootstrap whole-program checking and borrow analysis from Ziran
Build check / check (push) Failing after 1m15s
2026-11-22 06:47:20 -03:00
waozi 26a1e47854 Bootstrap the Go backend and checker from Ziran
Build check / check (push) Failing after 1m51s
2026-11-22 06:27:25 -03:00
waozi 122990b237 Use bulk copies for disjoint ZX frame storage
Build check / check (push) Failing after 1m10s
Check backing bounds and keep the original forward copy for overlaps.
Preserve work charges and the portable executor ABI. Retain matched
hosted i386 and private 128 MiB Taiji results from physical Alpha.
2026-11-22 06:14:19 -03:00
waozi 3116ceb59e Bootstrap the C backend and SIMD emitters from Ziran
Build check / check (push) Failing after 1m6s
2026-11-22 05:54:04 -03:00
waozi b5b8167f18 Reuse the current frame in packed ZX execution
Build check / check (push) Failing after 5m11s
Keep consecutive value operations in the same packed frame and preserve
instruction work charges and native block entry points. Record matched
i386 fixture runs and Taiji guest measurements from physical Alpha.

Discover modular diagnostic codes with the compiler's source scanner and
refresh the affected crypto and mesh-client site entries.
2026-11-22 05:11:53 -03:00
waozi 51e4505dd2 Batch LICM/Layout serialization and avoid redundant LIR re-verification
Build check / check (push) Failing after 4m57s
2026-11-22 04:56:10 -03:00
waozi 920c86a10d Accelerate packed ZX execution on Linux i386
Build check / check (push) Failing after 1h35m0s
Build check / Publish a new Ziran version (push) Skipped
Compile bounded hot integer runs and streamline scalar dispatch, branch
arguments, aggregate loads and opt-in synchronous scalar slice transfers.
Retain exact work and fuel accounting and hosted parity coverage. Record
matched physical Alpha measurements, including the private Taiji lifecycle.

Check package API exports under their selected targets so the retained
site test validates packages using target-conditional native providers.
2026-11-22 03:58:17 -03:00
waozi 2684af8d22 Add portable child bundle capability declarations
Build check / check (push) Failing after 8m40s
Build check / Publish a new Ziran version (push) Skipped
2026-11-22 03:48:18 -03:00
waozi d0435e6b37 Pack hosted ZX instructions for the portable engine
Build check / check (push) Failing after 1h30m1s
Build check / Publish a new Ziran version (push) Skipped
2026-11-22 03:46:11 -03:00
waozi 94dc864260 Pack checked ZX libraries for explicit targets
Build check / check (push) Failing after 14m6s
Build check / Publish a new Ziran version (push) Skipped
2026-11-21 21:04:27 -03:00
waozi 5db3d3c394 Use native Build host runner for Ziran checks and skip ccache symlinks in CheckExecutable
Build check / check (push) Failing after 20m44s
Build check / Publish a new Ziran version (push) Skipped
2026-11-21 15:32:46 -03:00
waozi eb53af7dae Reuse large aggregate slots in portable ZX frames
Build check / check (push) Failing after 29m31s
2026-11-21 13:50:55 -03:00
waozi 3432c0ca26 Keep package source selection isolated during lock resolution
Build check / check (push) Failing after 26m56s
2026-11-21 04:58:24 -03:00
waozi b4d7ad82f8 Reuse temporary ZX address slots across branches
Build check / check (push) Failing after 28m48s
2026-11-21 03:31:52 -03:00
waozi 7e56396c5c Fit native ZX frame arenas in constrained address space
Build check / check (push) Failing after 54m0s
Retry smaller contiguous reservations on ENOMEM and enforce the actual mapped extent. Exercise nested typed callbacks and release of their arenas under a process address-space limit.
2026-11-21 01:23:06 -03:00
waozi b6cc625a55 Speed up portable SHA-256 verification
Build check / check (push) Failing after 29m22s
2026-11-21 00:21:46 -03:00
waozi 9f601753bf Reduce repeated work in package and JSON tests
Build check / check (push) Canceled after 6m16s
2026-11-20 23:36:45 -03:00
waozi 5462fe2ebf Reduce spare capacity for large executor address tables
Build check / check (push) Failing after 27m14s
2026-11-20 17:10:22 -03:00
waozi fc11f5cefb Build and verify versioned ZX library packages
Build check / check (push) Canceled after 6m6s
2026-11-20 17:04:13 -03:00
waozi 9a22b19d74 Discover and pin prebuilt ZX package dependencies
Build check / check (push) Failing after 31m41s
2026-11-20 14:49:18 -03:00
waozi 8818597892 Cut duplicate work from the Ziran check suite
Build check / check (push) Failing after 34m11s
2026-11-20 13:35:37 -03:00
waozi 86827bb4cd Open hosted ZX apps through verified positional reads
Build check / check (push) Failing after 32m40s
2026-11-20 05:21:28 -03:00
waozi 79267de637 Use native-width block indexes in hosted ZX plans
Build check / check (push) Failing after 32m34s
2026-11-20 04:21:29 -03:00
waozi ec96fe0b3f Bound large ZX heap and address table growth
Build check / check (push) Failing after 33m54s
2026-11-20 03:37:14 -03:00
waozi 8e8e53bacd Share ZX plan storage for value locations
Build check / check (push) Failing after 34m3s
2026-11-20 02:34:52 -03:00
waozi ca459aecd9 Compact decoded ZX instructions
Build check / check (push) Canceled after 22m46s
2026-11-20 02:12:15 -03:00
waozi 25a11628d4 Reduce memory in hosted ZX execution
Build check / check (push) Canceled after 16m41s
2026-11-20 01:55:27 -03:00
waozi 34bd23fa4e Lock exact package pins from local Git objects
Build check / check (push) Canceled after 32m36s
2026-11-20 01:22:57 -03:00
waozi be5b40432e Reduce portable ZX working memory on constrained hosts
Build check / check (push) Canceled after 12m33s
Reuse verified instruction and constant data, allocate fast code in chunks, and offer a compact execution plan. Allow an opt-in frame workspace reservation for programs whose verified static frames reach an embedder-selected size. Execution bounds and typed host calls retain their semantics.

The original Taiji Stopwatch rendered and completed its interaction smoke in a 32 MiB guest. The reservation added zero bytes at open and instantiation for hello, fuel, cp, command I/O, and filesystem fixtures.
2026-11-20 01:10:05 -03:00
waozi 81a0bca977 Preserve the largest finite binary64 value on i386
Build check / check (push) Canceled after 29m54s
2026-11-20 00:40:29 -03:00
waozi e9e57d940f Reuse freed storage in the ZX engine heap
Build check / check (push) Failing after 39m27s
2026-11-19 22:16:26 -03:00
waozi d60a9c91fa Expose checked runnable API examples
Build check / check (push) Canceled after 11m6s
2026-11-19 22:05:28 -03:00
waozi f59690f087 Resolve qualified host capability calls in portable programs
Build check / check (push) Canceled after 22m26s
2026-11-19 21:37:24 -03:00
waozi 80b8cca8bb Match Ziran checks to Build runner capacity
Build check / check (push) Failing after 49m20s
2026-11-19 20:25:31 -03:00
waozi a7f112ff48 Support verified ZX modules in hosted filesystems
Alpha check / check (push) Failing after 39m30s
Resolve library images through an optional embedder callback and route app and library descriptor writes through one console. Let bounded instruction-engine entries renew their step budget at explicit host checkpoints.
2026-11-19 19:22:03 -03:00
waozi 7a2ed8ec3b Document pure and native Zstandard compression APIs
Alpha check / check (push) Failing after 38m23s
2026-11-19 18:36:06 -03:00
waozi 5a2ba0a576 Preserve native host arguments across reentrant callbacks
Alpha check / check (push) Canceled after 31m7s
Keep active callbacks' portable values and aggregate input images alive
when a nested native invocation calls the same instance again. Restore
outer storage on both normal return and failure.

Retain raw and checked A-to-B-to-A coverage for records, fixed arrays,
local strings, copied strings across runs, and failed-inner cleanup.
2026-11-19 17:28:36 -03:00
waozi 9432a11070 Reserve native frame storage only while instances execute
Alpha check / check (push) Failing after 17m32s
Keep checked pointer slots persistent and reserve the full frame arena for
an active outermost invocation, including reentrant callbacks. Release it
on return or trap so idle bundles fit in a 32-bit address space.

Add a bounded address-space regression with eight independent native
instances, precise loader diagnostics, and runtime documentation.

Validation: make check (272/274), then passing focused rechecks for the
repaired diagnostic registry and generated architecture page; bootstrap
verification; exact ARMv7 Moto Lumi/Practice, navbar, and PiP tests.
2026-11-19 14:00:28 -03:00
waozi 3a59682d86 Route embedded ZX console output through host callbacks
Alpha check / check (push) Successful in 10m25s
2026-11-19 01:32:24 -03:00
waozi 2cafe84dc8 Integrate verified ZX modules and compiler improvements
Alpha check / check (push) Successful in 10m8s
Add typed separately compiled ZX libraries with independent instances and compatible state replacement. Tighten generated-name diagnostics, remove the fixed loader graph limit, and resolve platform conditions without eager enum-import cycles.

Resolve known function calls, bound specialization work, improve loop inlining, and copy borrowed Wasm records safely across overlapping pointers. Retain measured native vector growth and allocated-state verification improvements with startup phase profiling. Include focused regression coverage, synchronized bootstrap and site documentation, Lean research plans, and raw Alpha comparison receipts with rejected prototypes clearly identified.

Local validation: all 273 retained tests passed across the full run (272/273) and the audio rerun after refreshing stale disposable CMake compiler paths (1/1), with no implementation drift. Linux, Darwin and SIMD bootstrap seeds match. Current-tree Omega installation verified all 11 binary identities and ran Hello World through the installed compiler.

Alpha matched measurements support smaller Wasm modules; the native vector workload improves 4.62%, while printing is 1.41% slower. Separate application, controller and Moto integration remains outside this compiler milestone.
2026-11-19 00:01:23 -03:00
waozi f442d706fe Edit tool: result envelope with embedded diagnostics
Alpha check / check (push) Successful in 10m40s
Every ziran edit invocation now writes exactly one schema_version-1
result document on stdout. Rejected edits answer applied=false with a
diagnostics array holding the collected schema-version-2 records,
matching the streamed stderr lines; accepted edits embed the same
array. Usage errors and unreadable request files go through the same
envelope.

The compiler reports candidate syntax errors through a fatal path that
exits mid-validation, so an atexit exit guard flushes the collected
diagnostics when that happens. Diagnostic collection storage uses raw
libc allocations: allocator-tracked storage would be freed when a
failed frontend scope unwinds, leaving the collector dangling.

semantic_edit.sh rejects now assert the envelope: applied flag,
diagnostics array, and per-record equality with stderr including full
native metadata.
2026-11-18 22:33:15 -03:00
waozi f7516d81d0 Record rejected call-load forwarding measurements
Alpha check / check (push) Failing after 29s
2026-11-18 18:09:51 -03:00
waozi bc946f307e Run Linux checks on Alpha’s Gitea runner
Alpha check / check (push) Failing after 10m55s
2026-11-18 18:02:15 -03:00
waozi 036cb7b5d2 Stream executable asset identities through the shared SHA-256 runtime 2026-11-18 17:55:53 -03:00
waozi 379776191c Run Wine without TMPDIR in the Windows parity check
Ubuntu's Wine 9.0 aborts with "free(): invalid pointer" when it runs as
root while TMPDIR is set, as in CI containers, where the check runner gives
every check a private TMPDIR. Wine needs none, so its commands start
through env -u TMPDIR; the compilers keep the private directory.
2026-11-18 16:56:40 -03:00
waozi ce42bdc0c1 Link the audio check's codecs from the build it tests
audio_checks builds the codec archives with `make audio-codecs` and linked
them from build/audio/native. Under `make sanitize` the sanitize build's
BUILD_DIR reaches that make through MAKEFLAGS, so the archives went to
build/sanitize/audio/native and a fresh runner failed to link
libziran_mp3.a and the Vorbis libraries; a local tree passed on stale
archives. The check now builds them in the directory of the ziran under
test and links them from there.
2026-11-18 16:45:56 -03:00
waozi e69f7143e9 Declare generic copies hidden behind a caller's private guard
A generic's copy is checked in its caller's module. When its signature
spells a type through the template's own `using` alias (Kryon text's
`props: Text.Props`) and the caller has a module-scoped import of that
name (Terminal's `Text :: #import "std/text_buffer"`), the header puts
its prototype behind the _PRIVATE guard. header_has_private counted only
private types and defines, so such a caller's source never defined the
guard, called the copy undeclared, and GCC 14 refused it.

header_has_private now counts these copies too. generic_procedure.sh
builds that shape with -Werror=implicit-function-declaration; it fails
with the earlier zi2c and passes now.
2026-11-18 16:44:02 -03:00
waozi 80a44b3c4c Reload ARM native images from the disk cache
Since 10f60362 an Android app keys and stores its compiled bundle, but
DecodePayload accepted only x86-64 Linux images and relocation kinds up to
PointerRuntime, so every ARMv7 entry (which carries RuntimeHelper
relocations) was refused as WrongStructure and compiled again on each
start: Jungle's 4,354,579-byte .zxn on the Moto, costing 6.5 s per launch.

- Decoding accepts every target native lowering supports and restores
  that target, with relocation kinds through RuntimeHelper.
- The loader maps an entry only when its target is this host's.
- native_cache_module_cases round-trips ARMv7 (with a RuntimeHelper
  relocation) and AArch64 Android images.

Jungle's real Moto entry now decodes (result 0, 8,645 globals; it
returned 7 before). Found and written by the owner's Jungle session.
2026-11-18 16:44:02 -03:00
waozi 31f4184827 Publish the Kryon 3D scene table on Targets
The Targets page gains one table of Kryon's animated GPU scenes: lit
meshes, a skinned character, a textured room and a particle field, at
640x360 and 1920x1080, as mean and nearest-rank p95 frame time in
microseconds. The receipt comes from a clean checkout of Kryon v0.6.0
(8d5d2e75, source_dirty false) on an NVIDIA GeForce RTX 5060 Ti through
OpenGL ES, with 60 completed and hashed frames per scene and size after
8 warmup frames.

site_benchmark_tables.zi renders and checks the table like the others.
It accepts only a visual-suite receipt with a clean 40-character Kryon
revision, a real GPU identity for every run, and 60 samples and 60
frame hashes for each scene and size.
2026-11-18 16:32:07 -03:00
waozi 3fec72ab5f Fold literal range tests into one unsigned comparison
For an integer x and literal bounds L <= U that fit its type, ZX
lowering turns x >= L && x <= U, in either order, into
unsigned(x - L) <= U - L, with the subtraction wrapping at x's width.
x must be a stable local, record member or fixed-array element, as for
the existing x > U || x < 0 fold; calls and other expressions whose
second evaluation can matter keep normal short-circuiting.

Kryon's TextIdeographic, six ranges of code points, drops from 55 to
41 LIR instructions. Across ten alternating Alpha rounds the Text
widget's Wasm module was faster in 8 (3.542 vs 3.677 us and 3.683 vs
3.713 us medians), with the paint result checked on every call. The
lowered parity fixture covers signed, unsigned, narrow and 64-bit
values, both orders, member reads, an empty range and repeated calls.
2026-11-18 15:32:50 -03:00
waozi 9748087d91 Read package mirrors through their GitHub remote in site pages
Package checkouts moved to Gitea keep GitHub as their github remote, so
site_pages.py compared the Gitea origin with the GitHub URL a manifest
names and failed on ziranlang/audio. It now reads the github remote
when one exists and origin otherwise.
2026-11-18 15:20:45 -03:00
waozi e6fdd96421 Pack Wasm frames with only the slots still in use
Wasm lowering lays out a frame slot for every record value before
planning decides which values are read in place, built in their
parent or caller, or never built. Only trailing unused slots were
dropped, so one small record after many in-place reads kept their
whole space: Shovey's LevelReplayPump, which reads single fields of
a 306 KB global 27 times, needed a 10.6 MB frame and failed with
wasm.gap.frame against the 8 MB limit.

CompactFrame now runs after planning. It gives each slot that a lowered
value still uses a packed offset sized to its furthest use, moves the
views into it, and tags unused slots so slot comparisons stay exact.
The frame size skips elided values, whose stale views reserved space
too. Shovey's bundle now lowers to a 16.8 MB module that V8
validates. The Wasm regression reads a 1 MB global ten times beside
a small record argument; the previous zx2wasm needed a 10 MB frame
for it.
2026-11-18 15:20:26 -03:00
waozi 68d845f49a Note verifying once and app native caches in the changelog 2026-11-18 15:12:07 -03:00
waozi 10f603625a Verify allocated code once and cache Android apps' native images
On a phone the bundle compile is the largest startup cost: Jungle spends
8.7 s in HostedAppStart on the Moto. Two parts of it were waste.

- Allocation verifies its program with MachineVerifyAllocated, and every
  encoder verified the same program again. The pipeline now encodes
  through MachineV7EncodeAllocated, MachineA64EncodeAllocated and
  MachineX64EncodeAllocated, which skip the repeat; the public encoders
  still verify what they are given.
- The native disk cache never worked in an Android app. Its key needs the
  compiler's GNU build ID, which Shovey's reproducible libmain.so does
  not have (-Wl,--build-id=none), and its directory came from HOME, which
  an app process lacks. Without a build ID the code is now identified by
  a 64-bit FNV-1a hash of the object's readable executable segments, and
  on Android an app's cache directory is /data/data/PACKAGE/cache. So only
  the first launch after an install compiles a bundle.

native_disk_cache_cases also runs a zi2zx stripped of its build ID: a cold
run stores the image and a warm run maps it.
2026-11-18 14:58:00 -03:00
waozi 5f95fae22f Publish the Targets cohort measured at 10570c2e
Every Targets table is regenerated from one clean pushed revision,
10570c2e, on Alpha's physical host with 11 host-gated samples. It
includes unbounded in-process native ZX, direct native console output
and host-call routing resolved once: the example programs run natively
in 0.024 us (score, text_demo), 0.17 us (enums), 0.48 us (arrays) and
0.70 us (loops), level with C on loops. Kernel and standard Wasm now
run without a step budget, like every other column: Sieve takes 39.0
us in Wasm instead of 59.3 and Hash 27.4 us instead of 37.6, level
with C and Go.
2026-11-18 14:57:20 -03:00
waozi 10570c2e39 Time unbounded Wasm in the kernel and standard tables
C, Go and the in-process ZX runners time calls with no step budget, but
the kernel and standard harness built their Wasm modules with fuel
checks and a zx.budget import. Both now use zx2wasm --unbounded, as
the widget table already does, and their methodology says the Wasm
module charges no step budget. A duplicate definition of the kernel
build function is removed.
2026-11-18 14:47:19 -03:00
waozi a4058c6011 Read large records in place and zero zeroed records once on ARM
Shovey trapped on the Moto when Play was pressed: LevelReplayPump needed
an 11.87 MB frame on ARMv7, and on AArch64, above the 8 MiB render
thread. ARM lowering kept aggregate views and in-place field loads off,
so every member read of the 306 KB global level_replay_check copied the
whole record into the frame.

- Views and field loads run on every target. The ARMv7 and AArch64
  encoders take a view's address as the aggregate of AggregateExtract and
  AggregateInsert, as x86-64 does.
- An aggregate build of zero constants and zero builds lowers to one
  StackAddress and Zero, and a member build only zero builds read emits
  nothing. Shovey's loop-local [241]ShoveyGame was 289,200 member stores:
  LevelReplayPump was 4.69 MB of ARMv7 code, and on AArch64 its branches
  left the conditional range, so the bundle did not compile.

Shovey's bundle: LevelReplayPump's frame is 1.84 MB on all three targets,
and its native code is 1.37 MB on ARMv7 (was 6.40), 0.91 MB on AArch64
(was rejected) and 0.86 MB on x86-64 (was 2.82). machine_fields_cases now
lowers, verifies and encodes on x86-64, ARMv7 and AArch64, with zero
builds; native_large_global_fields joins the parity programs.
2026-11-18 14:46:01 -03:00
waozi 0fdd5cdab1 Record the direct console services on Alpha
arrays.zi, enums.zi and loops.zi take about half the time per call;
enums.zi now runs faster than Wasm.
2026-11-18 14:31:38 -03:00
waozi 244db56e5c Take console service arguments straight from the saved registers (Alpha trial) 2026-11-18 14:21:55 -03:00
waozi 400f4c3edd Record the native console buffer on Alpha
Print-heavy examples take 8–11% less time per call.
2026-11-18 14:13:30 -03:00
waozi ef16754c17 Gather native program output in the console, as the engine does (Alpha trial) 2026-11-18 14:08:17 -03:00
waozi 0f1ed01d71 Record the native print path on Alpha
arrays.zi, enums.zi and loops.zi take about 45% less time per call.
2026-11-18 13:51:48 -03:00
waozi b63ebae04c Resolve each native host call's route once and format prints directly (Alpha trial) 2026-11-18 13:41:14 -03:00
waozi d7146386a5 Record the unbounded native column on Alpha
Unbounded instances run without fuel checks and a normal run no longer
flushes stdio: enums.zi takes 0.688 µs per call instead of 1.213, and
dijkstra 24% less time.
2026-11-18 13:33:18 -03:00
waozi fed9bd0f95 Leave a normal native run's output to stdio buffering, as the engine does (Alpha trial) 2026-11-18 13:27:16 -03:00
waozi 0bb3f36178 Run unbounded native instances without fuel checks (Alpha trial) 2026-11-18 13:09:55 -03:00
waozi 797332dec6 Publish the Targets cohort measured at ac64565e
Every Targets table is regenerated from one clean pushed revision,
ac64565e, on Alpha's physical host with 11 host-gated samples. In-process
ZX native entry no longer makes a system call per call, so the small
example programs run natively in about 0.03 us: score.zi 0.494 to
0.033 us and text_demo 0.493 to 0.032 us, now ahead of Wasm. Arrays,
enums and loops also run faster natively. Kryon widget medians (C / Go / ZX native / Wasm, us):

  Button  2.660 / 4.175 / 4.053 / 2.344
  Text    3.157 / 3.851 / 5.493 / 3.625
  Input   3.846 / 6.694 / 5.936 / 3.442
2026-11-18 13:08:34 -03:00
waozi 91bca360c8 Port the saved IR inspector driver to Ziran 2026-11-18 13:08:28 -03:00
waozi ac64565e50 Record the native entry measurement on Alpha
Every in-process entry made a prlimit64 system call; without it score.zi
takes 0.032 µs per call instead of 0.511, below Wasm.
2026-11-18 12:52:44 -03:00
waozi e6756bf62c Keep each thread's native stack range without a system call per entry (Alpha trial) 2026-11-18 12:42:32 -03:00
waozi 6205d2f20a Drop the ratio column from the Targets example table
The "Example programs compiled to four targets" table shows C, Go,
ZX native and Wasm times without a "Ratio to C" column. The kernel,
standard, widget and JSON/UTF-8 tables keep theirs.
2026-11-18 12:38:07 -03:00
waozi 30134bd9c1 Remove obsolete parser aliases and retired tool rules 2026-11-18 12:27:21 -03:00
waozi 1934aae05e Build saved IR expression ownership and source offsets in Ziran 2026-11-18 11:47:52 -03:00
waozi 55b0176800 Release Ziran 0.7.0
Wasm now runs all three Kryon widget scenarios faster than Go: Button
2.46 µs, Text 3.59 µs and Input 3.24 µs per two frames on Alpha. The
optimizer inlines small procedures and reads record members through
their inserts. Native x86-64 code is faster across division, shifts,
floating-point calls and small allocations. std/base64, JPEG reading
and writing, portable PNG inflate and core audio join the standard
library. The changelog section lists what users get, including the
known ARMv7 LevelReplayPump frame-limit issue. update_version.sh set
the version files and the standard-library inventory, and
site_pages.py regenerated the module pages for 0.7.0.
2026-11-18 11:30:26 -03:00
waozi 13c2a22ae6 Fix the audio codec, sanitizer optimizer and site page checks
- CI puts Emscripten's tree on PATH, and its cmake directory comes
  before the real cmake. Make's own lookup ran that directory, so
  make audio-codecs failed with "cmake: Permission denied". The
  audio rules now run CMAKE, which the shell resolves to the
  executable.
- Under AddressSanitizer, bundling the whole optimizer test takes
  more than the 180-second command limit. NativeRun takes an
  optional timeout, and those two bundle steps get 600 seconds;
  the sanitizer run passes in 220 seconds.
- The site page check reads the released version from VERSION
  instead of a literal, so a release no longer breaks it.
- The test scripts that make runs directly are executable.
2026-11-18 11:29:55 -03:00
waozi 0eaed218e5 Land load-test rotation and fixed member hoisting measured on Alpha
Merge the measured revision. Rotation copies a loop test that loads from
memory, and LICM hoists fixed member extracts such as a slice's data and
count. Across all 29 standard workloads the geometric mean improved
0.67%. Bytecode's unchanged code moves with placement, which the receipt
shows with a cross run.

Add a direct-assembly case: a loop over a slice reads its data and count
before the loop.
2026-11-18 11:27:55 -03:00
waozi 2806fb1cb5 Hoist fixed member reads out of loops (Alpha trial, with rotation) 2026-11-18 11:05:39 -03:00
waozi d898d1d122 Record the loop unswitching trial on Alpha
Splitting FASTA's middle loop on its phase test made FASTA and native
Input slower, so the pass was not kept. FASTA is bound by its modulo
chains and float divide; the plan keeps the raw samples.
2026-11-18 10:50:21 -03:00
waozi 884ef80bdb Publish the Targets cohort measured at 4f49aa9a
Every Targets table is regenerated from one clean pushed compiler
revision, 4f49aa9a, measured on Alpha's physical host with 11
host-gated samples and learning off: kernel tiers, the standard
diagnostic and compile suites, JSON/UTF-8 workloads, Kryon widgets
and the example matrix. The kernel receipt moves to its measurement
date, 2026-11-18.

Kryon widget medians, us per two-frame scenario, paint checked on
every batch (C / Go / ZX native / Wasm):

  Button  2.693 / 4.325 / 4.810 / 2.461
  Text    3.105 / 3.894 / 6.301 / 3.592
  Input   3.998 / 6.588 / 6.400 / 3.236

Wasm now runs every widget scenario faster than Go, and Button and
Input faster than C. The published cohort at 45b74b4e had Text at
4.153 us in Wasm against 3.837 us in Go.
2026-11-18 04:04:10 -03:00
waozi 177bcfd845 Rotate loops whose test loads from memory
The latch's copy of the test runs where the header's test ran, so each
instruction, fuel included, keeps its order and runs once per original
header visit. Loads, element and field addresses, and adds, subtracts,
masks and conversions can therefore join the duplicated test; a load or
address that traps still traps at the same point. Quicksort's scan loops
`while a[i] < pivot` now end in one branch back to themselves.
2026-11-18 03:16:50 -03:00
waozi 4f49aa9aff Add std/base64, portable JPEG decoding, and portable PNG inflate 2026-11-18 02:55:40 -03:00
waozi 6669a95333 Write zeroed records in Wasm with wide stores
A zero-initialized record, such as the 260-byte paint text block Kryon
pushes when a frame starts a new block, was built with one byte store
per array member and then copied into place.

Wasm lowering now tracks values whose bytes are all zero: zero scalar
constants and constructors built only from them. A constructor writes
adjacent zero members as one run, with unrolled 8-byte stores up to
320 bytes and memory.fill beyond. A store or allocation of a zero value
fills its destination. A zero constructor that only stores, allocations
and other constructors read is never built. Omitted members are still
left for the insert that overwrites them.

The Text widget module goes from 609 to 198 byte stores. In five
alternating Alpha rounds its Wasm median went from 3.890 to 3.604 us,
faster in every round, with the paint result checked on every call.
Button and Input keep their paint results. The Wasm regression covers
zeroed vector pushes, a 404-byte filled record and zero members beside
other members.
2026-11-18 02:55:11 -03:00
waozi 674412ede3 Land the Boolean specialization guard measured on Alpha
Merge the measured revision. Button and Input return to their speed
before Boolean specialization in native and Wasm, and spectral-norm keeps
both Multiply copies.

Also drop the compiler_opt_unswitch registration that reached the
Makefile without its module, so a clean checkout builds again.
2026-11-18 02:44:58 -03:00
waozi 7f9c508814 Build typed-body eligibility in Ziran
Move type, expression and statement eligibility to a bootstrapped module. Keep the thread-local memo and recoverable expression scratch in the C services and reuse the existing parameter cache.

Verified identical results for 2,129 checked functions and four rejection cases, all 270 local tests, and Linux, Darwin, and SIMD bootstrap replay.
2026-11-18 02:31:34 -03:00
waozi ee671ab680 Keep Boolean specialization from adding aggregate work
A literal Boolean copy is made only when folding the literal leaves no
record or array load without its field read; the backends would copy the
whole value for an unused aggregate load. Separately, DeadPass drops an
unused load when the same block loads the same type at the same address
again before any effect, since that later load raises the same trap.

TreeLayerAt$1 no longer copies the widget tree on every Button and Input
frame.
2026-11-18 02:25:06 -03:00
waozi 7e0695890c Format the full signed 64-bit range
Take decimal digits from a nonpositive magnitude so the minimum signed 64-bit integer never requires a positive magnitude that cannot be represented. Cover both endpoints in the existing formatter fixture and regenerate all affected bootstrap C.

Verified all 270 local tests and Linux, Darwin, and SIMD bootstrap replay.
2026-11-18 02:22:36 -03:00
waozi 1269a28afd Share SIMD vector type metadata in Ziran
Use one bootstrap table for vector recognition, C and Go spellings, and native block selection. Keep global record fields needed to reparse retained initializers.

Verified 1,022 vector queries against the previous compiler, all 270 local tests, and Linux, Darwin, and SIMD bootstrap replay.
2026-11-18 02:18:24 -03:00
waozi a1325927ad Copy fewer record bytes in Wasm lowering
Kryon widget calls copied whole records into Wasm linear memory to read
a few fields. Unchecked Wasm lowering now:

- copies only the byte span of the fixed members a snapshot's uses
  extract, and skips the member a single in-place insert replaces;
- initializes a fresh allocation straight from an aggregate member read
  in place while its source is unchanged;
- writes a load, fixed-member insert and store to the same pointer as a
  single member store when neither snapshot escapes.

Snapshot reads after an intervening write keep the original values. In
five matched Alpha rounds the Text widget scenario measured 3.851 us in
Wasm against 3.848 us in Go, with the paint result verified on every
call. The optimized zx_wasm regression covers snapshot reads and member
replacement across calls and vector member stores.
2026-11-18 02:17:40 -03:00
waozi e0a05faa5e Check site receipt inputs at the commits that measured them
The site receipt checks compared every recorded stdlib, workload and
harness hash with the working tree, so an unrelated std edit made
make check fail until the whole cohort was re-measured on Alpha.

Compiler inputs (stdlib, source inputs, workloads) are now read with
git cat-file at the receipt's measured revision. Harnesses are read at
the commit that published the receipt, or from the working tree while
a fresh receipt is uncommitted. Published copies and artifacts are still
checked on disk, and a missing revision or changed digest still fails.
The site workflow fetches full history so those commits are available.
2026-11-18 02:17:12 -03:00
waozi 0c4465a461 Build frontend expression IR in Ziran
Move statement structuring, default arguments, and caller locations into the Ziran parser seed. Keep the frontend ABI and checker diagnostics, and remove the former C implementation.
2026-11-18 01:47:58 -03:00
waozi 05ced3662c Read local fixed-array lengths without loading the array
Fold the count of a plain fixed-array local before loading its value. Keep evaluation of calls and other effectful receiver expressions. Record the matched k-nucleotide improvement on Alpha for native ZX and Wasm.
2026-11-18 01:06:09 -03:00
waozi 343de87f21 Specialize loop branches for literal Boolean arguments
Keep one out-of-line copy per literal value of an entry Boolean that controls a loop branch. Preserve the original function for runtime arguments and indirect calls. Spectral-norm improves in all 18 matched rounds on Alpha.
2026-11-18 00:26:13 -03:00
waozi 93853cd5ee Shorten the x86-64 multiply-by-31 dependency chain
Use the encoder scratch register to keep the original value while shifting. Extend the existing constant-arithmetic parity fixture to cover narrow and wide signed wrap. FASTA improves in 17 of 18 matched rounds on Alpha.
2026-11-17 23:11:19 -03:00
waozi d1b30019b2 Emit one shift for signed halves of even products
Keep exact truncation for odd products and cover signed wrap at narrow and wide widths. Alpha spectral-norm is 24.2% faster in the matched run. Extend the existing file-scope fixture to check private procedures with different signatures across named imports.
2026-11-17 22:33:11 -03:00
waozi adcf0873b2 Publish expanded standard benchmark cohort 2026-11-17 22:31:24 -03:00
waozi 241d817fa2 Consolidate Ziran check drivers and Unicode conformance cases 2026-11-17 22:30:07 -03:00
waozi c243baa6ae Canonicalize package graph roots through symlinks 2026-11-17 22:30:06 -03:00
waozi 68dc0f8cac Record the in-process step-check cost and the n-body record copies
The native speed plan now has the diagnostic Alpha comparison of the
same kernels compiled with and without fuel (fib +12%, spectral-norm
+16%, quicksort +10%) and what an unbounded in-process mode would need,
and notes the whole-record copies in n-body's body loop.
2026-11-17 22:25:16 -03:00
waozi 94e4fdcfc4 Check with the pinned Emscripten instead of Ubuntu's package
Since the check job started installing Ubuntu's emscripten package
(dd0aff64), the emcc checks that used to skip run against emcc 3.1.6 and
fail: audio_checks and native_entry run /usr/share/emscripten/wrapper,
the resolved target of Ubuntu's emcc symlink, which finds its script only
under the name it was called by; std_file_tree_wasm32 passes -sSTACK_SIZE,
which 3.1.6 does not have; date_time_linux fails in its clang-15 build.

Both check jobs now install Emscripten 6.0.6 with setup-emsdk, the
version the site workflow and local builds use, in place of the apt
package. With emsdk 6.0.6 first on PATH the four checks pass locally, and
std_file_tree_wasm32 runs rather than skipping.
2026-11-17 22:17:37 -03:00
waozi 8489739d3f Leave float constants at their uses again
Hoisting float constants out of call-free loops (96ce8d50) removed
mandelbrot's in-loop movabs/movq rebuilds, but the matched Alpha run made
the floating-point kernels slower, C / before / with it, µs: spectral-norm
10,457 / 20,924 / 33,951, mandelbrot 69,062 / 110,890 / 139,693, n-body
29,940 / 62,720 / 67,040. LICM keeps standalone constants at their uses
again, as before; the cause is not isolated yet. `x*2.0` as `x+x` stays.
The plan records the numbers and what a retry should check.
2026-11-17 22:16:25 -03:00
waozi 512ddb2e88 Make a loop-carried value in the register its parameter holds
Register allocation hinted a block parameter toward its first incoming
value's register, but not the other way round. A value computed in a loop
and passed back to the loop's parameter got whichever register was free;
after a call that was the result register, so the back edge copied it
into the parameter's register on every iteration, in a block of its own
with an extra jump. The rewritten Fib's accumulator did exactly that:
`add %r12,%rax`, then `mov %rax,%r12` on the way back.

A value passed on an edge now prefers its destination parameter's
register, choosing a back edge's parameter, which is assigned before the
value, over a forward one. The hint only orders registers that are free
for the whole interval, so allocation stays valid as before. Fib's loop
now adds into %r12 and jumps straight back; the one copy moves to the
exit.

regalloc_cases BackEdgeCase builds that loop shape and checks that its
back edge carries no register-changing move; it fails without the hint.
2026-11-17 22:07:23 -03:00
waozi 96ce8d50d6 Keep float constants in registers through call-free loops; x*2.0 is x+x
LICM leaves standalone constants at their uses, which suits integers: x86
takes them as immediates. A float constant has none: each use rebuilt it
with movabs and movq inside the loop. In a loop with no call, which would
clobber every XMM register, a float constant now moves to the preheader
and stays in a register. Mandelbrot's inner loop no longer rebuilds 4.0
and 2.0 on every iteration.

Constant folding rewrites a float multiply by 2.0 as an add of the other
operand to itself. x+x is exactly x*2.0 for every input, signed zeros,
infinities and NaNs included, and needs no constant; GCC emits the same
addsd for mandelbrot's 2.0*zr*zi.

Retained cases: a call-free float loop whose 1.5 moves to the preheader
while its integer constants stay (compiler_opt_licm_cases), and x*2.0
becoming x+x with the same results for 1.5, -0.0, infinity, a NaN and the
smallest subnormal (compiler_opt_float_cases).
2026-11-17 21:39:48 -03:00
waozi 45b74b4e31 Turn a self call added to a value into an accumulator loop
A function whose block ends `r = F(args); s = x + r; return s` (integer
result, either operand order) now adds x to an accumulator and jumps back
to its old entry with args instead of calling itself; every other
`return v` returns `acc + v`, and a new entry starts the accumulator at
zero. Integer addition wraps, so the regrouped sums are exact. The
replaced call ran last in its block, so effects keep their order. The old
entry's fuel moves to the new entry and each jump back charges one step,
so a run counts the same steps as before. GCC does the same at -O2.

Only a function that also has a base-case return is rewritten: one whose
only exit is the self call cannot return normally, so runaway recursion
such as `1 + Forever(depth + 1)` still takes the stack trap instead of
becoming an endless loop.

Fib(n-1) + Fib(n-2) keeps one call per loop iteration, half the calls.
The pass runs first in LirOptBuild, before inlining, as
compiler_opt_accumulate.zi. The new entry takes values 0.. as its
parameters, which native lowering expects of an entry block.

The three passes that each kept a private copy of the same encode/read
helper now share LirSsaSerialize in compiler_opt_ssa.zi.

compiler_opt_accumulate_cases covers fib (one self call left, values for
n = 0..20 with and without inlining), a call added to itself, a float sum
and a function with no base case (all three unchanged).
2026-11-17 21:23:03 -03:00
waozi e0f10da84b Move the compiler lexer adapter into Ziran 2026-11-17 21:19:44 -03:00
waozi aa3e9452bf Keep native heap offset assertions specific to x86-64 2026-11-17 21:09:06 -03:00
waoziandClaude Opus 5.5 91af270734 Share the ARM encoders' trap codes and Relocate
Both targets numbered their nine trap codes alike; they are now
NativeTrap* in compiler_encode.zi, and Relocate, identical once the
relocation kind was shared, moves there too. Each trap sequence's size
stays with its target. The encoders' output is unchanged for all 473
programs of the ZX corpus. Code-size cut 14: 15 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 19:50:52 -03:00
waozi 4c5b7e8eec Expose processor counts and explicit native pool sizing 2026-11-17 19:44:15 -03:00
waoziandClaude Opus 5.5 37f7455c4e Share the ARM encoders' relocations and image builder
One NativeRelocationKind, numbered as both targets' enums were, and the
NativeRelocation record replace each target's own; the mapping to
machine-image kinds and widths and BuildMachineImage, generic over the
encoder's owner, move into compiler_encode.zi. The AArch64 and ARMv7
encoders produce the same output for all 473 programs of the ZX corpus.
Code-size cut 13: 139 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 19:40:48 -03:00
waozi 7f17dcabeb Fold constant divisors and align loop heads on x86-64
The x86 selection plan folds a positive constant divisor that fits an
immediate into the division, which divides by shifts or a high multiply,
so the encoder no longer leaves the divisor's dead register load in loops.
Every loop head now starts on a 32-byte boundary: the divisor change alone
moved fannkuch-redux's loop and cost it 9%.

Alpha A/B against master, microseconds (C, master, now): spectral-norm
10483 23258 21745, fannkuch-redux 16101 19981 19162, mandelbrot 71693
115721 114387, matmul 3992 10673 11877 (five spills in its inner loop
instead of four), quicksort 12692 14119 14439; others within noise.
2026-11-17 19:32:31 -03:00
waozi e6f45f0d57 Keep XMM values across calls whose callee leaves them untouched
A direct x86-64 call to an internal function that register allocation has
already finished now clobbers only the XMM registers that function's
allocated code writes, plus its own calls' masks and the cycle scratch.
Callers keep floating-point values live across such calls in registers
instead of spilling and reloading them. Indirect, recursive and
not-yet-allocated callees keep the full ABI set.

The allocated-code verifier recomputes every function's mask and rejects
a direct call whose XMM clobber does not cover its callee's. The
regalloc cases cover a float leaf, a transitive wrapper, indirect,
recursive and later-allocated callees, a removed clobber, and the mask
collection's work budget.
2026-11-17 19:25:31 -03:00
waoziandClaude Opus 5.5 84f33e9b6a Share the ARM encoders' bookkeeping in compiler_encode
compiler_aarch64.zi and compiler_armv7.zi held the measuring and writing
passes' bookkeeping, operand and type lookups, block and function targets,
the layout arrays and the global image writer twice, word for word. They
now live once in compiler_encode.zi; procedures over the encoder state are
generic over it, so each target keeps its own State. zi2c now declares a
generic's copy whose signature names a module-private type behind the
header's _PRIVATE guard, which this needed.

The AArch64 and ARMv7 encoders produce the same code, ranges, relocations
and entry for all 473 programs of the ZX corpus. Code-size cut 12: 126 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 19:16:28 -03:00
waozi 66bd467132 Shift by constant counts with an immediate on x86-64
The x86 selection plan folds a shift whose count is a constant inside the
operand's width, and the encoder emits shl, shr or sar by that immediate:
no count in cl and no range check, which such a count cannot fail.
native_constant_shifts checks every width and signedness against C.

Alpha A/B against master, microseconds (C, master, now): nqueens 5324 7918
7568; other workloads unchanged within noise.
2026-11-17 18:56:58 -03:00
waozi 0422744e10 Test an inclusive range's end once per iteration on x86-64
An inclusive range with a computed end desugars to a loop that leaves on
cursor == last and steps; rotation copies the header test cursor + 1 <=
last into the latch, where it always holds. The x86 selection plan marks
it known when every entry into the loop tested its value against last and
the latch runs only after the equality exit; lowering drops the compare and
jumps. LIR keeps the test for the vectorizer.

Alpha A/B against master, microseconds (C, master, now): fasta 111321
134842 131285, spectral-norm 10473 24260 23271, fannkuch-redux 15952
20472 20006, quicksort 12712 14342 14088, matmul 3983 10879 10690.
2026-11-17 18:43:53 -03:00
waoziandClaude Opus 5.5 65084bf882 Share the constant owner and the bounded file reader
zi2go repeated the emitter's lookup of the module that owns a constant;
it now calls NativeConstantOwner. zi2zx, zx2wasm and zx2native each read
a bounded whole file; they now call CommandReadBounded, each keeping its
own diagnostic. Code-size cut 11: 53 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 18:39:23 -03:00
waoziandClaude Opus 5.5 b488c2a322 Share the expression owners and the target choice
zi-inspect repeated zir_serial.c's expression owners word for word; it now
calls ExpressionOwners. zi2c, zi2go and zi2zir each chose the target from
--target-os and --target-cpu; they now call CommandConfigureTarget.
Code-size cut 10: 40 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 18:23:16 -03:00
waozi 680f746969 Inline Finite32 and Finite64 in generated C
They move to std/finite, which std/math re-exports. std/math's C header is
named math.h, like the C library's, and such headers get no inline copies,
so every caller made an out-of-line call for three comparisons. finite.h now
carries #inline copies. std_finite_cases checks NaN and infinities on C and
native ZX and that finite.h holds both copies.
2026-11-17 18:23:03 -03:00
waoziandClaude Opus 5.5 46b5935540 Hold the Go SIMD helpers to the C reference
zir_emit_simd_go.c carried a 690-line Go port of zi_ref as a C string,
written only by GoSimdWriteCheck: every helper a program calls has a
typed body, so a missing one is now an internal error. tests/simd_go_ref.go
binds zi_simd_ref to the C zi_ref through cgo, and tests/simd_go.sh checks
all 1,060 typed helpers against it. Code-size cut 9: 665 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 18:12:53 -03:00
waozi b8d9637711 Publish the site's benchmark tables measured at fa65a3fb
One Alpha cohort at fa65a3fb, host gate on, 11 samples: kernels, standard
diagnostic sizes, compile times, examples, JSON and text, and widgets with
the unbounded Wasm build. In the standard set ZX native now beats C on
binary-trees (42.2 against 92.2 ms) and ties it on string-hash. The plan
records matmul's remaining redundancies.
2026-11-17 17:45:56 -03:00
waozi fa65a3fbd9 Report no value for in-process native entries without a result
NativeInstanceRun copied the result register even for a void entry, so
an embedder that compared the value saw whatever the entry's last call
returned. The site's Printing kernel failed this way once allocation stopped
leaving zero there. native_load runs a void entry whose last call returns
42 and expects no result and zero.
2026-11-17 17:32:31 -03:00
waoziandClaude Opus 5.5 3c905a61c1 Unroll Wasm record copies up to 320 bytes
CopyFixed moved a fixed-size value of more than 64 bytes with
memory.copy, which engines run out of line: V8 calls into the runtime for
it. A Kryon paint command (284 bytes) and text record (303 bytes) were
copied that way each time a command was queued or read back. Copies up to
320 bytes are now unrolled into 8-, 4-, 2- and 1-byte loads and stores;
bulk copies keep memory.copy.

Alpha (i7-8700, Node), unbounded Kryon widget scenarios, µs per two-frame
call, before -> after: Button 3.18 -> 3.00, Text 4.63 -> 4.41, Input
5.15 -> 4.45.

Local tests: zx_wasm.sh, zx_web_lifecycle.sh, zx_lowered_parity.sh,
compile_targets.sh, checks_granularity, proven_pointer, nested_vec,
module_parameters, context_scope, insert_source and tool_names pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 17:18:46 -03:00
waozi 478c74a9cf Allocate small blocks in in-process x86-64 code
Resize in in-process native code takes a machine-code fast path for blocks
of at most 256 bytes: per-instance free lists of 16-byte classes and bump
allocation from 1 MB chunks, behind a 16-byte header of count and element
size xor a per-instance cookie. Anything else, including a block whose
header does not match, goes to the host as before, which uses the same
heap for small blocks.

Alpha A/B against master, microseconds (C, master, now): binary-trees
98101 223496 46346; other workloads unchanged within the session's noise.
plans/2026-11-17-standard-benchmarks.md ranks what native still loses.
2026-11-17 17:17:07 -03:00
waoziandClaude Opus 5.5 284fd5ae59 Delete the C functions nothing calls
ImportKindName, FoldIntegerOperation and ExecBundleBytes (with its
no-engine stub) have no caller in any source, test or consumer repo.
The plans drop finished and stale items: the range proofs, the deleted
GPU emitter and Go SIMD body header, and SHA-256, which keeps its C
hardware path. Code-size cut 8: 35 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 17:02:31 -03:00
waozi 7899b2d32b Bound the wasm disassembly in the SIMD check
llvm-objdump 18, the one CI installs, never finished disassembling the
check's 12 KB wasm32 modules, which LLVM 19 lists in 20 ms, so the check
and sanitize jobs ran out of time. A disassembly past a minute now leaves
the SIMD128 count unchecked with a message; a failing one still fails.
2026-11-17 17:01:08 -03:00
waoziandClaude Opus 5.5 bd243f9915 Lower unbounded Wasm without fuel and drop unused frames
`zx2wasm --unbounded` (LowerExecutableUnbounded) makes the module for a
run with no step budget, as a native executable with unbounded fuel is:
fuel instructions emit nothing, no procedure keeps a budget local, and
the module defines global 0 itself instead of importing the mutable
zx.budget, so every other global keeps its index. The budgeted module is
unchanged and stays the default for the playground and limited runs.

The site's widget table builds its Wasm column unbounded, like the C and
Go builds, says so in its methodology, and hashes the Ziran Wasm lowering
(cmd/compiler_zx_wasm*.zi) in place of the deleted zx_wasm_lower.c.

A procedure reserved edge scratch for every block's aggregate
parameters, the entry's arguments included, so one taking a string or a
record set up a stack frame it never used. Scratch is now reserved only
for a block an edge enters with two or more aggregates, the only case
EdgeCopy stages through it.

Alpha (i7-8700, Node), Kryon widget scenarios, µs per two-frame call,
budgeted before -> unbounded with the frame fix: Button 4.07 -> 3.00,
Text 6.05 -> 4.37, Input 6.09 -> 4.57.

Local tests: zx_wasm.sh (new unbounded case: no zx.budget import, same
output, a host with no budget), zx_web_lifecycle.sh, site_pages --check;
make check on HEAD plus this change passes everything a source-only copy
can run (277/284: the 7 others need git metadata, the site tables or a
short path); check-bootstrap matches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 16:53:31 -03:00
waozi 398bd43d9c Divide by constants, align code and branch on float compares on x86-64
Division and remainder by a positive constant that is no power of two use
a high multiply. Functions and ELF/PE code start 32-byte aligned, and
branches stay inside 32-byte blocks, which the jump-erratum fix on Intel
cores needs to keep loops decoded. Ordered float compares fuse with their
branch.

Alpha A/B against master, in-process native, microseconds (C first):
fib 18657 71209 55947, spectral-norm 10433 33048 24017, fasta 110915
288201 134253, quicksort 12684 18539 14294, string-hash 5594 6916 5610,
fannkuch-redux 15693 24525 20530, mandelbrot 71657 120123 114955.
2026-11-17 16:40:01 -03:00
waoziandClaude Opus 5.5 c510c4c8ff Port the C emitter's index range proofs to Ziran
cmd/compiler_c_range*.zi (six modules) replace cmd/zir/zir_emit_range.c:
range facts, conditions and guards, polynomial index proofs, callers'
spliced copies and definite initialization. bootstrap/compiler_c_range/
seeds them for the bootstrap compiler, and zir_emit_internal.h keeps the
emitter's call names as macros over the Ziran entry points.

zi2c and zi2go write the same C and Go as before for 475 programs, with
and without --checks. Code-size cut 7 (bootstrap rank 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 16:34:23 -03:00
waoziandClaude Opus 5.5 d11ae9fe3b Delete zx2native paths it can never run
zx2native reads only .zx and emits only elf, map and image, so its
source-loading branch, optimizer run, lir/opt-report/zx outputs, run
path and their helpers were dead; it also no longer links zx_exec_run.o.
The explain registry drops assembly.gap.machine-parallel, which only
the deleted path emitted. Code-size cut 6: 184 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 15:32:59 -03:00
waozi c4c853819a Place x86-64 check traps after each function's blocks
A passing check now falls through instead of taking a branch over its
trap. Each trap call sits after the function's blocks, and the image
writer and trap-site lookup accept trap and fuel fields there for the
checking instruction's own function.
2026-11-17 15:25:51 -03:00
waoziandClaude Opus 5.5 7fbc8152b0 Look for loops only at blocks an edge leads back to
Hoisting, induction-variable rewriting and loop rotation tried every
block of every function as a loop header, and each try walked the whole
function, so their work grew with the square of a function's size.
Shovey's hosted app bundle (1,178 functions, 215,660 instructions) ran
out of the optimizer's budget in hoisting: "optimization rejected:
problem=5". LirLoopHeaders in cmd/compiler_opt_dom.zi marks the blocks a
depth-first walk from the entry reaches again through an edge back to a
block still on its path; every natural loop's header is one, so no loop
is missed. The three passes search only those blocks, marking them again
after each rewrite, and jump threading uses the same walk.

tests/compiler_opt_budget_cases.zi builds a 3,000-block function with
one loop and requires the optimizer to finish in under 20 million units
of work with unchanged results: it now takes about 0.55 million, and
took 253 million before.

Local tests: compiler_opt.sh and compiler_vectorize.sh pass; make check
on HEAD plus this change passes everything a source-only copy can run
(277/284: the 7 others need git metadata, the site tables or a short
path); check-bootstrap matches; the Kryon widget benchmark and bitmap
image tests pass; Shovey's desktop app.zx bundle builds (48.5 MB).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 14:34:35 -03:00
waoziandClaude Opus 5.5 3005017a2c Port the ZX to Wasm lowering to Ziran
cmd/compiler_zx_wasm*.zi replaces cmd/zx2wasm/zx_wasm_lower.c and .h:
module-wide types, layout, signatures and host shapes; the per-procedure
encoders; block ordering, loop structure, in-place views, member
placement and slot coalescing; instruction lowering; procedure bodies
with frame save and rewind; the heap, image and output helpers; and the
module assembly and API. The modules are part of the instruction engine
that cmd/compiler_runtime.zi names, so zir_zx_wasm.c and zx2wasm call
them under the engine names. A bootstrap build has no engine and keeps
failing stubs for the bundle Wasm tier, as before.

The C and Ziran lowerers give the same bytes for 310 executables from
this tree and Kryon (plain, --opt and --checks), both normal and
suspendable, and report the same wasm.gap codes. The explain inventory
finds the Ziran Gap and WasmDiagnose calls.

Net hand-written code: -794 lines (running total 39,710, 13.69% of the
290,000-line baseline).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 14:29:31 -03:00
waoziandClaude Opus 5.5 e6f4ccecce Publish the mesh-client package page and refresh package pages
GitHub renamed ziranlang/daochi-client to ziranlang/mesh-client, so the
site package inventory lists mesh-client and its page replaces the
daochi-client page. Its exported modules import each other as
mesh_client/..., so site_pages.py reads a package like that through its
own manifest (ziran api --project) instead of plain module paths.

The modules, telegram and webp pages and the sitemap are regenerated from
the current, pushed package sources and the current sitemap order. The
Records native frequency receipt records which harness files and settings
its remeasurements share with the published run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 14:10:13 -03:00
waoziandClaude Opus 5.5 c3b3028f18 Eliminate common subexpressions over the dominator tree
cmd/compiler_opt_dom.zi orders a function's blocks in dominator-tree
preorder, with immediate dominators from the iterative method of Cooper,
Harvey and Kennedy. The CSE pass walks that order with a scoped table, so
arithmetic, comparisons and record reads repeated in a block that an
earlier copy dominates reuse that copy; the earlier one runs first on
every path, so traps and effect order are unchanged. Constants,
conversions, addresses and byte comparisons are still reused only within
their own block: the backend folds them into their uses there, the
pointer prover sees an index converted beside its access, and a byte
comparison reads memory.

Copy propagation and jump threading also run before inlining, so callees
are measured as they will be after cleanup. Member-read inlining charges
its growth to the program's size after each round's cleanup rather than
to each copy it inlines, for up to four rounds.

tests/compiler_opt_cse_cases.zi checks reuse across a dominating block
and none between sibling blocks (fails with the block-local pass). The
optimizer fixture's answer function now merges into one block, and the
regression's compacted constant table lists the folded 14 before 65535.

Local tests: compiler_opt.sh, compiler_vectorize.sh and
proven_pointer_cases.zi pass; make check on HEAD plus this change passes
everything a source-only copy can run (277/284: the 7 others need git
metadata, the site tables or a short path); check-bootstrap matches; the
Kryon widget benchmark and bitmap image tests pass. Alpha A/B of the Wasm
widgets against the previous commit is within noise (Button 4.11 vs
4.17 us, Text 6.23 vs 6.31, Input 6.12 vs 5.87).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 14:05:46 -03:00
waozi 386130b636 Allow independent x86-64 addition results with LEA
Leave integer ADD untied so reused inputs do not require allocator copies. Emit ordinary ADD for shared input/result registers and LEA for independent results, retaining immediate bounds and narrow normalization. Other operations and architectures retain their ties.

Local tests: old encoder and lowering fail the new cases; candidate passes exact bytes, allocation with zero copies/spills, native/lowered parity, full suite 284/284 and bootstrap comparisons. Alpha timing pending.
2026-11-17 12:19:37 -03:00
waoziandClaude Opus 5.5 794a12f458 Thread jumps and merge straight-line blocks
cmd/compiler_opt_thread.zi runs before each CFG simplification. An edge
into a block that only jumps goes on to that jump's target. An edge into
a block that only branches goes to the side it selects when the
condition is a constant there, and a jump into such a branch becomes the
branch. A block is skipped only when its parameters are used in its own
terminal, and no edge moves onto a loop header, so each loop keeps the
one unconditional entry and the one latch that hoisting and rotation
need. Each block whose only predecessor jumps to it then joins that
predecessor. Blocks no longer reached go with their values; every
instruction, fuel included, still runs on each path it ran on.

Short-circuit conditions lower to blocks that join a flag and branch on
it; they now branch directly. The Kryon Button bundle falls from 7,255
blocks and 4,276 jumps to 4,169 and 1,175, and from 1.58 to 1.35 MB;
Text and Input shrink alike.

Local tests: tests/compiler_opt_thread_cases.zi (fails without the
pass), make check 284/284, check-bootstrap matches, and the Kryon widget
benchmark and bitmap image tests pass. Alpha timing is pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 12:19:05 -03:00
waoziandClaude Opus 5.5 0b34cc8a11 Fold theme lookups through joined records and member-read inlining
A member read of a record joined from several branches moves into each
branch, so the edges read the member instead of carrying the record. A
call to a pure procedure whose result is then read only member by member
is inlined for those reads, from callees up to four times the call limit,
for up to three rounds after the program is folded. A Kryon widget's
theme lookup becomes the constant colour or size it reads: the Button
scenario calls DefaultTheme once instead of 17 times.

Control-flow simplification that makes a jump's target the new entry
block drops the old entry instead of leaving it jumping into the new
one, and leaves an entry block with parameters in place.

Local tests: make check 284/284, check-bootstrap matches, and the Kryon
widget benchmark and bitmap image tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 12:19:05 -03:00
waoziandClaude Opus 5.5 c6768a4d60 Port zi2c's C pruning pass to Ziran
cmd/compiler_c_prune.zi replaces cmd/zi2c/zir_c_prune.c and .h: it keeps
only the C interface an entry-linked program uses, chunk by chunk, as the
C pass did. zi2c links its generated module, and bootstrap/compiler_c_prune
seeds it for the bootstrap compiler; check-bootstrap compares that seed.
zir_c_lower.c keeps the mark writer and the inline-section text it shared
with the pass, which the Ziran module calls as PruneInlineText.

The C and Ziran passes write the same files for 178 closed programs in
this tree and 119 Kryon programs, lowered directly with zi2c.

Net hand-written code: -117 lines (running total 38,916, 13.42% of the
290,000-line baseline).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:46:12 -03:00
waozi ffef721f5e Keep spilled values in memory through unused successor blocks
Only propagate a spilled location over its sole actual incoming edge, leaving joins and real fixed/tied reads under the existing allocation policy. Charge the scans to the allocator work budget.

Local tests: regression fails with the old allocator (two spills and two reloads) and passes with this change (one of each), existing cold joins and allocated verification pass, native/lowered parity pass, full suite 284/284 and bootstrap comparisons match. Alpha timing remains pending.
2026-11-17 11:27:41 -03:00
waoziandClaude Opus 5.5 ba6290c771 Publish the Alpha cohort at 5a2ee505 with in-process kernel native
Kernels, the standard suite at diagnostic sizes, compile time and the
example, JSON/UTF-8 and widget tables are measured again on Alpha behind
the host clock gate at 5a2ee505, which has hardware sqrt, the scalar
conversion fix and the callee-first inliner. Native n-body falls from
378 to 64.5 ms (C 30.1) and spectral-norm from 112 to 26.9 ms (C 10.3).

The kernel table's ZX native column now runs each bundle translated in
process, so it no longer carries process startup: Records reads 21.1 us
against C 16.5. Sieve, Vectors and Printing are slower in process than
the old per-process figures; the gap list explains why.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:21:34 -03:00
waozi 0bf00c77db Remove record-field pairing; it measured neutral on Alpha
The SSE2 pairing of adjacent record-field updates fired in the Records
hot loop but did not change its speed: 19.48 against 19.50 µs per call
on Alpha's i7-8700 with process startup amortized over 512 calls (C:
16.5 µs). Both lanes must return to general registers for the bounds
compares, so seven vector instructions replaced eight scalar ones. The
other kernels' executables were byte-identical with and without it.

Restore the pre-pairing machine IR, lowering, verifiers and x86 emitter,
delete cmd/compiler_vectorize_pair.zi and its tests, and keep both Alpha
receipts (bench/results/records-pair-*-alpha-2026-11-17.json). The plan
names the remaining Records gap to C.
2026-11-17 11:07:40 -03:00
waoziandClaude Opus 5.5 5a2ee505c0 Time kernel native in process and re-pick the gated core
The kernel native column ran 32 calls per zx2native process, so every figure
carried about 5 µs of process startup that C, the engine and Wasm exclude. It now
runs the same bundle through site_target_host.c with the native backend, translated at instantiation before warmup; the ELF is still run once as an output check. The host gate re-picks the quietest core after a rejection, waits for its hyperthread to settle, and logs each rejection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:02:37 -03:00
waoziandClaude Opus 5.5 08f85f5d15 Generate the SIMD headers at build time from a Ziran generator
scripts/simd/ (17 Ziran modules) replaces scripts/simd_header.py and
writes ziran_simd_ops.h, ziran_simd_types.h and zir_simd_go_bodies.h into
$(BUILD_DIR)/simd before anything includes or embeds them. The build
compiles the generator from its seed in bootstrap/simd; check-bootstrap
regenerates and compares that seed and update-bootstrap refreshes it.
The committed headers are deleted; the generated output is byte-identical
apart from the first comment line naming the generator. tests/simd_go.sh
drops its Python comparisons, which the seed check replaces.

Net hand-written code: -38,751 lines (running total 38,799, 13.38% of
the 290,000-line baseline).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 10:59:38 -03:00
waozi d033f60448 Read record members through inserts and drop unused pure calls
The copy pass follows an extracted member down the chain of inserts that
built its record: the insert that replaced that member gives the value,
and inserts of other members are looked past, up to the aggregate that
began the chain. The dead-code pass removes a call whose result is unused
when its procedure cannot be observed: no stores, host or indirect calls,
operations that may trap or loops, and calls only to such procedures.
Effects are renumbered after removal.
2026-11-17 02:24:08 -03:00
waozi 3f69e9c5fd Remove argument-register hint after matched Alpha regression
Restore the prior allocator and retained fixtures: the candidate removed both fib argument moves but increased measured fib time by 13.20%, despite passing correctness tests. Keep all 165 timed results and standard host-gated samples in the negative Alpha receipt. No unmeasured microarchitectural cause is claimed.

Local tests after removal: regalloc, zx_native, lowered execution parity, full make check (284/284), and make check-bootstrap, with learning off.
2026-11-17 02:16:59 -03:00
waozi 1ac1653faa Inline callees after their own calls are inlined
The call inliner visits functions callees first, by a depth-first search
of the call graph without recursion, and copies each callee in its
expanded form. A helper's inlined helpers come with it, and a callee that
grew past the size limit stays a call instead of bringing its original
calls along. spectral-norm's Spectral now calls Multiply, which has A
inlined, instead of calling A inside its loops.
2026-11-17 02:06:30 -03:00
waozi b9b66c1b8a Prefer tied arithmetic results in available fixed argument registers
Carry the result fixed-register preference back to its short tied-input copy only when the register is free through the result interval. Preserve source and previous-part hints otherwise, avoiding new pressure splits.

Local tests: free and occupied argument register fixtures, regression fails with old allocator, zx_native, C/engine/native/Wasm execution parity, full make check (284/284), and make check-bootstrap. Alpha matched timing follows at this pushed revision.
2026-11-17 02:01:55 -03:00
waozi 378e2870d3 Merge record-field pairing onto master
Keeps the Alpha-measured pairing commit in history.
2026-11-17 01:53:19 -03:00
waozi 4a488a44f3 Inline single-block callees in place
A callee with one block whose returned value one of its instructions
defines, such as std/math.Sqrt, is copied straight into the caller's
block: its parameters become the call's operands and the returned value
becomes the call's result, with no continuation block, jump or block
parameter. n-body's Nbody returns to 31 blocks with no calls left.
2026-11-17 01:51:52 -03:00
waozi 970b7687db Record Alpha scalar conversion dependency comparison
Retain 11 matched interleaved samples, standard host gates, raw samples and symmetric IQR exclusions. All 165 timed runs match C. Spectral-norm takes 13.84% less time. Retain the unrelated matmul timing difference without attributing it to the conversion encoder, and document remaining assembly findings. Source changes passed the full local suite and bootstrap before their feature pushes.
2026-11-17 01:51:23 -03:00
waozi f662d6c53a Pair adjacent record-field updates into SSE2 operations
Native x86-64 lowering now recognises two adjacent 64-bit integer
record-field updates read from disjoint adjacent fields of the same
record (x += dx; y += dy and the subtract/and/or/xor forms) and emits one
VectorPair instruction: two unaligned 16-byte loads, one packed integer
operation and one store, then both scalar results extracted for later
uses such as bounds comparisons.

The planner (cmd/compiler_vectorize_pair.zi) runs after the verified
virtual program is finalised, under the compiler's work and byte
budgets, and only for unchecked, unfueled x86-64 code. Both verifiers
check the packet form; XMM0/XMM1 are explicit clobbers so live
floating-point values are allocated elsewhere. Overlapping field pairs,
extra uses of the loaded values and checked builds keep scalar code.
2026-11-17 01:48:35 -03:00
waozi d647525b07 Break false XMM dependencies before scalar integer conversions
Clear unused high lanes before legacy CVTSI2SD/CVTSI2SS, preserving the converted value and condition flags while making the conversion independent of earlier arithmetic. Measure and write paths share the same encoder.

Local tests: exact low/high register encodings and output limits, signed/unsigned f32/f64 rounding boundaries and random integers against an integer ties-to-even reference through C/engine/native/Wasm, zx_native, full make check (284/284), and make check-bootstrap. Alpha matched timing follows at this pushed revision.
2026-11-17 01:39:58 -03:00
waozi 5065f7a577 Delete superseded historical benchmark receipts 2026-11-17 01:36:16 -03:00
waozi ceb9de7737 Record Alpha hardware sqrt and recursive entry comparisons
Retain 11 matched interleaved samples, standard host gates, raw samples and symmetric IQR exclusions. All 330 timed runs match C. Separate the two compiler cohorts and identify remaining native gaps. Source changes passed the full local suite and bootstrap before their feature pushes.
2026-11-17 01:28:32 -03:00
waozi 439dbcf10d Remove unused C helpers and superseded records 2026-11-17 01:21:52 -03:00
waozi 84a89f4c8e Return simple integer base cases before the x86-64 frame setup
Track original incoming integer arguments through pure allocated copies and emit a small leaf return before saving registers or reserving the frame. Keep checked, fueled, effectful and narrow-integer entries on their ordinary path. Fold adjacent 64-bit copies and constant additions/subtractions into LEA.

Local tests: exact encoder and exclusion fixtures, recursive signed/unsigned call parity against C, zx_native, full make check (284/284), and make check-bootstrap. Alpha matched A/B follows at this pushed revision.
2026-11-17 01:10:10 -03:00
waozi 52aad2d6cf Document the optional audio package after the core move
Regenerate the published audio package page and its module index row from the validated Opus and sinc package.
2026-11-17 01:00:02 -03:00
waozi 2313b49cb0 Add core IMA and Microsoft ADPCM WAV decoding
Validate mono/stereo blocks, coefficients, fact frame counts and bounded output. Exercise exact independent PCM references, source/saved mixer playback and malformed input. Limit the upstream Vorbis shift sanitizer exception to its external target.
2026-11-17 00:49:53 -03:00
waozi bda3d67882 Inline small procedures across their callers' control flow
LirInlineCalls copies a direct call's small portable callee into the
caller: the call's block ends with a jump to the copied entry, each copied
return jumps to the rest of the block, whose parameter is the result, and
effects are renumbered. Callees are the input versions, so the pass goes
one level deep. Eligible callees have at most 48 instructions, keep no
stack storage, do not call their host and do not call themselves. The
program grows by at most half (at least 256 instructions) and never past
what the remaining optimizer work admits, so a very large program keeps
its budget. The program is written and verified once.

Inlining makes accesses through small helpers' parameters direct, so the
pointer-proof fixture expects the new direct counts and its width tamper
targets the widest direct store. Fixtures that test a nested call, Twice
for the frame budget and Divide for a debug trap's procedure name, call
themselves on a never-taken branch so they stay calls.
2026-11-17 00:29:16 -03:00
waozi 515449986e Lower f64 square root to hardware instructions across native and portable targets
Replace software normalization and Newton iterations with a checked f64 sqrt intrinsic and pure LIR operation. Emit sqrtsd, fsqrt, vsqrt.f64 or f64.sqrt; use the corresponding C/Go operation in generated output and the portable engine. Keep the embedding library free of a new errno fallback dependency.

Local tests: full make check (284/284), make check-bootstrap, exact encoder bytes on all native backends, source/saved C and Go parity, native/Wasm/engine parity, malformed LIR rejection and portable budget equivalence. Independent integer digit-by-digit reference matches libm at every exponent and one million bit patterns. Alpha A/B follows at this pushed revision.
2026-11-16 23:56:16 -03:00
waozi e0367fa9c5 Restore signed interval comparison folding
Restore the compiler, bootstrap and regression hunks inadvertently reset by the audio integration.
2026-11-16 23:35:04 -03:00
waozi 03543b73fd Fix bank-specific scratch detection in native copy verification
Retain the conditional floating-point argument regression.
2026-11-16 23:20:52 -03:00
waozi 255a96027a Retain interleaved Alpha native backend measurements
Measure the same frozen standard ZX bundle with baseline and improved native runtimes and independent C on physical Alpha. Retain eleven interleaved samples per target, all host-gate attempts, raw timings, checksums and the driver source.

N-body improves13.1% and spectral-norm38.0%; large gaps remain. Other measured kernels change little. Local receipt validation verifies11 accepted checksum-matching runs per target; compiler full local suite and bootstrap passed before the measured commit.
2026-11-16 22:50:43 -03:00
waozi b88ab90c92 Share native Vorbis builds and validate Windows audio ABI 2026-11-16 22:40:16 -03:00
waozi 426c732928 Optimize native constant division and fix cross-block register copies
Use shifts with a signed rounding bias for division and remainder by known positive powers of two. Keep layout-adjacent live-range gap transfers inside one block; existing edge copies reconcile actual control flow.

Local validation: make check (284/284), make check-bootstrap, exact x86 encoder bytes, integer width/boundary/random parity, and a backward-definition regression that fails with the old allocator. All 54 inlined parity bundles also match engine output with the fix. Alpha timing follows at this pushed revision.
2026-11-16 22:37:31 -03:00
waozi 13bb919632 Measure every site table at one commit behind a host clock gate
The published native kernel column had run at about half clock: Alpha's
powersave/HWP governor moves between 0.8 and 4.3 GHz and short native
processes caught it low. wasm_tier.py --host-gate now runs each
measured job on one logical CPU of the quietest core, inherited by the
child so no wrapper process adds time, with Go at GOMAXPROCS=1, and
polls that CPU's clock and its hyperthread sibling from the other
cores. A job is kept only if its clock stayed within 3% of its median
at 95% of the calibrated sustained clock with the sibling idle;
otherwise it runs again, and rejected attempts stay in the receipt.
The kernel and standard generators refuse ungated receipts.

Kernels, the standard suite at diagnostic sizes, compile time and the
example, JSON/UTF-8 and widget tables are all measured again at
d3feb8a3; native Sieve, Records, Hash and Vectors now read 52.8, 36.5,
33.2 and 41.5 us, matching the matched A/B lanes. Widget downloads name
Kryon's license after its repository and drop stale copies, and the
example, JSON and widget generators gain --render.
2026-11-16 22:30:21 -03:00
waozi d3feb8a34b Rotate loops in memory and write the program once
LirRotate serialized, re-read and re-verified the whole program after
every rotated loop, so a large program paid one full codec round trip and
three verifications per loop: bundling compiler_opt_test made 1041
whole-program reads and 3144 verifications, past CI's 180 s step limit.
Rotations now rebuild each function in memory, keep only its latest
version, and the program is written and verified once at the end. An
unsupported rotation is still skipped and any other failure still stops
the pass.

That bundle takes 10.8 s instead of 41 s (88 s before the verifier and
codec fixes), and compiler_opt.sh 65 s instead of 250 s.
2026-11-16 21:55:24 -03:00
waozi 6742ac54cc Retain Alpha Records bounds-fold measurements and limitations
Keep fresh matched-harness raw samples, compiler provenance, restoration
guards and independent IQR verification. Document unchanged-binary host
variation and the remaining native gap against C without a causal claim.
2026-11-16 21:50:30 -03:00
waozi dd0aff6424 Move non-UI audio into std with Android PCM and async sinks 2026-11-16 21:46:29 -03:00
waozi 617dd0ede2 Fold stable signed interval checks during ZX lowering
Use one same-width unsigned comparison for repeated signed interval checks
on stable locals, record members and fixed-array elements. Preserve calls
and other expressions whose second evaluation can matter.

Cover signed widths, extrema, member/index paths and short-circuit behavior
in the retained lowered parity fixture; refresh generated bootstrap code.

Local validation: compiler optimization/vectorization and lowered parity,
full retained suite (284/284), and bootstrap comparison.
2026-11-16 21:45:54 -03:00
waozi 6d7ddadb72 Document only current Ziran behavior
Remove obsolete migration, roadmap and research documentation. Describe the current native/ZX/Wasm pipeline, manual safety and offline learning. Refresh current guides and remove historical website prose while preserving unpublished audio work.
2026-11-16 21:40:58 -03:00
waozi 83d541dc68 Keep cheap loop invariants near their uses
Retain dependencies of useful invariant expressions without hoisting standalone cheap values across growth loops. Add spill and correctness regressions and retain matched Alpha comparisons.

Local validation: 284/284 retained tests and bootstrap matched. Vectors improved from 85.8 to 42.5 microseconds on physical Alpha.
2026-11-16 21:27:29 -03:00
waozi 8cabdb9e64 Add standard language benchmarks and one clean site number format
bench/standard/ holds recursive Fibonacci, n-body, spectral-norm,
mandelbrot, fannkuch-redux, binary-trees, fasta, nqueens, integer matrix
multiplication, quicksort and FNV-1a hashing in Ziran, C and Go, every
input read at run time and every result checked against C.
wasm_tier.py --standard measures C, Go, native ZX and Wasm on Alpha's
physical host; standard-compile times whole-suite builds. The kernel
table gains Go references. Receipts at the published compiler commit
6a066abd, the earlier 96c23c7d receipts and a ranked native-versus-C
gap list are retained in bench/results/standard/.

Every benchmark table on /targets now uses one format: three significant
digits, thousands separators, no scientific notation, one unit per
table in its header. Python generators share format_number in
site_targets.py; the Ziran renderer uses scripts/site_numbers.zi; the
site test checks both against NUMBER_CASES and the page for exponents.
targets.js shows the pre-formatted texts instead of formatting itself.
The example and JSON/UTF-8 tables were re-measured with the updated
harness on the same host and commit so their harness hashes hold.
2026-11-16 21:06:32 -03:00
waozi 7897145d25 Verify dominance once per function and read codec fields whole
The LIR verifier checked that a definition dominates each use by searching
the control flow graph from the entry around the defining block, once per
use, so a large function cost uses times blocks. It now builds one
dominator tree per function (Cooper, Harvey and Kennedy over reverse
postorder) and answers each use with a pre/post interval comparison. The
verifier also frees its tables.

The codec read and wrote every integer byte by byte with a bounds check
per byte; a whole 32- or 64-bit field now takes one check, and a field
that does not fit still goes byte by byte, so truncation errors and their
offsets are unchanged.

Every optimizer pass verifies and round-trips the whole program, and the
loop passes added more of both, so bundling compiler_opt_test grew past
CI's 180 s step limit. That bundle now takes 41 s instead of 88 s on the
development desktop.
2026-11-16 20:49:05 -03:00
waozi bafbad6c8b Publish one-revision site tables with the Wasm widget fix
Kernels, examples, JSON/text and Kryon widgets were measured together at
6a066abd on one physical Intel Core i7-8700 host, 11 samples each, checks
and learning off, with Kryon exported at its pushed 08f70214. Wasm widgets
take 5.59, 7.27 and 8.41 µs per two frames (Button, Text, Input) instead
of 1056, 715 and 1234 µs, faster than native ZX (7.09, 9.14, 9.86 µs);
Go takes 4.11, 3.72 and 6.65 µs.

The kernel table drops the constant-folded Calls row, and its driver no
longer builds it. Library receipts record the compiler package path, so a
project pinned to an older compiler cannot pass as the one measured.
2026-11-16 20:03:23 -03:00
waozi 22c756016b Record matched Alpha loop and SIMD benchmark results
Retain both physical Alpha cohorts, raw samples and exclusions, host observations, compiler provenance and the exact measured harness delta. Record the remaining C gaps and Vectors regression without attributing changes to an individual pass.

Local verification passed for all 40 target/kernel sample sets and exact harness reconstruction. Compiler suite and bootstrap validation are retained in the prior milestone receipt.
2026-11-16 19:55:40 -03:00
waozi 6a066abdb2 Build Wasm record members where their parent keeps them
zx2wasm reads a large record's fields where the record lies instead of
copying it whole, gives record parameters and results the caller's
storage, and leaves out constructor stores that are overwritten before
use. A member, call result or returned record is now built directly in
the parent field, caller result or join where it ends up, and a returned
load copies once, from its pointer. Kryon's default theme was copied
record by record on every lookup; its constructors now copy nothing.

A host call that only reads a []T argument no longer copies its elements
back when they are unchanged.

The Wasm fixture covers snapshots across stores, calls and edges,
by-value aliasing, members that read the field they replace, a parent
made after its member, joins, and read-only host views.
2026-11-16 19:51:53 -03:00
waozi ebd19223fa Link Windows ZX external hosts through named DLL imports 2026-11-16 19:15:37 -03:00
waozi ddd853e149 Retain record types referenced by linked foreign signatures 2026-11-16 18:43:50 -03:00
waozi 18fb5aeb6c Optimize shared LIR loops and native SIMD prefixes
Add bounded natural-loop discovery, total scalar LICM, modular induction
strength reduction and deterministic block layout before native/engine
lowering. Preserve SSA edges, effects and zero-trip behavior, with retained
Ziran coverage through the existing optimizer entry point.

Add guarded SSE2 prefixes for supported integer reductions and slice maps,
with scalar tails, checked/fuel fallback, overlap guards and retained C
differential tests. Reject unsupported entry instruction placement and
malformed vector forms with a diagnostic.

Repair merged scalar allocator intervals and selected-expression binding
joins; retain allocation/short-circuit regressions and regenerate the matching
bootstrap seed.

Local validation: full retained suite 281/282, all compiler tests pass;
bootstrap matches. The sole suite failure is stale generated site pages.
Compiler inputs and seven binaries stayed unchanged. The global source guard
recorded an unrelated site generator change and two new foreign-record test
fixtures; these files are excluded. Alpha performance remains unmeasured.
2026-11-16 18:31:38 -03:00
waoziandClaude Sonnet 5.5 ae16ed5112 Record that the Records native slowdown is CPU frequency, not code
The published Records native 100.5 us (revision 96c23c7d) against 47.8 us
(revision 1fd89e81) is not a compiler regression. The native ELF in both
receipts has the same sha256 (as do all six kernels' native ELFs between
them), the same revision re-measured on the same physical host with the
same harness gave 47.75 us, and one unchanged ELF takes 45.4 us per call
at 4.3 GHz and 240.9 us at 0.8 GHz: time x frequency is constant
(195.7 us*GHz, 192.7-197.2 over 26 steady rounds), which puts the 100.5 us
run at about 1.95 GHz. Revision 36e6caf9, with the constructor placement
commit, measures 47.2 us. Pinned to cpu 0, 2 or 4 the same ELF is slower
still because those logical CPUs share a core with a busy sibling thread.

The receipt keeps the script, the raw rounds with the frequency read
before and after each, and the same-revision re-measurements.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-16 18:30:15 -03:00
waozi 225784c977 Record guarded Alpha C-teacher and widget comparisons 2026-11-16 18:25:03 -03:00
waoziandClaude Sonnet 5.5 898f58a5fb Build a returned record in the caller's result memory
When every return of a function gives the same aggregate class, that class
and every member class placed in it now live in the memory the caller's
hidden result address names, so the return has nothing to copy. The hidden
address belongs to the callee alone while it runs: callers pass a frame
object of their own (or a host buffer), and nothing else holds its address.

The planner (ChooseResult) picks the class only when the record is at least
16 bytes (a smaller copy is one or two moves, cheaper than saving and
setting a register) and declines a returned parameter or a class holding
one, two different classes returned on different paths, a split record, a
view, and anything but a plain aggregate operand; those keep the copy.

On x86-64 such a function keeps the address in r14
(MachineAbiResultPointerRegister): the prologue sets it from rax beside the
existing store of the hidden address, frame layout saves it like any
callee-saved register, allocation never hands it out
(MachineFunction.result_register), StackMemory turns an object placed in
the ResultAddress object into [r14 + placed_at], and Return skips the copy.
A nested shadow-token builder shaped like Kryon's DefaultShadows now zeroes
and fills [r14 + ...] directly; a recursive Chain passes its own result
memory to its recursive call.

Both machine verifiers check the new form: a placed Value object lies in
the result memory only in a function that says so, within the result type's
size, with offset equal to placed_at; the allocated verifier also requires
exactly one hidden result address, the saved register, and no allocated use
of it. A member placed at a packed, unaligned layout offset keeps only the
alignment that offset has (commented in lowering).

Retained tests: machine_place_cases gains the result cases (returned record
and its members placed, small records, parameters and two returned classes
copied, a call between a member and its record, a member spanning two
blocks) and structural and allocated negatives for the result placement;
machine_elf.sh runs a native program with a loop-built 280-byte record, a
packed record with an unaligned float64, a record inside another at an odd
offset, recursion, many live values, shared and rebuilt records.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-16 17:16:07 -03:00
waozi a129921478 Repair shared LIR SSA arguments and rotate guarded loops
Add bounded SSA repair and loop rotation modules with retained tests for exits, nesting, parameter renaming, fuel ordering and unsupported CFGs. Keep rotated integer range proofs precise with finite widening thresholds.

Validated on canonical Omega: build and bootstrap pass; all compiler suites pass in the stable full run, and the two publication failures pass after focused reruns. Retain raw benchmark samples and report the remaining C performance gap.
2026-11-16 16:57:57 -03:00
waozi 36e6caf964 Learn verified native integer idioms from C and tune offline policies
Add modular Ziran C/native assembly comparison and SIGPROF reports for the
six kernels, three widget scenarios and hello. Use closed differential-tested
multiply idioms, compact IMUL immediates and bounded scalar leaf inlining.

Extend ziran learn with offline rule verification and deterministic policy
selection joined to current-format corpus identities. Builds use a reviewed
versioned source table; benchmarks keep recording off. Identical artifacts
share timing evidence, so the initial calibration retains the baseline policy.

Local validation: 281/281 tests and bootstrap passed; the subsequent stable
constructor checkpoint passed all compiler tests and bootstrap. Its two site
receipt failures were resolved and both retained site tests passed in a
separate final run. Preserve all raw timings, exclusions and source-epoch
limitations in bench/results. Remaining loop/widget work stays with its lanes.
2026-11-16 16:56:03 -03:00
waoziandClaude Sonnet 5.5 e991274a2e Build record members where their parent keeps them and fold float constants
A member value built only to be put into a parent's storage now takes a
frame object inside the parent's on x86-64, so the copy at the use moves
a member onto itself and emits nothing. It covers the members of an
aggregate build, the value of an insert that updates its source in place,
a value inserted through a changed view at a constant offset, and a call
result used as a member. A class qualifies when it lives in one block, has
exactly one use outside it, nothing between its first definition and that
use touches the parent's storage, nothing defines or uses it after that
use, and the parent has a frame home. An aggregate build whose members
are all replaced one constant member at a time before it is read emits
nothing. The planner charges all of its work to the shared budget and
declines instead of failing when it would run out.

The machine IR gains placed stack objects (placed_in, placed_at). Frame
layout gives them no space, x86-64 CopyMemory skips a copy onto the same
memory, and both verifiers check that a placed object is a Value of the
same function lying inside a parent that has a home; the allocated
verifier also keeps placed objects out of the no-overlap sort.

The optimizer folds f64-to-f32 and f32-to-f64 constant conversions to the
hardware's patterns (ties to even, overflow to infinity, subnormals) and
float negations; a NaN keeps its operation.

A nested shadow-token builder shaped like Kryon's DefaultShadows shrinks
from 1759 to 661 bytes of code. Retained tests: machine_place_cases (eight
planner cases on hand-built LIR with frame verification, budget accounting
and malformed placements), compiler_opt_float_cases (28 vectors checked
against hardware conversion), and a native nested-record program in
machine_elf.sh with shared, escaping, loop-carried and call-result
members.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-16 16:53:04 -03:00
waozi 1a97a1a571 Publish verified Wasm widgets and one physical-host benchmark cohort 2026-11-16 16:52:02 -03:00
waozi d17c7aa1e0 Release Ziran 0.6.0
Ziran is manually safe like C by default with --checks and #checks to opt in, native code is much faster (Kryon's widgets run natively in 8.6–13.1 µs on Alpha), zx2native writes Windows PE executables, and ARMv7 runs ZX natively by default; the changelog section lists what users get. update_version.sh set the version files and the standard-library inventory, and site_pages.py regenerated the module pages for 0.6.0.
2026-11-16 16:47:38 -03:00
waozi 96c23c7de6 Use defining modules for portable host type identity
Resolve record and enum names through their defining module when writing the
host interface, including container element names. Match package-qualified
module names against plain host module names without accepting other modules.
Update native host assertions and the generated bootstrap lowerer.

Local tests: host records, slices, arrays, capability, VM payloads and browser
lifecycle passed; check-bootstrap passed. Full check initially 275/281; the two
wire-name assertion failures now pass. Remaining failures were unrelated
placement/debug output and a stale generated site page.

Reported-by: Breeze task codex-breeze-breeze-crash-recovery-ui
2026-11-16 16:13:27 -03:00
waozi 900ed8f716 Regenerate the usage and ZX guide pages from their docs
docs/USAGE.md and docs/ZX.md changed without regenerating site/guide; site_pages.py --check reported them stale.
2026-11-16 15:53:58 -03:00
waozi 42dc1b0f41 Fix diagnostic registry and offline Go toolchain selection 2026-11-16 15:45:13 -03:00
waozi 444649ed6f Publish physical Alpha native widget measurements and explicit tier receipts 2026-11-16 15:41:38 -03:00
waozi 1fd89e81cd Avoid native aggregate field snapshots and cache validated stack bounds 2026-11-16 15:30:37 -03:00
waoziandClaude Sonnet 5.5 8a3b727cfc Fold a constant zero element index into its base address in native code
An ElementAddress whose index is the constant zero and whose lowering
needs no bounds check (the unchecked form, or an index the shared facts
prove below its bound) now aliases to its base and emits nothing, and
that use no longer materializes the index constant. The alias keeps its
base's pointer type only when every use moves the pointer value itself,
so a typed aggregate build never reads through a retyped alias.

An alias may name a value that a later fold aliased in turn, so every
alias, and every cached split-record field virtual, now points at the end
of its chain; a record built from a field of another record no longer
names an eliminated virtual.

Hello's main is four machine instructions instead of six. The map-based
instruction count in tests/machine_elf.sh now steps past each range
correctly, and a retained alias-chain case (Triple/State, SampleAt) runs
natively and returns its own field values.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-16 15:22:03 -03:00
waozi 888f39a992 Link host capabilities from registered host libraries in native executables
zx2native now writes a Linux x86-64 executable for a program that calls
host capabilities instead of stopping at assembly.gap.machine-host. Each
capability links by name from a registered host library, a NAME.library
file beside the .host players that ziran run dispatches to (ZIRAN_HOST_PATH,
or ~/.local/share/ziran/hosts then XDG_DATA_DIRS), with the C ABI the C
target declares for it, so a host library built from Ziran through the C
target serves both routes.

The ELF gains PT_INTERP, PT_DYNAMIC (one DT_NEEDED per library), a symbol
and an R_X86_64_GLOB_DAT relocation per capability and PT_GNU_STACK; the
data holds each capability's slot, and compiler_x86_host.zi writes one
System V veneer per capability that moves the program's arguments into the
C registers (strings and slices as their two words), calls through the slot
and widens the result as the program keeps it. A program with no host
capability stays the static executable it was, byte for byte.

A capability no registered library defines is still the machine-host gap,
which now says so, and a signature the veneer cannot carry is
assembly.gap.machine-host-abi; nothing falls back to another engine.
tests/machine_elf.sh links a provider built by the C target and checks
string, integer, bool, float and narrow-result calls, the map and both gaps.
2026-11-16 13:07:32 -03:00
waozi fde5c44154 Note the index-proof failure loop rotation causes
With the pass on, proven_pointer_cases fails because the shared index
proofs do not recognize rotated loops; the plan says so and no longer
claims the suites pass.
2026-11-16 13:01:30 -03:00
waozi 30b2374fed Record the loop-rotation result: correct, shorter, measured slower
The SSA rotation pass is on branch wip/loop-rotation. It shortens every
rotated loop but measured Sieve and Records slower in a controlled A/B, so
it waits for a loop-alignment check before it lands.
2026-11-16 12:55:51 -03:00
waozi 4389559ae6 Coalesce copy-related block parameters in native register allocation
Before intervals are built, a block parameter whose value an edge copies
into another block's parameter shares that parameter's root interval when
neither is live where the other is defined. They are SSA values, so they
never hold different values at once, and the copies between them become
relabelings with no move. Sieve's outer loop count now stays in one
register, and its common path branches straight to the increment instead
of through an edge block.

A merged interval that is split can still leave a stack slot holding the
other value; Vectors tripped the allocated-code verifier that way. So
RegAllocAllocate allocates once more without coalescing whenever the
verifier rejects the first result, and only verified allocations are
published.

On Omega, A/B of 41 processes x3 against the commit before block layout:
Sieve 31 -> 24 us, Records 18 -> 15 us, Hash and Vectors unchanged. The
28.7 MB Unicode conformance bundle compiles natively in 1.7 s. The
private clone's make check passes 278 of 280 (zx_web_lifecycle fails on
clone path length; packages on a package-resolution case outside native
code), check-bootstrap matches, and the four tier kernels return their
checksums.
2026-11-16 11:57:38 -03:00
waozi 848d11dd48 Plan the allocator coalescing and the SSA loop-rotation pass
The loop count's register mismatch comes from intervals without lifetime
holes. The plan names the two allocator designs that fix it, and lays out
the LIR loop-rotation pass as its own module run before native and Wasm
lowering.
2026-11-16 11:47:39 -03:00
waozi dd102f8a58 Record why Sieve's loop-count copy needs coalescing in the allocator core
The loop count's parameter already hints at the header count's register;
it is denied because the closing copy is the parameter's last use and the
header count's definition at one position. Preferring loop-carried hints
changes nothing, so the plan names where the fix belongs.
2026-11-16 11:33:41 -03:00
waozi d2d33d3556 Lay native blocks out with exits last and skip pass-through blocks
The selection plan now orders each function's machine blocks: the entry
first, then the other blocks in LIR order, then every block that returns,
traps or is unreachable (including blocks nothing reaches). Lowering emits
them in that order, so a loop's hot blocks fall into each other. Each
machine block keeps its LIR block for maps and trap reports, and later
stages see blocks in id order as before.

An edge into a block that only jumps on, with parameters used by nothing
but that jump and all values in registers, goes straight to the jump's
target. Values from elsewhere dominate the skipped block and every edge
into it; its parameters are replaced by the arguments passed to it. Such a
block dies and sinks to the end. A block whose jump already threads into a
branch keeps its edges, since that branch's block may be dead.

On Omega, A/B of 41 processes x3: Records 17.4 -> 15.1 us; Sieve, Hash and
Vectors within noise. The private clone's make check passes 278 of 280
(zx_web_lifecycle fails on clone path length; packages on a
package-resolution case outside native code), check-bootstrap matches,
and the four tier kernels return their checksums.
2026-11-16 07:36:14 -03:00
waozi 17677858b3 Forward extracts of just-inserted values instead of reloading them
LIR aggregates are values, so a scalar extract that reads a place an
insert just wrote is that insert's value. Before lowering each function,
a pass walks every scalar extract's aggregate back through inserts at
the same key (equal constants or the same index value), past inserts at
a different constant key, and into the extracts its aggregates came from.
When it reaches the inserted value, the extract becomes an alias of it
and emits nothing. In Records, the `x > 1000` and `x < 0` tests after
`x += dx` now compare the register instead of loading x back.

The timing gain is within noise on Omega: the hardware forwarded the
store to the load cheaply. The private clone's make check passes 278 of
280 (zx_web_lifecycle fails on clone path length; packages on a
package-resolution case outside native code), check-bootstrap matches,
and the four tier kernels return their checksums.
2026-11-16 06:21:19 -03:00
waozi aea1e2adff Fold unchecked element addresses into their load or store
In an unchecked x86 build, an element address whose only use is a scalar
load or store later in its block is not computed on its own. The
selection plan records its base, index and scale shift (elements of 1, 2,
4 or 8 bytes), lowering skips it and gives the access base, index and
shift operands, and the encoder reads or writes `[base + index*scale]`,
with an immediate value for a constant store. Sieve's inner loop drops
from 7 instructions to 5.

On Omega at load 8, three A/B runs of 41 processes each: Sieve 33 -> 29
us and Vectors 37 -> 26 us; Hash and Records are unchanged. The private
clone's make check passes 278 of 280 (zx_web_lifecycle fails on clone
path length; packages on a package-resolution case outside native code),
check-bootstrap matches, and the four tier kernels return their
checksums.
2026-11-16 06:15:50 -03:00
waozi 1d071b6765 Record why native loop rotation needs an SSA pass in the LIR optimizer
The optimized LIR names a loop header's parameters directly in the body,
so copying the header's test to the latch while lowering skips their
update. With the condition that makes it safe, it never applies. The
plan now names the pass that would: rotation in the shared optimizer,
with block parameters for the body.
2026-11-16 05:30:39 -03:00
waozi 4001c4e8ac Store constants as immediates and forward jumps past lone jumps
In unchecked builds, a store whose value is a constant that fits a
sign-extended imm32 writes it directly: the selection plan folds the
value, lowering passes it as an immediate operand, and the encoder emits
`mov size [address], imm`. Checked builds keep the value in a register,
because the checked-memory proof sizes each store by its value.

A jump or branch into a block that holds nothing but register self-moves
and a jump goes to that jump's final target in one step, and falling
through checks the same forwarding. Sieve's composite path takes one
branch to the loop increment instead of two.

The private clone's make check passes 278 of 280 (zx_web_lifecycle fails
on clone path length; packages fails on a package-resolution case outside
native code), check-bootstrap matches, and the four tier kernels return
their checksums.
2026-11-16 04:57:29 -03:00
waozi ab5f39b9f1 Drop default checks on ARMv7, SIMD gathers and plain std readers
ARMv7 native code gets the unchecked forms AArch64 has: frame words on
the arena mark, a raw resize, and no index compare for a member whose
bound marks the no-check form, so lowering no longer forces ARMv7
programs to checked pointers; default bundles pass the 72-program
parity on the Moto. Generated C checks a SIMD gather's indexes and Go
uses its _checked SIMD helpers only where checks are asked for.

The plain ReadU16LE, ReadU32LE, ReadS32LE and ReadF32LE read the bytes
at their offset at any alignment, as C does, instead of returning 0 for
a field they refuse, and GetHttps passes its URL straight to curl; the
TryRead forms and GetHttpsCapped keep the validation. The Android parity
driver builds its trap cases with --checks.
2026-11-16 04:51:27 -03:00
waozi 4fdd16d21e Write Windows x86-64 executables as PE32+ .exe files
zx2native --target x86_64 --platform windows writes a PE32+ console
executable from verified ZX with no CRT, carrying only what the program
uses, as the ELF does: a minimal MS-DOS header, .text, .rdata and, only
with writable state, .data at 512-byte file alignment; one kernel32
import table naming only what the image calls; DYNAMIC_BASE and
HIGH_ENTROPY_VA with base relocations for the pointer runtime's
addresses (an empty block when there are none); NX_COMPAT; and an 8 MiB
stack reserved and committed, so large frames need no probes.

hello.exe is 1,536 bytes. Its main loads the string's address and jumps
to the writer, which calls GetStdHandle(-11) and WriteFile with the
constant; the entry stub ends with ExitProcess. A program that prints
nothing imports only ExitProcess; resizable storage adds VirtualAlloc
and VirtualFree.

The program keeps the Ziran-internal convention. The runtime follows
Win64 only at its kernel32 calls, with shadow space, 16-byte alignment
and the volatile registers (compiler_x86_win64.zi). The console,
formatters and resize classes stay shared with Linux, and only the
primitives differ: WriteFile through GetStdHandle, ExitProcess with the
status's low byte, VirtualAlloc/VirtualFree with no mremap. A Windows
program that prints floats resets the x87 unit to the precision Linux
starts with.

The lean ELF writer's container-independent parts move into
compiler_x86_image.zi (needs, data layout, stubs, relocations, globals
and pointer runtime), which the ELF and PE writers share; the ELF keeps
its layout, and hello is still 254 bytes. The registry names each row's executable container, which
zx2native and ziran capabilities read, and --emit map describes a PE.

tests/zx_windows_parity.sh runs all 72 parity programs and a quiet one
under Wine with a private prefix and no display: each .exe prints and
exits as its Linux ELF, is reproducible, keeps W^X sections and only
in-image base relocations; hello's and the quiet program's imports are
checked exactly. CI installs Wine.
2026-11-16 04:34:54 -03:00
waozi ad3877d9c3 Record the Omega tier benchmark with checks off by default
Measured at 118ec0ff, 11 samples at load 17-22 (noisy). Native: Sieve
38.4, Records 20.1, Hash 29.1, Vectors 39.1, Calls 3.8, Printing 5.2 us;
zx engine Vectors 33.8 us (C 10.6, 8.5, 22.2, 13.3, 5.0, 4.0). Vectors
drops from 64.1 us now that elements are reached without checked
pointers.
2026-11-16 04:29:43 -03:00
waozi 118ec0ff46 Let unchecked executables fault on deep recursion as C does
With checks off by default, an AOT executable owns its process, so deep
recursion can fault on the guard page as C's does. Its functions check
the stack limit only when their frame is larger than the slack, which
could step past the guard page, and _start sets the limit only when one
does. Loaded code and --checks builds keep the check in every calling
function, since an overflow in a host process would take the host down.
MachineOptions.executable reaches MachineProgram.executable through
lowering and allocation.

An element address in the no-check form cannot trap, so it no longer
keeps a function's frame. Hello's main is now frameless: lea, xor, lea,
mov, mov and a tail jump to the write. The file is 254 bytes, with one
LOAD, and machine_elf.sh now fails above 320 bytes.

The private clone's make check passes 277 of 279 (zx_web_lifecycle fails
on clone path length; packages fails on a package-resolution case that is
not native code), and check-bootstrap matches.
2026-11-16 04:28:52 -03:00
waozi 6e3d216c68 Decide checked pointers once for lowering and the loader
Native lowering and the in-memory loader now both ask MachineChecked:
a --checks build, and every ARMv7 one until its encoder has the
unchecked forms, so the new in-process ARMv7 loader keeps its slot
table. x86-64 tail calls and frameless functions are kept out of any
function with frame-arena storage, now marked by its arena word in both
modes. The bootstrap is regenerated.
2026-11-16 04:22:49 -03:00
waozi feb984ce97 Document Ziran as manually safe with opt-in checks
The usage guide gains a Checks section: no defensive runtime check by
default, --checks for the whole build, #checks for a module, block,
statement or access, the engine always checking and Go's own checks left
to -gcflags=-B. The ZX, laws and status pages no longer describe checked
pointers as the default, and the site guide pages are regenerated. The
manual-safety plan keeps only its open work.
2026-11-16 04:17:45 -03:00
waozi 1ffc9365e4 Keep checks where #checks is written
#checks alone at the top of a module, before a block or statement, or
before one index or slice access keeps the defensive checks of those
accesses in a build without --checks. The parser marks every expression
under it, the body parser marks the statements of a #checks line or
block, and saved IR keeps the marks (ZIR format 66). ZIR lowering stamps
the element addresses, extracts and inserts it lowers there, and the
LIR codec stores the stamp per instruction behind a function flag, so
programs without #checks keep their size. Native lowering selects the
checked element and member forms for stamped instructions, Wasm keeps
their index and subview checks, and the C and Go emitters keep their
range checks.

A new local test runs each level natively, as Wasm and in C, and shows
the default ELF has no pointer resolve and the default C no index
check. The site's target matrix is regenerated for the new format.
2026-11-16 04:17:45 -03:00
waozi af1121a9ce Generate code without defensive checks unless built with --checks
Default native, Wasm, C and Go output follows manual safety like C: a
native data pointer is its address, so loads, stores, byte compares and
platform services use it directly, globals are RIP-relative addresses,
allocate takes plain frame-arena bytes and resize passes the raw block.
Element and member accesses use the unchecked operand forms, the machine
verifier's checked-memory obligation and the proven facts apply only to
--checks programs, and the native loader builds its slot table and host
token resolver only for a checked bundle. Wasm skips index, subview and
resize checks; generated C uses raw indexes, SliceRangeAt and the new
StringRangeAt; Go drops Ziran's explicit range checks. ARMv7 keeps
checked pointers until its encoder has the unchecked forms.

--checks builds today's checked program. Trap, hostile-twin and bounds
tests build with it, and new assertions show the default C build has no
index check. The bootstrap, including the macOS copy, is regenerated.
2026-11-16 04:17:45 -03:00
waozi d01ed08bfc Add the --checks build switch and record it in ZX
zi2zx, zi2c and zi2go take --checks. It marks the program and every
module checked; the LIR keeps it through the optimizer, and the LIR
codec stores it as header flag 1, so saved bundles, zx2native, zx2wasm
and the native loader know how a bundle was built. Nothing consumes the
switch yet; the default stays as it was until native code drops its
checks.
2026-11-16 04:17:28 -03:00
waozi 76b6bb454f Record the Omega tier benchmark for the lean native ELF
Measured on the step-budget, split-record, linear-verifier and lean-ELF
commits before the tail-call change, 11 samples at load 10-13. Native:
Sieve 39.7, Records 16.8, Hash 28.8, Vectors 64.1, Calls 3.9, Printing
4.4 us (C 10.9, 8.5, 22.2, 13.0, 5.0, 4.0).
2026-11-16 04:16:28 -03:00
waozi 97f5f43343 Tail-call and drop the frame of functions that need none
A direct call that its function returns at once (the next instruction
returns the call's register result or nothing, with no stack arguments
and no result in memory) leaves the frame and jumps. The callee then
returns straight to the caller, with the stack exactly as a direct call
would leave it. A function with no stack objects, no stack check or fuel
register, and only instructions that cannot trap and call nothing except
such a tail call has no frame: no push rbp, mov rbp, rsp or leave. A
function returning a constant is now `mov eax, 42; ret`, and hello's
main ends in `leave; jmp` to the write. Functions that can trap or make
other calls keep their frame, because the loader's trap and host
veneers enter C code that needs the ABI's 16-byte alignment.

The private clone's make check passes 276 of 278: zx_web_lifecycle
fails on clone path length, and packages needs the version stub already
on origin. Private parity matches the engine on all 32 programs, the
four tier kernels return their checksums, and Wurm's steering bundle
matches the engine.
2026-11-16 04:12:40 -03:00
waozi af087b47b8 Carry only what a native ELF uses, so hello is 576 bytes
The x86-64 ELF writer emits each data piece only when the image
references it: the fuel counter, trap status and stub, stack limit,
pointer runtime (header, table and arena), heap state and console buffer.
Each console routine is likewise emitted only when called. Text starts
right after the program headers and data follows it in the file, mapped
one page higher, so there is no page padding; an image with nothing
writable has a single PT_LOAD. _start sets the stack limit only when
some function checks it and ends with exit_group itself unless output is
buffered.

An executable with an unbounded budget, the default, never runs out, so
it is lowered without fuel checks (MachineOptions.fuel); zx2native --fuel
N keeps them. A function whose only calls are runtime services no longer
checks the stack, since those never call back. A program whose one
console call runs at most once (in an acyclic entry that nothing calls)
writes directly, with no buffer, terminal probe or flush at exit.

examples/hello.zi: 8,352 -> 576 bytes. The remaining bulk is the checked
resolve of its constant string, which the unchecked default removes.
machine_elf.sh fails again if hello grows past 640 bytes or carries the
bool formatter; the old size check left with the direct backend. The
native map reports the startup size and data address from the encoder.

The private clone's make check passes 275 of 278. The three failures are
zx_web_lifecycle (clone path length), packages (the package version stub
fixed on origin) and direct_assembly; direct_assembly then passed with its
map check updated for the new layout, as do all assembly, ELF, native and
parity checks. check-bootstrap matches.
2026-11-16 04:12:40 -03:00
waozi 16bd1edf6e Check native relocations in one pass instead of per instruction
Native compilation of tests/spec/unicode_conformance.zi's 28.7 MB bundle
spent nearly all of its time in scans that rescanned every relocation:
MachineVerify's FuelFacts did so per instruction and CallsAndRelocations
per call, the allocated verifier's call check per call, and the x86
image builder's ImageOperand per encoded relocation. Each is now one pass.
MachineCallReferences counts every call's symbol references, and
MachineRelocationIndex chains each instruction's relocations for the
image builder. Both verifiers check relocations before calls, so a
malformed relocation is still reported as one.

On Omega the bundle now compiles natively in 7.4 s instead of 81 s,
and the result runs and exits 0. The machine-IR, regalloc, x86, ELF and
AArch64 suites pass on HEAD plus this change. The AArch64 and ARMv7
image builders still have the same loop and are left to their owners.
2026-11-16 04:12:40 -03:00
waozi ab7fe5a521 Hold small native records in registers, one value per field
A record of up to eight scalar fields that is only built, changed and read
by constant member and passed between blocks never needs memory: the
aggregate plan marks such values split, and lowering gives each one a
virtual per field. A build takes its operands' virtuals, a constant insert
its source's with one replaced, an extract stands for its field's virtual,
and an edge copies each field, so a loop-carried header lives in registers.
Split values take no frame slot.

The machine verifiers no longer require a frame object for a stack value
that no operand or copy names; a stack operand or copy that names a value
without one is still rejected, since the allocator needs its home. The
record-swap fixture takes its records as parameters so it keeps testing
memory-to-memory cycles, and the frame-alignment check moves to the
fixture that passes a record to a call.

make check passes but for site_pages (packages/audio vorbis.zi missing)
and zstd_go (needs Go 1.25); make check-bootstrap passes. Private parity,
32 programs: native output and exit codes match the engine. The four tier
kernels return their checksums and Wurm's steering bundle matches.
2026-11-16 04:12:40 -03:00
waozi d1fabf4043 Keep a looping native function's step budget in a register
Every loop header charged fuel with sub qword [rip + fuel], 1 and a jae over
its inline trap, so each iteration took a branch only to skip the trap.

On x86-64 a function that charges fuel outside its entry block now keeps its
step budget in r15: the prologue loads it, every fuel check subtracts there,
and it is written back to the instance counter before internal and host
calls (and reloaded after), before returns and on every trap, so budgets and
trap points stay exact. A loop header's check falls through, sub r15, n; jb
to a trap that opens the header block inside the check's own range, so trap
reports keep their instruction and line; jumps enter past it and a
predecessor that would fall into the header jumps over it. The allocator
keeps r15 out of such functions and saves it; the ELF writer accepts the
budget's relocations in the prologue and at calls, returns and traps.

The allocated verifier treated a spill into stack slot 11 as parking a value
in the r11 scratch register and then rejected a correct swap; it now parks
only physical registers. The wide tail-swap fixture hits this once r15 is
reserved.

Private timing on Omega, 32 calls per process: Sieve 59.6 -> 47.1 us, Records
18.9 -> 17.5 us, Hash unchanged (C 12.2, 8.8, 22.5). The x86, AArch64,
regalloc, machine-IR and ELF suites pass on HEAD plus this change, Wurm's
steering bundle runs, and the kernels return the engine's results.
2026-11-16 04:12:27 -03:00
waozi fdcd90072b Run native ZX on ARMv7 in process and on the Moto
The loader's ARMv7 half, zir_host_native_armv7.c, writes the A32 host,
trap, resize and helper veneers, the C helpers for 64-bit divide and
int64/float conversion, and MOVW/MOVT and BL patching. The shared loader
takes __arm__, and native is the default on linux-armv7.
`make android-parity ANDROID_ARCH=armv7 ANDROID_API=28` cross-builds zi2zx
and runs the 72-program parity on the Moto e6 play: all 72 match on the
device engine, natively and from the native cache
(bench/results/zx-android-parity-moto-2026-11-16.json). The Pixel reruns
72/72.

The device runs found:
- The entry's narrow result left r1 unset; the entry now widens it.
- Frames over 4 KiB rebased through r10 while it held a live value. The
  arena mark and pointer chain now sit beside the callee saves on every
  target, a dynamic element's address moved to lr, and storing r10 to a
  slot that needs rebasing is rejected at encode time.
- Kryon's player bundle needed host calls that return records, and copies
  that do not unroll 132 KB records word by word. Both ARM encoders now
  accept record results from host calls and loop copies and zeroing of 64
  bytes or more; AArch64 also steps large displacements by 4095 << 12. The
  bundle compiles for both ARM targets and runs natively on the Moto.

NativeBlock's size check uses max_align_t, which is 8 on ARMv7.
2026-11-16 04:07:41 -03:00
waozi 572b50d000 Encode machine IR as ARMv7 A32 in register pairs
M4 row 4. cmd/compiler_armv7.zi encodes allocated machine IR for armv7a
Linux and Android. LIR values are mostly 64 bits (s64, pointers and
function values), so the ARMv7 target describes its general bank as six
register pairs, (r2n, r2n+1) and (r12, lr), and allocation, lowering and
verification run unchanged: 32-bit values use a pair's low register,
64-bit ones both, with ADDS/ADC, UMULL/MLA, register-shifted pair shifts,
CMP/CMPEQ and SUBS/SBCS compares. Floats are d0-d15 with f32 in s(2n).
Memory goes through core registers word by word, since packed records
leave fields unaligned. Addresses materialize as MOVW/MOVT halves; veneer
calls are BL with the A32 pc addend.

64-bit divide and remainder and int64<->float conversions call loader
runtime helpers through a new RuntimeHelper relocation, with operands and
result in 16 bytes at sp, so the call changes only its destination.
Fixed-form clobber lists may now end early, since six pairs cannot fill
x86's eight.

The encoder cases' builder moves to tests/machine_encoder_build.zi, shared
by the AArch64 and new armv7_encoder cases, whose expected words come from
the NDK assembler. All 72 zx_lowered_parity programs encode for ARMv7;
loading and running them on the Moto is row 5.
2026-11-16 04:06:55 -03:00
waozi f9f92b46db Release Ziran 0.5.0
ZX runs as native code by default on Linux x86-64 and AArch64, the toolchain builds on macOS again, and the website's benchmarks are fresh Alpha measurements; the changelog section lists what users get. update_version.sh set the version files and the standard-library inventory, and site_pages.py regenerated the module pages, which now mark the modules shipped in 0.5.0.
2026-11-16 03:28:16 -03:00
waozi ee68a8b268 Fix the native loader and name-cache faults the sanitizer job found
The sanitizer job had been timing out, so these were never reported.

- The native loader copied a program's code, constants and data with
  memcpy even when a section was empty and had no buffer; UBSan aborts on
  a null source, which failed 89 checks. Empty sections are now skipped.
- compiler_native_names cached kept-text pointers in a process-wide
  table, but kept text belongs to a compiler context: once that context
  closed, the next check read freed memory (bundle-link-test,
  parser_recovery, semantic_edit). Kept text is already interned per
  context, so Literal keeps the name directly. The checked bootstrap is
  regenerated.
- formatter.sh compiled its law test against build/ even under make
  sanitize; it now uses the runner's ZIRAN_LIB and VM_CFLAGS like the
  other C tests.
2026-11-16 03:28:03 -03:00
waozi 768495fcbd Make the C pruning pass linear and finish the remaining CI checks
zi2c's PruneNoteNames measured the whole generated text with strlen for
every identifier it read, so a large program spent minutes there: the
Unicode conformance fixture's C build ran past 13 minutes on Alpha and
kept the check and sanitize jobs from finishing. Measuring the end once
brings std_unicode.sh to 273 s.

package_artifacts compiles a client of cmd/package.zi on its own; the
package commands now import the version module the Makefile generates, so
the test writes one beside its client.

The engine-less ZX-to-Wasm lowering defines ZxWasmLowerProgramSuspendable
like its other entry points, so every libziran variant links zir_zx_wasm.
2026-11-16 02:13:19 -03:00
waozi 7acf793845 Regenerate the reference pages for the file-tree, timer and ZX guide changes
site_pages.py --check found std/file_tree_linux.html and std/timer_linux.html behind their Darwin doc comments and guide/zx.html behind docs/ZX.md's learning-corpus section.
2026-11-16 00:54:09 -03:00
waozi cc31776b37 Merge the macOS, CI and fresh-benchmark fixes for the 0.5.0 release
The receipts name 2b49d83b, where they were measured; the GPU emitter removal and learning-corpus filing on master do not change the measured code.
2026-11-16 00:39:48 -03:00
waozi 30dc39b17a Measure the release on Alpha: kernel tiers, comparison 2 and the widget table
All three ran on Alpha's physical host (virtualization none) at
2b49d83b with a clean tree, through bench/bench.zi with ZIRAN_LEARN=off,
one after another; each receipt records load before and after, revision
and dirty state.

- bench/results/wasm-tier-alpha-2026-11-16-release.json: C, engine,
  native and Wasm kernel tiers, 11 samples.
- bench/results/zx-compare-alpha-physical-native-2026-11-16-release.json:
  comparison 2, engine against cold and warm native ZX, AOT and C.
- site/generated/library-targets and site/targets.html: Kryon's widget
  scenarios at kryonlabs/kryon 83c24cdb with ZX run as native code (the
  removed portable VM column is gone).
2026-11-16 00:38:07 -03:00
waozi 37de4b35bf File the learning corpus by ZX format and name each record's compiler
Each recorded program now lives under zx<R>-lir<S>/, read from the
bundle's own header revision and instruction schema, so a ZX revision
bump starts a new folder instead of mixing programs the current tools
reject into the ones they read. Each machine-code record ends with a
.record.json, written last, naming the SHA-256 of zx2native and zi2zx,
the Ziran version, the source and entry and the Unix time, so compiler
upgrades can be told apart and paired. learn status lists each format.
The plan records the acceptance ladder (proven rules, learned decisions,
whole-program replay) and the missing per-opcode ZX reference.
2026-11-16 00:28:50 -03:00
waozi 0d8fb13db6 Regenerate the implementation status page without the GPU emitter 2026-11-16 00:27:39 -03:00
waozi 2b49d83b60 Build on macOS again, fix the package and playground CI jobs
macOS: the self-hosted compiler backend and its file, process and timer
modules called Linux-only libc (__errno_location, pipe2, statx,
clock_nanosleep, sched_getaffinity, Linux open flags and clock ids), and
the checked bootstrap C was generated for Linux only. std/process_run_linux,
std/file_tree_linux, std/timer_linux and cmd/compiler_backend_process gain
Darwin branches (pipe + FD_CLOEXEC, __error, fstatat with the 64-bit-inode
record, nanosleep, CLOCK_MONOTONIC 6, Darwin open flags and sysconf name),
and open/fcntl take their mode as a variadic argument as Apple's arm64 ABI
requires. Darwin's $INODE64 symbols are resolved at run time, so one seed
serves Apple Silicon and Intel. bootstrap/darwin holds the Darwin copies of
the three platform modules, generated with the Darwin defines; the Makefile
selects them on a Darwin host, passes ZIRAN_DEFINES when generating those
modules, and check-bootstrap/update-bootstrap cover them.

Package jobs: check.yml ran the deleted test_native_package.sh wrapper; it
now runs scripts/test_native_package.zi directly.

Site: the browser playground linked the deleted cmd/zi2zx/zir_asm_lower.c
and missed ZxExecBuild's debug argument; it now compiles the checked Ziran
lowering from bootstrap/compiler_zir_lower.

The widget table generator measures native ZX, the default on Linux
x86-64 and AArch64, labels the column accordingly and records host load.
2026-11-16 00:25:27 -03:00
waozi f7a0bafd91 Delete the unreachable GPU device emitter
Every target rejects a #parallel_gpu region as gpu.device before any
emitter runs, the ZX lowering fails it and zx2native reports it as a
gap, so the compute-shader lowering, the EGL/GLES device runtime and the
C emitter's dispatch and device notes never ran. The checker keeps the
GPU region rules that enforce the documented Gap. The build comment no
longer mentions TCC, and the legacy plan now holds only the planned
self-hosting replacement and the do-not-delete list.
2026-11-15 23:39:01 -03:00
waozi c97860d964 Run native ZX by default on AArch64 and record the Pixel parity
linux-aarch64, Android included, now selects native code for Auto in
the embedding API and for zi2zx run, as linux-x86_64 does; a bundle
native code cannot run fails with its named gap.

tests/zx_android_parity_cases.zi is the device runner. It bundles every
zx_lowered_parity program (the list now lives in tests/zx_parity_list.zi,
shared with zx_lowered_parity_cases.zi), runs each on this host's engine
and natively, pushes the bundles and a cross-built zi2zx through adb,
and on the device runs the engine, native code into an empty native
cache and native code from that cache, plus the trapping program with no
backend named. Each device route must print the host engine's output and
exit as the host run of its backend; native traps must name themselves.
It writes a JSON receipt.

make android-aarch64 cross-builds libziran.a and zi2zx with the NDK
(compilers that run during the build stay host binaries), and
make android-parity runs the device runner. The Pixel 4a receipt,
bench/results/zx-android-parity-pixel-2026-11-15.json, has 72 of 72
programs agreeing on every route, with 64 native cache entries stored.

The M4 plan now lists only rows 4-6 (ARMv7 and standalone executables).
2026-11-15 23:34:40 -03:00
waozi 93a15838fb Plan manual safety by default with opt-in checks
Ziran becomes manually safe like C: default output on every compiled
backend has no defensive runtime checks, and #checks or --checks turns
them on for a build, module, block or single access. The plan lists every
check site, the syntax, the ZX header flag and the stages, and records
the before benchmark on Omega. The finished trust-tier and checked-pointer
plans are folded in and deleted.
2026-11-15 23:19:46 -03:00
waozi 680b1d5e26 Delete AArch64 encoder helpers nothing calls
BitsOf, CmnOne and MaterializedWords have no caller in the encoder, the
machine lowering or the tests.
2026-11-15 23:11:15 -03:00
waozi 5953b38977 Fix the AArch64 encoder forms the Pixel found wrong
The first native AArch64 runs on a real device (Pixel 4a, Android 13)
compiled 6 of the 72 zx_lowered_parity programs correctly. Each fix was
found from the device or from disassembling the encoder's image on Omega:

- Records, arrays and vectors were given x0-x7/v0-v7 as arguments;
  only general and float values are, as on x86-64.
- Functions using v8-v15 were rejected; their low halves are now saved
  as AAPCS64 callee saves.
- A general spill stored the spill slot's number as its register.
- Fuel compared its counter instead of decrementing it.
- A value branch whose taken block falls through used CBNZ to the other
  block; it is CBZ.
- 32-bit integers widened to 64 bits without SXTW, and unsigned ones
  assumed zero upper halves that a sign-extending load does not leave.
- FMOV between 64-bit general and float registers, FCVTZU, and f64
  range checks were mis-encoded; float to integer used v15, which is
  allocatable, instead of the form's v31 scratch.
- Float greater and greater-or-equal were true for NaN.
- Byte equality never decremented its count and advanced its input
  pointers; it now walks an index in its declared clobber.
- A dynamic element address overwrote an index held in x10; it is built
  in x17.

The encoder cases pin the corrected words, and the spill case no longer
uses slot ids equal to the spilled registers, which hid that bug.
2026-11-15 23:09:16 -03:00
waozi 11f94607f8 Record the native fuel and trap-layout findings for fix 6
A register step budget alone does not speed up Sieve on Omega: the cost is
the taken jump each inline check makes over its trap sequence. A private
experiment with the budget in r15 and one out-of-line fuel stub brings Sieve
from about 52 to 41 us, close to removing fuel entirely. The plan records
how the fall-through fuel check will land without losing trap locations, the
Wurm regression the first shared-tree attempt caused, and what remains per
kernel from objdump: Sieve's direct frame store sequence, Hash's
loop-invariant address work and Records' reloads and forwarding jumps.
2026-11-15 22:53:22 -03:00
waozi 7441f9f5de Drop the finished x86 item from the legacy plan
The json-text site copies are the benchmark's published receipt, not
legacy code.
2026-11-15 22:41:46 -03:00
waozi 5d60ef90d0 Delete x86 register and condition constants nothing reads
X86Rbx, X86Rsi, X86R12, X86R13 and X86Sign have no reader in the
encoder, the machine lowering or the tests.
2026-11-15 22:40:02 -03:00
waozi 02e3478ea7 Select compares, branches and immediates like a C compiler on x86-64
Native integer code made a 0/1 value for every compare and tested it, loaded
every constant into a register first, and jumped over empty blocks. A new
planning pass, cmd/compiler_machine_select.zi, decides per LIR function:

- A constant that fits a sign-extended 32-bit field is the right operand of
  the integer compare, add, subtract, and, or, xor or multiply using it (a
  commutative constant left operand swaps places); a constant every use of
  which folds is not loaded.
- A compare whose only use is the branch after it branches on its flags.
- A jump into a block that only branches on its one parameter does that
  branch itself: straight to the chosen edge for a constant, on a compare's
  flags, or on the value. A block every edge now skips lowers as
  unreachable. This turns || and && joins into direct branches.

The x86-64 encoder takes immediate compare and arithmetic operands, elides a
jump when only lone jumps to the same target lie between, and scales 1-, 2-,
4- and 8-byte element indices in the address instead of multiplying.
MachineVerify also rejects a branch that tests neither an operand nor flags.

tests/spec/wide_compare_test.zi adds immediates at the 32-bit edges and on
s8, u8 and u32 values, folded constants, || / && chains and loop conditions,
matched on every parity route. The regalloc and machine-IR fixtures now look
for the fused branch, and keep register pressure with constants too wide to
fold.

Omega, bench/results/wasm-tier-omega-2026-11-15-scalar-select.json: native
Sieve 65.9 -> 57.8 us, Records 32.2 -> 20.1 us, Hash 38.9 -> 32.1 us. make
check (277/277) and make check-bootstrap pass.
2026-11-15 22:33:02 -03:00
waoziandClaude Opus 5.5 0c31c0b6b3 Buffer native standard output
Printing made one write syscall per fragment: a "% % %\n" line was six.
The ELF runtime now emits its console in Ziran with the x86 encoder
(cmd/compiler_x86_runtime.zi) instead of the old byte blob:

- write_all, the integer and bool formatters and the float formatter's
  writer collect standard output in an 8 KiB buffer. It is written when
  full, after each line when standard output is a terminal (one TCGETS on
  the first write, as C's stdio decides), before any write to another
  descriptor, and at exit. _start and the trap stub both end in one Exit
  routine, so output printed before a trap still arrives first.
- Every write still goes through the partial-write and EINTR retry loop; a
  failed write exits 125 without flushing again.
- Integers format by reciprocal multiplication instead of div. The float
  formatter blob loses its private write loop and calls stdout_bytes.
- A program carries only the console and float routines it calls.

tests/print.sh adds a 100-line fixture with signed extremes that must match
the engine byte for byte, take at most one write request per line under the
injected EINTR and short write (tests/native_write_all_cases.zi now counts
requests against an optional bound; the 100 lines take one), match on a
terminal, and print what came before a trap.

On Omega (bench/results/wasm-tier-omega-2026-11-15-speed-after.json, 11
samples, load 8.5/11.6) Printing goes from 41.7 to 4.5 us natively (C 3.9-4.4
us); startup-free the kernel went from 34 to 1.57 us, 2.5x faster than C,
and the bench row keeps the native process start its Calls row shows. The
zx engine is unchanged at 24-25 us: its prints already reach libc's buffered
stdout, and its cost is the generic host call per fragment in the loader.
make check passes except the known environment failures (zstd_go and
zx_web_lifecycle pass with Go 1.25 and a short path) and site_pages, stale
at HEAD for guide/zx.html; guide/architecture.html is regenerated for this
change. make check-bootstrap passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 22:16:57 -03:00
waoziandClaude Opus 5.5 95ad997f0b Grow native vectors without mapping each step
Vectors spent two thirds of its native time in the ELF's resize veneer,
which mmapped a new block, copied and munmapped the old one on every
geometric growth. The ELF runtime's resize routine is now emitted in Ziran
with the x86 encoder, in a new cmd/compiler_x86_runtime.zi, and replaces the
resize part of the old byte blob:

- Blocks carry a 32-byte header (total, free-list link, count, element
  size). Totals up to 1 MiB are power-of-two classes carved from 2 MiB
  chunks and recycled through one free list per class, so steady growth and
  freeing stay out of the kernel; a block that keeps its class stays put.
  Larger blocks are their own mappings and grow or shrink with mremap.
- Bytes past the kept elements still read zero (New(T) relies on it): chunk
  and mapping bytes are fresh, recycled ones are cleared. A refused request
  leaves the old block live, and Resize/ResizeSlots still retire the old
  token on every success, so stale aliases trap even when the address stays.
- The ELF carries the routine only when the program resizes; its state lives
  after the frame arena.

Every PointerResolve also drops its slot bound check, which guarded nothing:
the ELF and the in-process loader map all MachinePointerCapacity + 1 entries
and CreateSlot never makes the last one live. Version, liveness and
writability are now one xor and test. The zx engine runs the same code.

tests/spec/zx_lowered_resize.zi (ZX parity: C, interpreter, native, Wasm)
adds rounds of growth, shrinking, regrowth and freeing that reuse each
other's blocks, New after a freed dirty block of its class, and a vector
past 1 MiB that remaps and regrows; tests/machine_elf.sh adds an ELF whose
stale element pointer must trap after another vector reuses its block.

On Omega (bench/results/wasm-tier-omega-2026-11-15-speed-before.json and
-speed-vectors.json, 11 samples, load 8.9/12.0 and 8.8/11.7) Vectors goes
from 379.9 to 69.3 us natively and from 81.4 to 64.5 us on the zx engine
(C 13.1-13.7 us, Wasm 27.7-28.6 us); startup-free the kernel went from 353
to 58 us. The 1.5x C target is not met: the push and sum loops still resolve
every element and materialize each compare, see the plan's status section.
make check passes except the known environment failures (zstd_go and
zx_web_lifecycle pass with Go 1.25 and a short path) and site_pages, which
fails at HEAD too; make check-bootstrap passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 22:16:57 -03:00
waozi f00a8d5b49 Write a closed C program's entry as C's main itself
A program linked with --entry and built with --exe, or with its own
exported main, no longer gets a separate ziran_exe_main.c that calls
<module>_main. zi2c writes the entry's body as int main(void), or as
int main(int argc, char **argv) when the body uses its parameters: an s32
count is main's own parameter, other types the body reads are copied from
main's, and an entry with no result returns 0. hello's C is now one
int main in hello.c with no header.

The entry keeps its own name and the wrapper when other code calls it or
takes it as a value (ProgramUsesFunction in zir_link.c), when it is
exported under another symbol, when it carries assembly or #target
clones, in library builds and with --no-main, which now does what it
says. tests/native_entry_cases.zi checks hello's C against a fixture and
builds every native entry fixture as a closed program.

Also regenerates site/guide/zx.html, which docs/ZX.md had left stale.
2026-11-15 22:09:54 -03:00
waozi 436d73cf3a Regenerate the bootstrap without the TinyCC guard
The checked-arithmetic helpers every generated module carries no longer
test __TINYC__.
2026-11-15 21:56:20 -03:00
waozi 8022b2326b Link Android tools with a build ID through one flag variable
The NDK links no GNU build ID unless asked, and the native code cache
keys its entries by it, so Android binaries stored nothing. The flag
lives in ANDROID_LINK_FLAGS: written inline, the comma in -Wl, ended the
$(if) and gave Linux links a bare --build-id=sha1.
2026-11-15 21:56:09 -03:00
waozi a6cbf5b6d8 Reduce the legacy plan to open work and name the engine in the guides
The legacy-removal plan keeps only the deletions still blocked on other
lanes' open files (the unreachable GPU emitter, three AArch64 helpers,
five x86 constants, a Makefile comment, generated site copies), the
planned self-hosting C replacement and the do-not-delete list. The
tool-names, native players and self-hosting plans drop their finished
deletion items. The usage and owned-values guides call the portable tier
the engine, not the VM.
2026-11-15 21:40:21 -03:00
waozi fe535abdf5 Keep the benchmark entry check non-executable like the other test scripts 2026-11-15 21:40:15 -03:00
waozi 12c78dda4b Remove every TinyCC path from generated C
TinyCC left with the native engine's ziran run tier; no build, test or
consumer compiles generated C with it. The SIMD generator drops its
TinyCC macro bodies and SSE2 assembly macros, ziran_simd.h, the bounds,
Vec and slice headers and the emitted checked-arithmetic helpers drop
their __TINYC__ branches, and #asm no longer writes TinyCC variants,
cpuid probes or volatile selection caches. Other compilers keep the
plain lane-array and portable-body fallbacks. The SIMD tests stop
compiling with -D__TINYC__ and check helper segments by their real
spelling.
2026-11-15 21:39:22 -03:00
waozi d29b58d75b Record by default and run every benchmark through one entry point
ziran learn is now on by default: a native ziran build records each new
program once, silently (a failed record leaves a note that
`ziran learn status` shows), and `ziran learn off` or ZIRAN_LEARN=off
stop it.

bench/bench.zi is the one entry point for Ziran's benchmarks: `list`,
`NAME [ARGS]`, `--local NAME` for measurement-free modes, and `check`.
Every driver runs without display or desktop-session variables or
ZIRAN_PROFILE and with ZIRAN_LEARN=off, so benchmarks never record. Host
benchmarks refuse to measure anywhere but the physical ZIRAN_BENCH_HOST
(alpha by default). tests/bench_entry.sh fails while a driver in bench/ is
not registered. bench/README.md uses the entry point for every command.
2026-11-15 21:39:07 -03:00
waozi c9b088cb30 Delete dead compiler C and the native engine's run guards
Nothing called FunctionReturnsOnEveryPath, ProgramDump, bound_constant,
owned_initializer_shape or poly_range. ProgramMeasurePortable and
ProgramWritePortable were the last writers of semantic-IR bundles, so the
serializer's portable mode goes with them. EmitRunGuards was never
enabled after the native engine left, so the C emitter's ZIR_ENTER,
ZIR_BUDGET, ZIR_STEP, ZIR_UNREACHABLE and ZIR_GLOBAL branches and the
loop-iteration counter that fed them are gone.
2026-11-15 21:20:36 -03:00
waozi 98f22ce6f8 Delete unreferenced compiler procedures
Nothing in Ziran, its C hosts, Kryon or the packages calls these: the
ARM unsigned-field helper and its range test, three process-runner
helpers, six LIR slice and push helpers and a source-type lookup in the
ZIR lowering, and the native cache's hit-or-miss wrapper around the
checked decoder. The generated bootstrap matches.
2026-11-15 21:19:37 -03:00
waozi 6fc175170f Delete test sources whose runners are gone
Six C test programs and three Ziran case files lost their runners in an
earlier pruning and nothing builds, runs or imports them. The engine
benchmark's usage line names zi2zx instead of the removed zi2asm.
2026-11-15 21:19:04 -03:00
waozi b5958c162b Add an opt-in learning corpus for native builds
`ziran learn on|off|status` records the programs this machine builds to
native code, as training data for improving Ziran's machine code. It is
off by default; while off a build reads one small settings file. With it
on, each new native `ziran build` keeps its verified .zx, ELF,
`zx2native --emit map` JSON and LIR once, named by SHA-256, under
$XDG_DATA_HOME/ziran/learn. A rebuild writes nothing, a compiler that
emits different code adds a second ELF beside the first, and the corpus
stops growing at its cap (--limit-mb, 1024 MB by default).
ZIRAN_LEARN=on|off overrides the switch and ZIRAN_LEARN_DIR moves it.

plans/2026-11-15-learning-compiler.md records the next steps: wider
recording, instruction-window search, a cost model and Alpha's GPU.
2026-11-15 20:58:33 -03:00
waozi de2e9f1a0d Split the native loader by architecture and add AArch64 veneers
zir_host_native.c is now target-neutral: it compiles, caches, maps and
relocates images and bridges host calls through NativeAbiFrame.
zir_host_native_arch.h names what each architecture supplies, and
zir_host_native_x86_64.c (the existing SysV veneers and rel32 patching,
byte for byte) and zir_host_native_aarch64.c implement it.

On linux-aarch64, Android included, the AAPCS64 host veneer saves x0-x7,
q0-q7, x8 and the stack argument base into the same frame, the trap
veneer passes w0 and the return address, and the resize veneer keeps
q0-q31. Width-2 relocations write one MOVZ/MOVK halfword and width-4
ones a BL displacement. Code is published RX after the instruction-cache
flush, and HWCAP/HWCAP2 key the code cache. --backend native selects it;
Auto stays on the engine there until device parity is recorded.

Inherited from the native compiler lane: the AArch64 sf bit is set for
pointer and function values, the allocator's clobber check allows the
caller-saved x16/x17 that are also reserved, GEN_ZI2C lets a cross build
generate C with a host zi2c, and Android links -llog.
2026-11-15 20:41:38 -03:00
waoziandClaude Opus 5.5 25cf857cfa Drop finished plans and stale benchmark and milestone text
plans/2026-11-15-assembly-remaining.md now lists only open work (M4-M6,
native code quality, self-hosting S5-S18, legacy R1/R3/N5, deferred
metaprogramming, language gaps, Go 1.25); its finished integration and
in-flight sections are gone. plans/2026-11-15-jai-lessons.md is removed:
std/temp, module parameters, std/context and #insert landed, step 3 was
dropped, and its deferred items moved to the remaining plan.

ASSEMBLY/milestones.md no longer says M2 is open or that native speedup
waits on M2/M3, and drops the superseded portable-engine paragraph.
bench/zx_compare.md points its intro at comparison 2, replaces the
Reproduce steps for the deleted Alpha transport with the current driver,
and removes the stale validation status and the superseded intermediate
2026-11-13 cohort section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 20:36:20 -03:00
waoziandClaude Opus 5.5 ad6b02c83e Record the Alpha kernel tier receipt after the native Records fix
bench/wasm_tier.py --samples 11 on Alpha's physical host (i7-8700,
virtualization none) at 77a7ef04 with a clean compiler tree, load 8.22
before / 7.81 after. Every kernel's output is verified. Native Records
falls from 4068.9 us in wasm-tier-alpha-2026-11-15-proven.json to
61.1 us (C 13.0, engine 83.6, Wasm 29.9).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 20:27:55 -03:00
waoziandClaude Opus 5.5 77a7ef0459 Record the Omega comparison-2 cohort and publish the std/temp and std/context pages
bench/results/zx-compare-omega-native-2026-11-15.json runs the
comparison-2 driver on Omega from a clean clone of 699eb20c (Ryzen 9
9950X, load 17.67 before / 15.96 after, I/O pressure above 70%). All 72
samples pass the oracle, backend, 1.5x IQR and M0 byte-identity checks.
Warm native ZX: 0.0240 ms scalar / 0.0198 ms structured per entry,
7.8x / 20.4x faster than the engine, 6.3x / 4.5x slower than C. It is
a second-machine view, not comparable with the Alpha M0 TinyCC rows;
bench/zx_compare.md says so in its Omega subsection.

The site pages regenerated for std/temp and std/context (module counts,
modules table, usage guide sections, sitemap and the two std pages) are
committed; tests/site_pages.sh passes on them at 699eb20c.

CHANGELOG keeps the reordered native direct-access entry, restores the
dropped shared LIR optimizer entry, and notes comparison 2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 20:23:51 -03:00
waoziandClaude Opus 5.5 699eb20c69 Close M3 with interim comparison 2 on Alpha's physical host
bench/results/zx-compare-alpha-physical-native-2026-11-15.json is the
comparison-2 receipt from bench/zx_compare.zi, measured directly on Alpha
(hostname alpha, machine ID 56391af3..., virtualization none, i7-8700,
load 4.34 before / 3.83 after) in its own checkout at 31d291f3. All 72
samples completed; every engine, native and C checksum matches the
oracle, native rows report NativeX86_64, both AOT ELFs print the oracle
value, the 1.5x IQR summaries recompute, and the M0 old VM/TinyCC rows
are byte-identical to the 2026-11-12 receipt.

Warm native ZX medians are 0.0483 ms scalar / 0.0633 ms structured per
entry: 11.1x / 16.1x faster than the portable engine, 2.82x / 1.48x
slower than the M0 TinyCC tier (0.0171 / 0.0427 ms), about 10x slower
than the C control (0.0046 / 0.0063 ms).

bench/zx_compare.md gains the Interim comparison 2 section,
ASSEMBLY/milestones.md marks M3 done and cites it, and the finished M3
cutover plan is removed (every step, including the disk cache, landed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 20:18:14 -03:00
waozi 31d291f337 Keep native records and arrays in place
Records spent all its time copying: every member update copied the whole
2048-byte array word by word, extracts copied each 32-byte record out and
loop edges copied the array again. The native backend now plans aggregate
storage the way zx2wasm does, in a new cmd/compiler_machine_aggregate.zi:

- Aggregate values whose lifetimes never overlap share one frame object, so
  an insert whose source dies there writes only its member, and loop-carried
  and branch-joined values reuse their arguments' object with no edge copy.
- On x86-64 an extract read only by extracts in its block is a view: its
  members are read and changed in place through one address register
  (StackAddress, then FieldAddress or ElementAddress), shared with a
  dominating view of the same storage and member. A changed view put back
  where it came from emits nothing. AggregateExtract/AggregateInsert take
  that register as their aggregate operand.
- Dynamic indices carry the shared facts' proven bound and skip their check;
  others are checked once per address.
- Copies and zeroing of 64 bytes or more run a 16-byte movups loop with a new
  indexed x86 operand instead of unrolled 8-byte pairs.

Per the owner, speed comes first and only correctness guardrails stay: no
new verifier obligations; the remaining checks are unproven index bounds,
interference before sharing a slot, and the view write/read windows. The
allocator's aggregate cycle temporaries now have the aggregate's own size,
which 8-byte record swaps needed once coalescing made such cycles common.

tests/spec/zx_lowered_aggregates.zi joins the ZX parity suite: the Records
kernel (68788), a whole-array snapshot after insert, a two-array swap cycle,
in-place branch updates, a record parameter changed in place, loop-carried
and edge-carried records, a small-record swap at a join and scalar stores at
runtime indices, matched against C, the interpreter, native and Wasm.

On Omega (receipts in bench/results/*records-before/after.json) Records goes
from 1951 to 32 us natively and 1858 to 29 us on the zx engine (C 8.7 us,
Wasm 17.0 us); its image shrinks from 69,760 to 12,416 bytes and Sieve's
from 94,336 to 8,320. make check (276/276) and make check-bootstrap pass.
2026-11-15 19:40:16 -03:00
waozi c0efdfd534 Keep only the runtime helpers a closed program calls
The small runtime headers (zir_bounds.h, zir_slice.h, zir_string.h,
zir_vec.h) are split into helper segments by /*@Name*/ marks, the
convention ziran_simd_ops.h already uses; a helper's mark also lists the
helpers that call it. EmitRuntimeHeaders takes the names a closed
program's generated files spell and writes only the segments they name.
Other programs keep every helper, and the marks never reach generated
output.

Kryon's window headers go from 8524 to 6628 bytes: zir_bounds.h drops
EmptyArrayIndex and zir_slice.h drops the range helpers.
2026-11-15 18:59:55 -03:00
waoziandClaude Opus 5.5 e9a0418423 Record the Alpha wasm tier receipt after proven-check elision
bench/wasm_tier.py on Alpha from a clean clone at 78758062, the same
host and harness as wasm-tier-alpha-2026-11-15-native.json. The Hash
and Sieve native images carry no pointer resolve sequences (objdump
finds no `shr 0x2c`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 18:53:16 -03:00
waoziandClaude Opus 5.5 787580628b Drop proven native index checks and read constant text directly
Following the owner's "make sure we oly have guardarils wher ew enede
tehm": a shared fact now carries a pointer's room (the bytes from it to
its root's end that every execution may reach), so a constant text read
through its view is direct too, and x86-64 drops the index check of an
element the shared intervals prove below its bound (ElementAddress with
an immediate bound). Wasm drops proven view checks as well. The machine
verifier proves every PointerDirect where it is defined by walking from
the root down with the same room arithmetic. A checked constant index
past its bound stays a run-time trap instead of a verifier refusal.

On the bench kernels Sieve and Hash now carry no pointer or index
checks. Runtime indices that can leave an array or a view keep their
checks and still trap (tests/proven_pointer_cases.zi).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 18:43:47 -03:00
waozi 7ac6643d04 Enforce named trust-boundary validation 2026-11-15 18:27:45 -03:00
waozi db0bae5077 Keep only the C a closed program uses in its headers
A program linked with --entry that builds with --exe or has its own C
main is closed: only its generated files include its module headers.
zi2c now marks each header declaration as a chunk and keeps it only when
another generated file, or another kept header chunk, names it. The
module's own .c takes the declarations only it reads, inline copies stay
only for procedures another module calls, includes follow what the kept
text names, and a header that would declare nothing is not written.
Library builds keep each header's whole interface for their C hosts, and
separately lowered modules are unchanged byte for byte.

Kryon examples, headers before -> after: window 13/18171 -> 11/8524,
hello 71/288004 -> 67/90997, box 74/319181 -> 70/102271, image
107/691846 -> 103/419574 bytes; executables are unchanged.
2026-11-15 18:22:31 -03:00
waoziandClaude Opus 5.5 8f0bd37614 Elide proven native pointer checks and share index proofs with Wasm
Trust-tier steps 0-2 (plans/2026-11-15-trust-tiers.md). One LIR pass,
cmd/compiler_lowered_proven.zi, finds each pointer's root (a global, or an
allocate in the same function) and the fixed-array indices an interval
analysis proves in range. x86-64 lowering reaches a rooted load, store or
zero through PointerDirect (the root's raw start plus the token's offset)
instead of PointerResolve. MachineVerify now checks every memory access:
its address must be a resolve, fresh arena storage or a PointerDirect it
re-derives to the same root. zx2wasm reads its index proofs from the same
pass and drops its private copy (byte-identical modules on the bench
kernels). A LIR zero is resolved like a store instead of writing through
the raw token.

tests/proven_pointer_cases.zi prints per-fixture counts from the machine
pipeline and holds the hostile twins: a runtime index past a frame array,
a resized heap block and a stale frame alias still trap, and the verifier
refuses tampered direct proofs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 18:07:58 -03:00
waozi a86e6da41f Keep binary readers compatible with checked variants 2026-11-15 17:58:57 -03:00
waozi e813c84737 Document native speed profiling and ranked fixes 2026-11-15 17:42:32 -03:00
waozi c6bf5cbf5d Record the wasm tier receipt on current master for Omega 2026-11-15 17:31:00 -03:00
waozi a95fef8c10 Add the comparison-2 ZX runtime driver with an Omega receipt
bench/zx_compare.zi records one synchronized comparison-2 receipt: portable engine, cold and warm native ZX, the zx2native AOT ELF control and the C control over identical workloads, with per-trial oracle checksums, explicit backend evidence, machine and load attestation, prepare-step records, source and library hashes, and the copied M0 TinyCC summary. The C helper now selects its backend explicitly instead of platform auto, so a cohort can never silently change backends, and reports the realized backend with the native evidence flag in every row. bench/README.md documents the invocation.

The receipt bench/results/zx-compare-omega-2026-11-15.json holds 9 trials per kind on omega under load 16.3-20.7: engine 0.201/0.462 ms, native cold 0.346/0.459 ms, native warm 0.0234/0.0921 ms, C control 0.0039/0.0046 ms, zx2native AOT 0.508/0.653 ms per run, integrity verified. build-queue -- sh tests/site_targets.sh build/bin/ziran passes on the live tree.
2026-11-15 16:45:32 -03:00
waoziandClaude Opus 5.5 f44e5afa81 Emit only the code a program reaches; drop the one-C-file step
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:42:18 -03:00
waoziandClaude Opus 5.5 73b77bd817 Port checked memory and stack checks to the AArch64 encoder
PointerResolve, ArenaAllocate, PointerCreate, the pointer frame chain,
slot-aware Resize and the calling-function stack-limit check now encode
for AArch64 with StackLimit and PointerRuntime halfword relocations, and
the image publishes stack_limit_offset and pointer_offset like x86-64.

TrapUnless now branches past the trap sequence instead of onto its BRK,
and TrapSequence materializes the high half of the trap code, so the
pointer trap and user trap codes keep their values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:35:08 -03:00
waoziandClaude Opus 5.5 f0c9a610b8 Record the AArch64 checked-memory port design for M4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:07:24 -03:00
waoziandClaude Opus 5.5 b2ce9761ac Plan M4 native ZX on the Moto and Pixel devices
Records the two ARM test devices, what the AArch64 encoder, the native
loader and the ELF writer lack after M3, and the order of the M4 rows:
AArch64 checked memory, the AArch64 loader, the Android build and device
runner, the ARMv7 encoder and the Moto row, then standalone ARM ELFs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:03:24 -03:00
waoziandClaude Opus 5.5 b4e3fccd55 Prove native pointer types are guaranteed by the load-time verifier
M3 step 2 asked native code to re-check a pointer's element type on every
access, as the engine does. The verifier already makes a wrong-type access
unrepresentable. LIR has no pointer casts, since Convert and Bitcast are
numeric only. Field, element and view addresses, loads, stores and platform
pointers are typed against the pointee. Every reader verifies the program
it decodes before native code is built. So the step closes on that
guarantee rather than on a runtime check, and a test enforces it.

verified_loading_cases.zi builds a bundle from source, retypes one integer
load to another width, and encodes and frames it without verification, as
any producer could, with the new LirWriteUnverified and ZxExecFrame. It
checks that the reader returns Verify, that zi2zx run and zx2native refuse
the file with a verifier diagnostic before any native code exists, and that
a source pointer cast never reaches ZX. The M3 plan, the milestones and the
trust-tiers plan record the decision. The engine's own element-type check
stays; it is a candidate for trust-tier elision.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:00:22 -03:00
waozi 7910e60542 Splice compile-time source into a module with #insert
`#insert NAME;` at file scope splices the text of a compile-time string
constant into the module where it stands: a literal, a #string body or
the result of `#run` on a pure procedure. The text is checked like the
rest of the file and shares its scope and #scope_file privacy, so a
compile-time procedure can write declarations generics cannot express.

Inserts are evaluated after discovery, under the #run rules and budget,
and their declarations are discovered before the file is parsed. Code
anywhere in the module can use them, including #if conditions and #run
calls above the #insert. The parser reads each insert as an in-memory
load frame. Every line of it keeps the #insert's line, so diagnostics
name the insertion site, and line numbers after the splice stay true.

A value that is not a compile-time string, #insert inside a procedure
body or an #if block, an insert in inserted text, and a misspelled
directive are rejected. The grammar lives in compiler_declaration.zi.
Saved IR holds only checked declarations, so no backend changes.

tests/insert_source_cases.zi builds a program whose Square, Cube and
helpers come from #insert. It runs from source and saved IR on C, Go,
the engine, native code and Wasm, with nine rejections.
2026-11-15 16:00:17 -03:00
waozi 68477abbf0 Record the wasm tier receipt on the Alpha physical host
Clean origin/master clone under the coordinators authorized work directory, built and measured on Alpha (idle-ish, loadavg 6.6-8.5 of 12 threads); all four runtimes oracle-checked per kernel; 11 samples, 1.5xIQR medians.
2026-11-15 15:58:08 -03:00
waozi 68a0737e70 Add explicit scoped context 2026-11-15 15:53:25 -03:00
waozi c1e3f08505 Record the wasm tier receipt for the native default on Omega
build-queue -- python3 bench/wasm_tier.py --samples 11 against the live 65-format toolchain; medians follow the 1.5xIQR rule; loadavg before and after recorded (Omega was heavily loaded, 21-25 run queue).
2026-11-15 15:50:51 -03:00
waozi 65cd4c7e1e Add checked temporary storage 2026-11-15 15:45:19 -03:00
waoziandClaude Opus 5.5 94355db42d Keep whole host import names when lowering to LIR
The Ziran assembly lowering copied a host import's name and result type
with size_of(*import.name) and size_of(*import.return_type): the size of
a pointer, not of the 128-byte name arrays. Only eight bytes survived, so
a host function returning a record whose type name is longer than that,
such as std/process's StartHost -> ProcessStart or Kryon's
ReadBundleInput -> BundleInput, failed with "this type has no portable
lowered representation yet". The copy now takes both whole arrays, and
the bootstrap C is regenerated. host_bindings bundles a host function
that returns a long-named record.

SayTarget became the only emitter of assembly.lower when the lowering moved
to Ziran, so explain's independent code scan now includes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 15:41:02 -03:00
waozi 285b51e2e2 Choose a module's compile-time features where it is imported
A module declares parameters as its first declaration,
`#module_parameters(STB := false, CACHE: s32 = 8)`, and an import picks
their values, `#import "fonts"(STB = true)`. Each parameter is an
ordinary constant of the module, so `#if` keeps unchosen code out of C,
Go, ZX, Wasm and native code alike.

One program binds a module's parameters once. Every import has to give
every parameter the same value, so disagreeing imports fail with
module.parameter_conflict instead of compiling a second copy. Unknown
names and values that do not fit their type (integers by range) fail
with module.parameter_unknown and module.parameter_type at the import.
The grammar and literal rules live in compiler_declaration.zi. The
bindings are checked IR, ZirModule.parameters and ZirImport.parameters,
so they port with the checker to Ziran.

Saved .zir becomes version 65. It keeps each import's canonical list and
each module's types, defaults and bound values. A saved import that
disagrees with its module is rejected like source, and so is a bound
value that differs from the module's constant. The unused reserved
import slot is gone.

Also: a constant whose string holds `#import`, such as module source in
#string, is no longer parsed as an import. The C include path now lists
the IR headers first, so a stale copy that another generated module
keeps can't shadow them in an incremental build.

tests/module_parameters_cases.zi runs two programs that share one module
with different choices. They run from source and saved IR on C, Go, the
engine, native code and Wasm, along with the named rejections and edited
saved IR. Grammar cases are in tests/spec/compiler_declaration_test.zi.
2026-11-15 15:40:12 -03:00
waozi e76ebae7ae Refresh the site target matrix on the live toolchain
Regenerated with scripts/site_targets.py on the active shared tree: checked IR cells serialize with the in-tree format (65) ahead of the module-parameters landing; zx, native and WebAssembly artifacts rebuilt byte-identical; per-cell timings re-measured (5 samples), desktop platform snapshot carried as the generator designs. build-queue -- sh tests/site_targets.sh build/bin/ziran passes.
2026-11-15 15:37:32 -03:00
waoziandClaude Opus 5.5 0ecdc85601 Plan trust tiers for compiler checks and input validation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 15:31:04 -03:00
waoziandClaude Opus 5.5 40212fc992 Cache compiled native code on disk across runs
The native loader compiled every bundle once per process. It now keeps the
compiled image in $XDG_CACHE_HOME/ziran/native (or ~/.cache/ziran/native),
so a later run in another process maps it instead of compiling again.

cmd/compiler_native_cache.zi frames an image with its key (format, image
version, runtime ABI, target, CPU features, the GNU build ID of the object
holding the compiler, and the bundle's content digest), the payload
length and a SHA-256 of the payload. Decoding refuses any entry whose key,
length or digest differs, then runs MachineImageValidate. The loader writes
a private temporary file, syncs it and renames it over the entry. It removes
a damaged entry and compiles again, keeps at most 64 entries and 512 MiB,
and clears temporary files writers abandoned. Code read from disk has no
machine program, so a trap compiles once to name its site.
ZIRAN_NATIVE_CACHE=DIR moves the cache and ZIRAN_NATIVE_CACHE=off turns it
off.

native_disk_cache_cases.zi, run from the check plan, covers the cold store,
the warm hit, an abandoned writer, flipped and truncated entries refused and
replaced, the off switch, trap sites from cached code and four racing cold
runs, all matching the engine's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 15:15:43 -03:00
waoziandClaude Opus 5.5 93a54f08db Expect five optimizer passes and record the full-suite receipt
The optimizer now reports common-subexpression elimination as a fifth
pass, so the direct-assembly check expects five counters and requires each
to have run. With that, a clean clone of master passes make check-bootstrap
and 265 of 266 checks on Omega; only zstd_go fails, because it needs
Go 1.25. ASSEMBLY/milestones.md records the result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 15:07:27 -03:00
waozi b1089b207c Remove the legacy assembly lowering C sources
No build rule references zir_asm_lower.c/.h after the compiler_zir_lower port, so the hand-written copies are deleted.
2026-11-15 14:45:57 -03:00
waozi a7bb3c27b0 Port the assembly lowering to Ziran
compiler_zir_lower.zi replaces cmd/zi2zx/zir_asm_lower.c with the generated module: zi2zx and zx2native call the generated ABI through zx_exec_run, assembly.mk builds the module into the assembly pipeline, and the zi2zx link drops the hand-written lowerer. The checked-in bootstrap/compiler_zir_lower and bootstrap/compiler_lowered_ir verify against check-bootstrap, and the self-hosting plan records the step.
2026-11-15 14:45:57 -03:00
waoziandClaude Opus 5.5 0e6e37935f Record the installed tool check for the native default
Installed from the Omega working tree with make install-user and checked
the installed tools: the examples run from source, ziran bundle writes
revision-28 ZX, zi2zx --emit lir and zx2native --emit map inspect it, and
ziran run app.zx executes it as native code. A bounds trap reports
"native execution failed" where --backend engine reports "portable
execution failed", and its zx2native ELF exits with 125.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:45:27 -03:00
waoziandClaude Opus 5.5 6f69f0176b Pass the AArch64 record-result address in x8, after the arguments
An internal call that returns a record passed the hidden result address
in x0, which also carries the first integer argument, so the callee
stored its argument as the address. The address now passes in x8, the
AAPCS64 indirect-result register, and is computed only after every
argument is placed. An indirect call's target is pinned to x9, as x86-64
pins it to r10, so neither the result address nor the stack-argument
scratch can overwrite it. aarch64_encoder checks the call computes x8
just before bl, keeps its x0 argument, and that the callee stores x8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:43:29 -03:00
waozi 74e5d8f30b Speed verified ZX with optimized shared LIR and safer Wasm checks
The optimizer adds block-scoped common-subexpression elimination, folds
constant text calls through published ASCII definitions, tracks scratch
allocations to their precise peaks, and cleans only proven-dead code and
unreachable blocks. Wasm lowering uses closed signed ranges to remove bounds
checks only when the index cannot leave the object. Optimization reports name
the CSE pass, and the tier benchmark measures the native leg now that its
native heap-storage gap is implemented.
2026-11-15 14:42:18 -03:00
waozi 8e812f5da1 Add the measured native column to the site target matrix 2026-11-15 14:39:20 -03:00
waoziandClaude Opus 5.5 9436b8a7f5 Mark M1 and M2 done; add the M3 cutover and Jai lessons plans
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:28:24 -03:00
waoziandClaude Opus 5.5 eb42c5fb9d Run the trapping parity fixture through native code, fix token docs
zx_lowered_parity returned right after the interpreter for the
std_string_bad trap fixture, so it never reached native code. It now also
requires the bundle to trap natively and the zx2native ELF to exit with
the interpreter's trap status, so all 71 parity programs run as native
bundles and ELFs.

The ASSEMBLY notes still described native pointer and procedure tokens as a
linear scan. A pointer token carries its slot, version and offset and is
checked in constant time, and a procedure value is a code address called
through a register.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:11:46 -03:00
waozi 38f133cd31 Let Go module initializers store procedures that call a host later
A feature module registers itself by storing a procedure from its module
initializer. When that procedure calls a host capability, the Go startup
check refused the program, because uses_host also counts procedures that
are only referenced. Go binds the host interface after package
initialization, so only a call made while an initializer runs needs the
host. The check now follows calls from each initializer, and
tests/module_registration.sh covers both cases.
2026-11-15 14:05:40 -03:00
waoziandClaude Opus 5.5 931fed4c86 Run ZX natively by default and integrate the finished assembly lanes
One commit, because the parts below only build together.

Allocator: an interval needed at the current instruction is never
evicted, and the allocated-program verifier checks that every operand sits
where the allocation says.

AArch64 encoder: compiler_aarch64.zi encodes allocated machine IR with the
shared ARM byte helpers, maps the function-address relocation,
sign-extends signed 8- and 16-bit loads and rejects what it cannot encode
with a named diagnostic. It has no AOT ELF writer yet.

Native default with checked pointers and no fallback: on linux-x86_64,
`ziran run app.zx`, `zi2zx run`, the embedding API's Auto and the Kryon
players run a bundle's verified program as native code in W^X memory.
Stray and freed pointers, double free, bounds and read-only stores trap. A
native gap is a named preflight error, nothing falls back to the engine,
and `--backend engine` picks it explicitly. zx2native uses the same
preflight. Native code exchanges module state for hot reload, checks the
stack, zeroes fresh locals, spends fuel at the engine's checkpoints and
returns records, arrays and strings from host calls. `zi2zx --debug` source
origins name lines in native traps and `zx2native --emit map`. The host
value API drops its VM prefix (HostValue, HOST_*). A call with a record
result loads the hidden result address into rax only after its stack
arguments are stored, and an indirect target stays in r10: rax could hold
a stack argument (Kryon's text-field clip guard arrived as an address) or
the target (indirect calls returning records crashed).

Self-hosting ports: compiler_backend_process, compiler_backend_cache,
compiler_native_names and compiler_runtime_emit replace the zir_c_build,
zir_c_cache and zir_c_process C, with checked bootstrap C and Makefile
rules. zir_c.toolchain again reports "compiling OUT failed:" with the head
of the compiler output and a truncation marker. The parallel scheduler no
longer stalls on a held compiler after reaping a finished job, and poll or
read errors now fail the build. A fresh BUILD_DIR (Kryon's runtime build)
builds: generated files have pattern rules, objects wait for the headers
they include, and engine flags are per object instead of leaking into zi2c.

Legacy removals F1-F10 and N1-N4: the duplicate LirX64 encoder and its
spec test, zir_c_*, zir_runtime and zir_native, nine zero-reference spec
tests, vec_capacity, the zx_metadata and native_cache_names benchmarks,
build-android-host.sh and two shell wrappers are deleted; zx2native is
machine-only; `zi2zx` rejects `--opt` on ZX input; the bootstrap is
regenerated. ASSEMBLY docs, the legacy-removal plan, the milestones and the
remaining-work plan record the current position.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:04:48 -03:00
waozi 943c1a5bfc Run bundles on the engine in web runtimes without the Wasm tier
A 64-bit web runtime such as the playground's, and a JSPI one, install no
wasm provider. Since Auto always chose the Wasm tier under Emscripten,
they could open no instance: every playground program stopped with
status 2 and no diagnostic. Auto again takes the Wasm tier only when a
provider is installed, and the instruction engine otherwise.
2026-11-15 11:22:09 -03:00
waozi eb05cf68e4 Build the native host object without GNU Make 3.82 features
macOS ships GNU Make 3.81, which has no `private` modifier: it read the
word as a prerequisite and stopped with "No rule to make target
`private'". The assembly include for zir_host_native.o is now a variable
named after that object, which the object rule adds to its own compile
only, so the prerequisites make builds for it (zi2c among them) still
never see the generated assembly headers.
2026-11-15 10:56:46 -03:00
waozi fe3624fa97 Speed up ZX engine runs, derived addresses and console output
A derivation that makes a table entry remembers the token it made and the
operand words it made it from. While that token is still a live entry it
is the one the table lookup would find, so a repeated derivation skips the
lookup. Console output gathers in the instance and reaches stdio in one
write at the end of a run, before any other host call, before a write to
standard error and when the instance closes; a terminal still gets every
write at once, and a run that succeeds no longer flushes stdout.

The entry's return of a word or of nothing runs in the fast loop, a run
checks host bindings once, and LirExecRunEntry runs the entry again
without building a result. Platform writes from the fast loop check that
the binding is a write and report a failing host at its own instruction.

Omega desktop, committed artifacts, median ns per run: loops 1994 -> 857,
arrays 1767 -> 891, enums 547 -> 229, score 81 -> 68, text_demo 391 -> 348.
2026-11-15 10:52:31 -03:00
waozi c7b107d26f Keep every platform in the target matrix
The last three commits published a matrix with only the desktop
snapshot, so the site_targets check and the website deploy failed.
Restore the web and USB Android snapshots and the web artifacts they
ran, and render the library table in nanoseconds like the target table.

The previous matrix recorded outputs from an uncommitted compiler and
timed those, so it is rebuilt from the earlier snapshot whose outputs
and desktop timings match the committed artifacts. Rebuilding outputs
with site_targets.py now carries the platform snapshots forward; only
site_target_platforms.py replaces one.
2026-11-15 09:46:53 -03:00
waozi ad2952866f Speed up ZX engine host calls and record Omega timings 2026-11-15 01:58:44 -03:00
waozi e41b61abee Speed up ZX platform writes and report timings in ns 2026-11-15 00:27:25 -03:00
waozi 1f1abe72e7 Record Omega desktop target timings 2026-11-14 23:14:57 -03:00
waoziandGLM f60e704d4c Shorten the changelog to one line per change
Co-Authored-By: GLM <[email protected]>
2026-11-14 22:59:35 -03:00
waoziandClaude Opus 5.5 c43f2ba4e1 Share engine frame slots between records that are never live together
Arrays and records whose lifetimes don't overlap now share one frame
slot, and copies move eight bytes at a time. On Omega the Records kernel
went from 47.5 to 2.8 ms and image_resize from 49 to 42 ms; json is
unchanged. lowered_exec, which checks every limit against the reference
stepper, and all 71 zx_lowered_parity programs pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 22:27:28 -03:00
waoziandClaude Opus 5.5 96f65225e6 Record Omega benchmarks for the faster engine
json_scan 665 -> 170 ms, image_resize 278 -> 49 ms and float text
43.7 -> 11.4 s on Omega, with the bench/wasm_tier.zi kernels on C, the
engine and Wasm on the same machine.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 22:14:31 -03:00
waoziandClaude Opus 5.5 e4fe9c0b6c Ignore machine-local VS Code settings
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 22:09:11 -03:00
waoziandClaude Opus 5.5 43e743b081 Make the instruction engine about four to five times faster
Each verified function is translated once, when the plan is built, into
entries specialized by operation and width, with operands and storage
offsets resolved ahead. Work and fuel are charged per run of
instructions; a run that does not fit is refunded and stepped
instruction by instruction, so limits stop where they did. Verified
code skips the per-read validity check, single-use addresses make no
table entry, and the hottest pairs are fused. On Omega, json_scan went
from 665 to about 175 ms, image_resize from 278 to about 50 ms, and float
text from 43.7 to 11.9 s. lowered_exec checks every result against the
reference stepper at each work and fuel limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 22:08:00 -03:00
waoziandClaude Opus 5.5 9ad5f481ef Name the tools by what they turn into what, and run verified ZX natively
The tools are renamed after their input and output: zi2zx lowers source
or ZIR to executable ZX, zx2native turns ZX into a native ELF, zx2wasm
into a wasm32 module, and zi2c, zi2go and zi2zir keep their roles under
cmd/ folders of the same names. zi2asm and the cmd/zir-* folders are
gone, and tests/tool_names.sh keeps the old names out. zx2native keeps
the direct encoder as its default; the machine pipeline replaces it once
it reaches parity.

The embedding API can run a verified bundle as x86-64 machine code in
memory. Code is written to RW pages, relocated, then switched to RX,
never RWX, and each instance gets its own data
(cmd/zir/zir_native_memory.c, zir_host_native.c). Backend selection is
BundleBackendPolicy: Engine and Native are strict, and Auto chooses by
platform only, never by whether one program fits. A native gap is a
named error, never a switch to the engine. Desktop x86-64 Auto stays on
the engine until the native backend is complete.

cmd/compiler_machine_image.zi adds the target-neutral machine image
contract. The machine verifiers reject unknown relocation kinds,
out-of-range symbols and addends, non-host external calls, native-width
mismatches and missing stack or fuel facts. The machine pipeline lowers
and encodes more of LIR. Docs, site pages, Kryon's build references and
the benchmarks use the new names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 22:07:42 -03:00
waoziandClaude Opus 5.5 46a099154a Plan the native players, engine speed, tool names and self-hosting
The native ZX player plan gains its engine-speed section with the profile
and the steps toward at least 3x. The tool-name, self-hosting and native
optimization plans record how they coordinate. The Kryon web player tier
and engine float-text measurements from 2026-11-14 are kept with their
raw samples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:54:38 -03:00
waoziandClaude Opus 5.5 d9360880c3 Fix the CI build goal, Go version and an empty image clear
A plain `make` built only the first single-object rule once one was placed
above `all`, so the macOS and package jobs never got build/bin/ziran; the
goal is now named. CI pins Go 1.25, which the Zstandard module requires,
and fetches that module before the offline Go checks. Growing an empty
image by zero bytes no longer calls memset on a null pointer (UBSan).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:54:10 -03:00
waozi efe3fabf71 Run the Wasm tier under Asyncify, fix float32 literals, docs for one format
- The bundle WebAssembly tier runs inside Emscripten runtimes built with
  Asyncify, such as Kryon's web player: a host that suspends inside a
  call (image decode, storage flush) suspends the tier's frames and
  resumes at that call; JSPI runtimes keep the engine. The suspending-host
  test agrees with the engine, including suspension inside a module
  initializer and in a loop.
- Revision-28 lowering compares an untyped float literal with a float32
  operand as float32, as C does (`x: float32 = 0.55; x != 0.55` was true).
- A prebuilt build tree compiles only zir_load.c again (Toolchains CI).
- Site target matrix collected on desktop, web and the moto e6 (mobile);
  Kryon widget library data regenerated.
- Docs describe the instruction engine and one ZX format instead of the
  removed portable VM, TinyCC and zi2wasm routes.
- Plans: native ZX players and phones, self-hosting, tool names by
  format; engine before/after samples from Omega.
2026-11-14 17:54:25 -03:00
waozi 490c107fda Update the docs for the instruction engine after removing the portable VM 2026-11-14 17:54:14 -03:00
waozi 16b60d090f Free host-returned storage, speed up the engine, finish the Wasm tier
Engine (cmd/compiler_exec.zi, compiler_opt.zi, compiler_lowered_verify.zi):
- Storage that host calls return is given back once nothing the program
  can reach names it; 100,100 calls returning 64-byte strings peak at
  65,752 live bytes instead of growing by 6.4 MB.
- An address only loaded from or stored to later in its own block takes a
  scratch table entry instead of a permanent one, so programs that read
  millions of bytes of a global or of host text no longer hit the address
  limit. The optimizer drops block parameters every edge passes one value
  (float-text: 32,168 -> 1,031), and frame and plan records are read in
  place. float-text runs 63.9 -> 45.0 s locally.

Host interface and embedding:
- Types that hold themselves through a slice and procedure values are
  written in the interface section; when it cannot be written the build
  fails with a diagnostic naming the type instead of writing a bundle
  without it. Every entry-module global is lowered and named, so state
  export includes globals the entry never reads.

Wasm tier (cmd/zir-wasm/zx_wasm_lower.c, zir_zx_wasm_web.c):
- Recursive host types work; the tier stays out of Emscripten runtimes
  built with Asyncify or JSPI, where hosts suspend (Kryon's image and
  storage hosts trapped with "unreachable"), and the engine runs those.
  Kernels use real loops without dispatch tables. Benchmarks on Alpha in
  bench/wasm_tier.*, raw samples under bench/results/.

Also: generated C indexes []*T slices with pointer elements; the site
target matrix is regenerated for desktop and web (mobile waits for the
phone's USB authorization); ASSEMBLY docs describe one ZX format; the
package artifact test restores CC instead of unsetting it, since the
artifact key names the compiler.
2026-11-14 15:51:28 -03:00
waozi 1a750826b7 Give the engine's names a private prefix on every target
The instruction engine in libziran carries its own copies of the standard
modules (Sin, Copy, Count, ...). On ELF a merged object with objcopy
--localize-hidden kept them private, but wasm objcopy cannot localize and
COFF keeps no hidden visibility, so Kryon's browser player failed to link
against libziran built with the engine. scripts/engine-names.sh now writes
a header that renames every name the engine's modules declare to
ziran_engine_*, force-included in the engine and in the embedding API;
names a header also offers inline are renamed only in their own module.
The merge step goes.
2026-11-14 14:23:26 -03:00
waozi cb0a762fd4 Migrate to one ZX format and delete the old route
zi2zx bundle and ziran run always write and run revision-28 executable
ZX. The semantic bundle reader and writer, the portable VM, the
TinyCC-compiled and linked native bundles with the vendored TinyCC,
bundle libraries, the VM profile, --vm, BundleInstantiatePortable,
libziran-vm.a and the ZIR-based Wasm lowering with zi2wasm are removed;
the Wasm tier, the embedding API and every tool run revision 28. Tests
of the removed VM internals and libraries are removed, and the rest run
on revision 28. Engine problems read as the diagnostics users rely on.
2026-11-14 14:03:01 -03:00
waozi 1d2a6f5d85 Plan: record the switch-over work and its owners 2026-11-14 13:01:40 -03:00
waozi 42da58fef1 Remove the unused Ziran ZIR codec and its service helpers
cmd/compiler_serial.zi was built, imported and tested by nothing. The
saved-IR helpers only it used leave cmd/compiler_services.zi and
cmd/zir/zir_services.c, and the stale copy of the services module in
cmd/law-isolate goes too.
2026-11-14 13:00:53 -03:00
waozi 761411435d Run revision-28 bundles through the embedding API and Wasm
Lowering covers using fields, every Simd operation, target variants,
generic records shared between modules, constant tables as read-only
data and owned globals. The embedding API gives revision-28 bundles
slice copy-back, step limits over initialization, state export and
import, components, capability signatures and assets. The Wasm lowering
has the typed host ABI and a linear-memory heap, and the bundle Wasm
tier runs revision-28 bundles. With ZIRAN_BUNDLE_EXEC=1, 247 of 280
local tests pass; the default suite passes.
2026-11-14 12:54:26 -03:00
waozi f4a26ecc08 Lower parallel loops, bit builtins and constants; hide the engine's symbols
Parallel loops run in order, clz/ctz/popcount/bswap lower to ordinary
instructions, named constants work in global initializers, size_of takes
isize and usize, and union members take compound assignment. The engine
and the embedding bridge merge into one library object whose engine
symbols are hidden and localized, with its rule outside the bootstrap
conditional so bootstrap, Windows and Web library builds have it.
2026-11-14 11:02:10 -03:00
waozi 78d7eae3f8 Open revision-28 ZX through the embedding API
libziran links the portable instruction engine, one archive member per
generated module, and BundleOpen reads, verifies and plans a revision-28
file. Bundles run and instantiate as before, with each host call
translated between the engine's host image and VmHostValue trees by the
host interface section and the semantic VM's rules. The unchanged
record host test passes against a revision-28 file. ZIRAN_BUNDLE_EXEC=1
makes zi2zx bundle and ziran run write revision 28, to measure the
switch-over.
2026-11-14 10:49:25 -03:00
waozi 6582e55feb Name the host interface in revision-28 ZX
An optional section records the type spellings and record field names
of every host capability's parameters and result, which an embedder's
host values carry and the structural payload does not. Any pointer
crosses a host boundary as an opaque handle, and platform services are
recognised only in the ziran.platform module.
2026-11-14 10:22:36 -03:00
waozi 7eceb25e21 Run revision-28 ZX files with ziran run
zi2zx run reads a file whose header names revision 28 on the portable
instruction engine and prints what it prints for a semantic bundle;
other files still go to the bundle reader. zi2asm --run and zi2zx run
share one runner. The parity test runs every pinned program this way.
2026-11-14 10:03:30 -03:00
waozi f645a925bf Lower every spec program the semantic route runs
Assembly variants lower from their ordinary body, same-shaped records
convert field by field, one expression's instructions share an origin,
and the default work limit admits programs of several hundred thousand
instructions. 82 of 82 spec programs and 14 of 14 examples lower; the
parity test pins 68.
2026-11-14 06:05:39 -03:00
waozi 0e9abf798d Lower vectors lane by lane to revision-28 ZX
A vector type is an array of its lanes and each Simd operation is
lowered lane by lane, so every program that reads JSON lowers. The
interpreter's address index no longer fails when rebuilt smaller. 79 of
82 spec programs lower and the parity test pins 66.
2026-11-14 02:56:18 -03:00
waozi 665fbbca60 Lower integer case lists as a binary search
A case list of eight or more integer values branches through a binary
search over the values instead of one compare per case. The Unicode
normalization test now runs to the end on revision-28 ZX with the
semantic route's result.
2026-11-14 02:30:30 -03:00
waozi 65b890108e Give interpreter address entries back when frames return and blocks die
Entries made for a frame's storage or a heap block are chained to it and
released when the frame returns or the block is freed or resized. A
reused slot carries a new version in its pointer bits, so a pointer kept
from before still fails. A program no longer stops at its millionth
address.
2026-11-14 02:20:16 -03:00
waozi 4d7fa2fd45 Lower else-if chains flat and free heap storage without a scan
An if with its else-if links is one chain with one join block, so a case
list of any length lowers. The interpreter gives freed heap storage back
down a link from each block to the one below it, and a block keeps its
record when it grows in place.
2026-11-14 02:11:58 -03:00
waozi 6031f41cb7 Lower unions of integers and floats to revision-28 ZX
A union is one unsigned integer as wide as its widest member; a member
is read and written by reinterpreting its low bytes. The parity test
pins 57 programs.
2026-11-14 02:04:53 -03:00
waozi e36596732a Lower VecClone and remove seven unused procedures
VecClone fills a fresh destination with a copy whose capacity is the
source's count, sharing the element loop with VecResize. Seven
procedures nothing called leave the portable interpreter, the executable
reader and the native encoder.
2026-11-14 02:00:38 -03:00
waozi 2f22c43e22 Lower VecGet and VecPop to revision-28 ZX
Both answer an Option: VecGet copies an element and gives nothing at or
past the count, VecPop moves the last element out and shortens the
vector. The parity test pins 54 programs.
2026-11-14 01:51:44 -03:00
waozi 4401df78e7 Evaluate laws over records returned under another type spelling
A procedure declared with an imported record type that forwards the
imported module's record, or returns an untyped literal, was outside the
compile-time evaluator. The returned record is matched by its declared
type and the literal takes the return type.
2026-11-14 01:47:01 -03:00
waozi a0136b02b7 Lower VecResize and index the interpreter's address table
VecResize reserves like VecReserve, drops the elements it removes and
zeroes the ones it adds. A derived address is found through a hash index
instead of a scan of the whole table, so image_resize_fallible runs on
revision-28 ZX; the parity test pins 53 programs.
2026-11-14 01:38:03 -03:00
waozi 39ae6033ac Lower New, free, size_of, signed constants and untyped null
New(T) and free use the heap instruction, size_of is the C layout size,
a folded constant keeps its sign, and a bare null takes the pointer type
it is passed, assigned or returned as. 60 of 77 spec programs lower and
the parity test pins 51.
2026-11-14 01:29:13 -03:00
waozi 9a453acd80 Lower rich host values, shared float and array types and long zero arrays
Host capabilities on revision-28 ZX take and return records, fixed arrays
and views of host values and opaque handles, passed as one host image.
float32, float64 and [N]T are one lowered type for the whole program, the
zero value of a long fixed array is read from a frame slot, and VecReserve
and signed literals in global initializers lower. All 89 built Kryon
examples now lower to revision-28 ZX.
2026-11-14 01:16:18 -03:00
waozi a4fb763b2e Document module initializers and test registration by import
A module-level variable whose initializer calls a procedure is the module's
initializer. The usage guide now says so, with the registration pattern it
enables: a library calls an optional part through a procedure variable, and
the module a caller imports to use that part registers it, so programs that
do not import it carry neither the module nor what only it reaches.

tests/module_registration.sh locks this on C from source and saved IR, on
the native and portable engines, and on Go: the import alone runs the
initializer, and without it the feature's files are not generated.
2026-11-13 22:49:16 -03:00
waoziandClaude Fable 5.2 b721a53649 Lower pointer fields, VecSwap and literal global initializers
pointer.field reads and writes go through a field address on the
pointer itself. VecSwap exchanges two vector places without moving an
element. A global whose initializer is a record, nested record, string,
float or fixed-array literal is parsed as the checked expression it is
and stored by a private <name>.initializer procedure; those run before
every module startup procedure. Untyped numeric literals inside such an
initializer take the type of the member or global they initialize.

The stack-slot encoder resolves record fields through its own
allocations, globals and loaded pointers, but a pointer argument names
another procedure's frame and trapped at run time. zi2asm now refuses
that at compile time as assembly.gap.native-pointer-field, following
block parameters to every incoming edge so local addresses still pass.

48 of 75 spec entries lower; every built Kryon example gets past these
forms.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 22:14:31 -03:00
waoziandClaude Fable 5.2 1078ba6ea4 Lower byte builders and owned Text to revision-28 ZX
BuilderAppend reserves room first with the C runtime's policy (capacity
0 starts at 8 and doubles until the text fits), then copies the bytes,
so a refused reserve appends nothing and an empty text allocates
nothing. BuilderFinish hands the bytes on as a string and empties the
builder, freeing an unused reserve. TextView borrows a Text or a
Vec(u8) in place. Vector types are interned by element type, so two
modules' spellings of Vec(u8) convert without a cast.

tests/spec/zx_lowered_text.zi matches the semantic route, capacities
included, and ends with no live heap block. 39 of 72 spec entries
lower.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 21:46:04 -03:00
waoziandClaude Fable 5.2 b1c9dc5516 Lower owned moves, vector-holding records and recursive drops
The checker marks each move on an identifier or member path. The
lowering reads the value and empties that source, as the C emitter's
clear_owned_value does, so the unconditional drop at scope exit frees
nothing twice. Records and fixed arrays may now hold vectors, vectors
may hold vectors, and vectors pass as parameters and results. Drops
recurse through fields and elements, with a loop over a vector whose
elements own storage; VecClear and VecFree drop those elements first.
A fresh owned result used as a statement is dropped at once, and a
procedure that falls off its end drops its parameters.

zi2asm --run --heap-report prints the heap blocks still live. The
parity test passes it for every program and requires none, which pins
both leaks and double frees. tests/spec/zx_lowered_owned.zi covers the
moves. 34 of 71 spec entries lower.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 21:35:50 -03:00
waoziandClaude Fable 5.2 a7fcb8ab01 Add heap blocks to LIR and lower the first owned vectors
LIR gains one heap instruction, resize(pointer, old_count, new_count),
numbered after unreachable so earlier encodings stand. The portable
interpreter keeps typed heap blocks in its owned bytes: a block's
addresses carry its generation, so a resize or free makes every derived
pointer fail as a returned frame's pointers do. The last block resizes
in place, dead tail blocks are given back, and a request beyond the
value-byte budget yields null with the old block intact.

Vec(T) lowers for elements that own no vectors: the record type,
indexing, count, capacity, VecSlice, VecPush with the C runtime's
growth (0 to 8, then doubling), VecClear and VecFree, plus drops of
vector locals at block close, return, break and continue. Moves,
vector-bearing aggregates, the Option-returning operations, builders
and Text stop at named compile errors.

tests/spec/zx_lowered_vec.zi gives the semantic route's output byte
for byte, capacities included; the executor cases cover allocate, grow,
zero fill, stale pointers, a wrong count, free and a refused request.
Native and wasm output name the gap.

Also pass -Icmd/zir-wasm only to the zi2asm objects; the target-specific
variable leaked it into every compile.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 21:24:50 -03:00
waoziandClaude Fable 5.2 712f70a324 Plan the heap collection lowering in steps
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 21:01:19 -03:00
waoziandClaude Fable 5.2 35e03697d4 Lower verified ZX to a wasm32 module with zi2asm --emit wasm
Wasm becomes the third lowering of one portable image, beside the
interpreter and native ELF. zi2asm --emit wasm reads the verified
revision-28 payload and writes one wasm32 module, so source input and
saved-ZX input give identical bytes; examples/hello.zi is 287 bytes.
The module keeps the existing budget and output ABI (zx.overrun,
zx.budget, zx.host_i64, zx_entry), so the node and web runners load it
unchanged. A form without wasm code stops at a named wasm.gap
diagnostic; the 37 codes are registered for ziran explain.

tests/zx_lowered_parity.sh emits each program twice, compares the
bytes, runs the module in node and compares its output with the
interpreter: 36 of 37 programs run as wasm.

zi2wasm and the bundle Wasm tier keep the ZIR-based lowerer until LIR
lowering covers the programs they run; the plan records why a one-step
replacement failed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 20:46:00 -03:00
waoziandClaude Fable 5.2 34aba841ae Lower slice stores, procedure slots and aggregate views to revision-28 ZX
First milestone toward one ZX format. The semantic bundle route runs 69
tests/spec entries; 32 now lower to revision-28 executable ZX (was 20).

Lowering: assignment through slice elements, including a field of a
record element; global procedure slots with typed null; comparisons of
mixed-signedness integers by value, as the semantic VM does; slice view
types interned by element type so two spellings of []T convert. The
verifier admits checked views of records, fixed arrays and procedure
values. The interpreter binds checked platform byte output, so
zi2asm --run prints.

Native output names its refusals: assembly.gap.native-aggregate-view,
and assembly.gap.native-limit and assembly.gap.native-unsupported
instead of a bare encoder problem number.

tests/zx_lowered_parity.sh holds 37 programs to identical output on the
semantic route and the revision-28 interpreter; native ELF matches or
stops at a named gap. The plan records the inventory and the order of
the remaining features.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 20:28:18 -03:00
waoziandClaude Fable 5.2 f985be664e Name both toolchains when a tool rejects another version's ZIR
A project that overrides its compiler can write ZIR that an older
installed tool then reads. The reader used to say only "unsupported ZIR
version". It now names the file's version, its own executable and the
version it reads, and the driver that started it, and tells the user to
rebuild or reinstall the toolchain. The driver passes its canonical path
to every tool as ZIRAN_DRIVER.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 20:20:34 -03:00
waozi b0216fd4e1 Restore the Wasm lowering removed by the previous commit
The previous commit picked up another task's uncommitted deletion of
cmd/zir-wasm/zir_wasm_lower.c and its header, whose replacement is not
committed yet. Restore both so master builds.
2026-11-13 19:43:32 -03:00
waozi bd85c5288f Show ZIR listings by meaning and call it just ZIR
ziran inspect printed every expression's text, so a statement's source
appeared once per node. Statements now carry their source once as a
trailing comment; literals show their value and calls their callee and
arguments, and expression text is printed only when no statement holds it.

ZIR is always written after type checking, so docs, the website and the
zi2asm pipeline help call it ZIR instead of checked ZIR or checked IR.
The site's inspection listings are regenerated in the new form.
2026-11-13 19:42:51 -03:00
waozi 7fc35a9bff Save expression text as a slice of its statement in ZIR 64
Every ZIR expression saved its own copy of its source text, so a call and
its literal arguments repeated the statement's text. An expression whose
text appears in a statement of its function now saves that statement's
distance from the last one referenced, the text's length and a change in
the span-to-offset bias; the writer keeps whichever form is shorter and
the reader rebuilds identical text. Statement text stays: the checker
parses loop headers, targets and case markers from it when it loads ZIR.

examples/hello.zi saves its literal once (223 to 184 bytes) and
compiler_lowered_x64.zir shrinks from 583,008 to 526,092 bytes. The
published site artifacts are re-encoded with identical inspect listings.
2026-11-13 19:30:22 -03:00
waozi b390572374 Unify the native pipeline around verified ZX and shrink native hello
Source builds now check and lower to LIR, verify and optimize it, encode
portable ZX, and read that same verified image for the interpreter or for
native ELF generation. Standalone .lirb, --emit exec and --input exec are
removed. Linux x86-64 hello lowers to a static ELF with target-owned
write_all/exit_group veneers and no libc, CRT or dynamic linker.

Add machine IR register allocation, allocated-code verification, the
x86-64 encoder and ELF writer, LIR optimizer folds and type/origin
pruning, and the matching ASSEMBLY, docs and site updates.

Native tests now remove their temporary build/tests folders after failing
runs too, and the private Chromium profile under build/t is removed on close.
2026-11-13 18:13:30 -03:00
waozi 37a64372a6 Add target-aware package application APIs 2026-11-13 04:20:48 -03:00
waozi 1cf12f8aa4 Optimize lowered execution planning 2026-11-13 02:43:24 -03:00
waozi 01ad5ebbc6 Map re-exported types through the caller's module alias
A facade that re-exports a type with `using PropsModule :: #import "button_props"`
spells it PropsModule.Props in its procedure signatures. A caller that
imports the facade as Button and has its own PropsModule alias resolved
that spelling to its own module, so Button.Draw(props: Button.Props)
failed with "imported procedure parameter type is shadowed" and an
argument type mismatch; results failed the same way.

A qualified call site now names any type the callee module declares or
publicly re-exports as Alias.Name, accepted only when it resolves to the
same declaration. Unqualified imports keep their shadowing rejections.
2026-11-13 01:17:40 -03:00
waozi 04fadbbce7 Measure the verified-LIR portable engine in the ZX comparison
bench/zx_lowered_host.c runs the revision-28 executable form of
bench/zx_compare.zi through the new portable engine. It uses the same
arguments, Input host ABI, warmup loop and JSON row as the existing
VM/TinyCC harness. zx_compare.py prepares both fixtures and measures
the new `lowered` variant beside vm, native and c.

Summaries now apply the repository's symmetric 1.5×IQR rule with
inclusive interpolated quartiles, keeping raw samples and excluded
indices. Receipts name Alpha's physical host only when it attests as
non-virtualized.
2026-11-12 20:23:44 -03:00
waozi ab18ff0972 Lower string literals and counts in the direct backend
`string` lowers to the record {data: *u8, count: s64}. Literals become
deduplicated read-only byte-array globals; empty literals use a null
data pointer. Copies, reassignment, returns, .count and .data work
from source and saved IR through the portable engine and match the C
backend.

The verifier allows read-only globals only for byte-array constants of
exact length, and allows byte-array constants only as their
initializers. The engine copies the bytes per instance and traps any
store through them. Indexing, comparison and concatenation are rejected
explicitly. Native output and machine IR reject read-only data until a
read-only section exists.

bench/zx_compare.zi now lowers to a verified revision-28 container.
2026-11-12 20:18:22 -03:00
waozi 525ebb743b Lower host_api calls to explicit capabilities in the direct backend
`#foreign host_api` declarations with bool, integer and float
signatures now lower from source and saved IR to bodiless Host
functions called by host.call. The verifier keeps host signatures
bodiless and scalar, forbids direct calls, procedure values and entry
use of them, and lets host.call reach nothing else.

Revision-28 containers store the reachable capability count recomputed
from verified instructions. The reader rejects a manifest whose count
differs. The portable engine gains LirExecBindHost: a run with an
unbound capability stops before the entry executes, and host results
must use canonical bits for their declared type. Native output and
machine IR reject host calls explicitly until the native host ABI
exists.

This removes one of the two constructs that block bench/zx_compare.zi
on the new path. String values remain.
2026-11-12 19:54:05 -03:00
waozi 4e33fa2221 List the Mermaid package on the website
Regenerate the module index, home page count and sitemap, and add the
Mermaid package reference page now that ziranlang/mermaid is published.
2026-11-12 19:46:04 -03:00
waozi 10e854af6b Add native std facades, fix ASCII lowercase and move site examples
Portable standard facades for byte text, environment, timers, randomness,
mapped files, streams, worker pools, directory trees and threads; full ASCII
lowercase in std/unicode; examples move to examples/ with generated site
pages; Go output handles mixed-width slice bounds.
2026-11-12 19:15:45 -03:00
waozi bb89cbe24b Add the revision-28 executable ZX container and machine IR boundary
The experimental direct backend now writes and reads an opt-in
revision-28 ZX container that holds verified lowered instructions.
Stripped files run through the portable engine without source or
semantic IR. Bounded validation covers framing, identities, symbols
and reachability, and versions 26/27 are rejected with a rebuild
diagnostic. Default ziran/zi2zx output is unchanged.

Address-taken local scalars lower to fresh checked frame storage in
the portable engine and native x86-64, including aliases across calls
and recursion and stale-token traps. A verified target-neutral machine
IR keeps Allocate as an explicit effectful operation ahead of register
allocation.

ASSEMBLY/milestones.md reviews the ten-step plan and reorders delivery
around a Linux x86-64 vertical slice. It starts with an Alpha
physical-host baseline and adds staged interim comparisons. Plan
statuses now match the implementation.
2026-11-12 19:11:59 -03:00
waozi 71c0eec79d Compile Go slice bounds of mixed integer widths
Cast both VecSlice bounds to int64 in generated Go so s16 and s32
indices compile, and cover bracket slicing and VecSlice with those
widths in the vector check.
2026-11-12 19:07:01 -03:00
waozi d2db9d35fe Extend verified direct assembly execution and optimization 2026-11-11 21:28:27 -03:00
waozi 0ac56bdebe Build the native compilation database validator with supported flags
Compile the Ziran validator with ziran build --exe before executing it. This forwards Darwin defines through the supported build interface and preserves every compilation-database assertion and recorded C command.

Local tests: the compilation database integration and native source/saved-IR file integration passed on Linux; generated C for both Darwin ABIs passed syntax validation. Native macOS CI provides the remaining platform verification.
2026-11-11 19:11:32 -03:00
waozi 78621014f3 Prepare the approved Ziran 0.4.2 release
Consolidate the completed changes into the 0.4.2 release notes and regenerate the release inventory and module pages through update_version.sh.

Local tests: version, site pages and published targets, JSON SIMD and release-inventory cases, assembly comparison validation, Alpha benchmark artifact validation, and all 4661 local links passed. Preserve ongoing VM and assembly edits outside this release.
2026-11-11 19:03:49 -03:00
waozi 4838ce9b2f Improve runtimes, add an experimental direct backend, and prune Ziran tests
Prepare short portable helpers and scalar record reads, improve JSON SIMD scanning, expose one-line execution, and publish qualified Alpha benchmark artifacts. Add the experimental verified lowered execution, serialization and Linux x86-64 backend with source maps.

Physically remove 263 redundant test entry points and unused helpers, migrate retained helpers to Ziran, and execute the full retained suite without sharding. Allow ignored backup state for the managed physical Alpha workflow.

Local validation: all 268 retained tests passed across the full run and corrected targeted reruns; bootstrap matches. Current assembly verifier, x86-64, executor and serializer tests passed. Website examples and all 4661 local links passed. Six Alpha JSON/text workloads retain verified artifacts, raw samples and explicit unsupported Wasm diagnostics. The mobile sub-500 ns target remains pending.
2026-11-11 18:46:34 -03:00
waozi 126266c4a6 Release 0.4.1 with faster portable execution and verified benchmarks 2026-11-11 02:25:51 -03:00
waozi 8d44256676 Remove Wine execution while retaining Windows cross-build tests 2026-11-10 23:56:47 -03:00
waozi 4dc2da6b09 Publish measured desktop, Android and web target matrix
Compare five real examples across four targets on three measured platforms, preserving raw samples, independent output verification and artifact provenance.

Complete the WebAssembly support needed by the examples, inspect ZX bundles, prune generated C dependencies while preserving C++ linkage, and validate native script execution. Optimize only the temporary bootstrap seed and retain fresh-build measurements and historical benchmark records under bench/results.

Local tests: all 522 cases passed across the full run and corrected header-test rerun; all 16 bootstrap modules match. Playground runtime, bundle runtime, private browser layouts and matrix controls, published artifacts and local site links passed.
2026-11-10 23:50:12 -03:00
waozi 61b1e5402a Adopt capybara branding and require CI website deployments 2026-11-10 22:00:44 -03:00
3478 changed files with 1828747 additions and 282836 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Byte-preservation fixtures deliberately contain trailing spaces.
tests/fixtures/formatter/source.zi.in -whitespace
+144
View File
@@ -0,0 +1,144 @@
# Generated by waozixyz/gitea-ops scripts/test-ziran.py --emit from
# .github/workflows/check.yml (Linux check job) for Build's Gitea runner.
name: Build check
on:
# Prose alone cannot break a check. CHANGELOG.md is read by the version check.
push:
branches: [master]
paths: ['**', '!**/*.md', CHANGELOG.md]
pull_request:
paths: ['**', '!**/*.md', CHANGELOG.md]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: check-${{ github.ref }}
cancel-in-progress: false
jobs:
check:
name: check
runs-on: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'build-native-ziran' || 'build-primary' }}
timeout-minutes: 90
env:
JOBS: 2
BUILD_NATIVE: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'true' || 'false' }}
steps:
- name: Check out the exact Build commit
id: native
if: env.BUILD_NATIVE == 'true'
run: gitea-native-build checkout
- uses: actions/checkout@v4
if: env.BUILD_NATIVE == 'false'
# site_pages.sh marks std modules shipped in the latest v* tag.
with:
fetch-depth: 0
- uses: actions/setup-go@v5
if: env.BUILD_NATIVE == 'false'
with:
go-version: '1.25'
cache: false
# tests/zstd_go_cases.zi builds against this module with GOPROXY=off,
# and the module itself requires Go 1.25.
- name: Fetch the Go Zstandard module for the offline Go checks
if: env.BUILD_NATIVE == 'false'
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 tools and the private display for the test scripts
if: env.BUILD_NATIVE == 'false'
timeout-minutes: 5
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip gcc-mingw-w64-x86-64 wine wine64 xvfb xauth libsdl2-dev ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
# The emcc checks use the Emscripten the playground and the site use;
# Ubuntu's emscripten package is 3.1.6, and its emcc is a symlink to a
# wrapper that cannot run under its resolved name.
- name: Set up Emscripten
if: env.BUILD_NATIVE == 'false'
uses: emscripten-core/setup-emsdk@v15
with:
version: '6.0.6'
- name: Keep compile results between runs
if: env.BUILD_NATIVE == 'false'
uses: ./.github/actions/compile-cache
with:
key: check
- name: Verify the cached native toolchain and Go modules
if: env.BUILD_NATIVE == 'true' && steps.native.outputs.current == 'true'
run: gitea-native-build run bash -ec 'emcc --version && go mod download github.com/klauspost/[email protected]'
- name: Build the toolchain
if: env.BUILD_NATIVE == 'false' || steps.native.outputs.current == 'true'
run: |
if [ "$BUILD_NATIVE" = true ]; then
gitea-native-build run make
else
make
fi
- name: Run the language, backend, and portable runtime checks
if: env.BUILD_NATIVE == 'false' || steps.native.outputs.current == 'true'
run: |
if [ "$BUILD_NATIVE" = true ]; then
gitea-native-build run env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=2 </dev/null
else
env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=2 </dev/null
fi
- name: Pack the tested Ziran toolchain
id: toolchain
if: github.server_url == 'https://git.waozi.xyz' && github.event_name == 'push' && github.ref == 'refs/heads/master' && (env.BUILD_NATIVE != 'true' || steps.native.outputs.current == 'true')
env:
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
run: |
output="build/toolchains/$GITHUB_SHA"
if [ "$BUILD_NATIVE" = true ]; then
gitea-native-build run python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
else
python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
fi
printf 'directory=%s/%s\n' "$SOURCE" "$output" >> "$GITHUB_OUTPUT"
- name: Keep the verified toolchain archive
if: steps.toolchain.outputs.directory != ''
uses: actions/upload-artifact@v4
with:
name: toolchain-${{ github.sha }}
path: ${{ steps.toolchain.outputs.directory }}
if-no-files-found: error
- name: Publish the toolchain to Gitea Packages
if: steps.toolchain.outputs.directory != ''
env:
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
OUTPUT: ${{ steps.toolchain.outputs.directory }}
ZIRAN_TOOLCHAIN_PACKAGE_USER: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_USER }}
ZIRAN_TOOLCHAIN_PACKAGE_TOKEN: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_TOKEN }}
run: |
if [ -z "$ZIRAN_TOOLCHAIN_PACKAGE_USER$ZIRAN_TOOLCHAIN_PACKAGE_TOKEN" ]; then
echo "Gitea package writer is unavailable. The toolchain is in this run's artifacts."
exit 0
fi
for descriptor in "$OUTPUT"/*.json; do
python3 "$SOURCE/scripts/toolchain_package.py" publish "$GITHUB_SHA" "$descriptor"
done
- name: Show how much the compile cache saved
if: always()
run: |
if [ "$BUILD_NATIVE" = true ]; then
gitea-native-build run ccache --show-stats || true
else
ccache --show-stats || true
fi
- name: Keep complete check logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: check-logs
path: ${{ steps.native.outputs.source || github.workspace }}/build/check-logs/
release:
name: Publish a new Ziran version
needs: check
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
runs-on: build-native-ziran
permissions:
contents: write
steps:
- name: Check out the tested Build commit
run: /usr/local/libexec/gitea-native-build checkout
- name: Publish the tested VERSION to Gitea
env:
ZIRAN_RELEASE_TOKEN: ${{ github.token }}
run: /usr/local/libexec/gitea-native-build run python3 scripts/release_gitea.py
+26
View File
@@ -0,0 +1,26 @@
name: Quick Ziran build
on:
workflow_dispatch:
permissions:
contents: read
jobs:
quick:
# Build's primary host slot. ccache is installed on the host.
runs-on: build-primary
timeout-minutes: 15
steps:
- uses: https://github.com/actions/checkout@v4
with:
persist-credentials: false
- uses: ./.github/actions/compile-cache
with:
key: check
- name: Compile and start Ziran
run: |
make JOBS=2 build/bin/ziran
build/bin/ziran --version
- name: Report compile cache savings
if: always()
run: ccache --show-stats
+290 -75
View File
@@ -1,11 +1,11 @@
name: Set up Ziran
description: >
Check out the Ziran a project's ziran.lock pins with its compiler built, put
its build/bin on PATH and optionally fetch the locked packages. The build
tree is the Toolchains workflow's prebuilt archive for that commit, else
this repository's cache, else a build here. Package checkouts are cached by
the whole lock and start from the previous checkouts when it changes,
keeping only the ones the lock uses.
Set up the Ziran revision pinned by a project's ziran.lock, put its
build/bin on PATH and optionally fetch the locked packages. The build
tree comes from this repository's exact verified cache, the Toolchains
workflow's prebuilt archive for that commit, or a build here. Package
checkouts are cached by the whole lock and start from the previous checkouts
when it changes, keeping only the ones the lock uses.
inputs:
project:
@@ -25,6 +25,12 @@ inputs:
Ubuntu packages to install, separated by spaces or lines, from the
canonical Ubuntu archive with time limits (scripts/ci_packages.sh).
default: ''
jobs:
description: Make jobs (1–64), capped by the runner's JOBS allocation when set. Defaults to JOBS or 1.
default: ''
min-free-mib:
description: Minimum available MiB at each destination (checkout, runner scratch, and requested package cache).
default: '1024'
recommends:
description: Also install the packages' recommended packages.
default: 'false'
@@ -51,49 +57,90 @@ outputs:
runs:
using: composite
steps:
- name: Resolve the Ziran commit
- name: Resolve inputs and check available space
id: resolve
shell: bash
env:
PROJECT: ${{ inputs.project }}
CHECKOUT: ${{ inputs.path }}
COMMIT: ${{ inputs.commit }}
FETCH: ${{ inputs.fetch }}
PACKAGES: ${{ inputs.packages }}
REQUESTED_JOBS: ${{ inputs.jobs }}
MIN_FREE_MIB: ${{ inputs.min-free-mib }}
run: |
set -euo pipefail
lock="$PROJECT/ziran.lock"
digest=none
if [ -f "$lock" ]; then
digest=$(python3 -c 'import hashlib, sys; print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())' "$lock")
for tool in python3 git mktemp rm mkdir printenv; do
if ! command -v "$tool" >/dev/null; then
echo "::error::Ziran setup requires $tool on PATH"
exit 1
fi
done
python3 - <<'PY'
import hashlib, json, os, re, shutil, sys, tempfile
from pathlib import Path
def number(label, value, maximum):
if not re.fullmatch(r'[1-9][0-9]*', value) or len(value) > len(str(maximum)) or int(value) > maximum:
raise ValueError(f'{label} must be an integer from 1 to {maximum}')
return int(value)
def probe(path, needed):
directory = path
while not directory.exists():
directory = directory.parent
if not directory.is_dir():
raise ValueError(f'expected a directory for {path}, found {directory}')
try:
with tempfile.TemporaryFile(dir=directory) as scratch:
scratch.write(b'ziran setup preflight')
scratch.flush()
except OSError as error:
raise ValueError(f'cannot write scratch for {path} in {directory}: {error}') from error
available = shutil.disk_usage(directory).free // (1024 * 1024)
if available < needed:
raise ValueError(f'{directory} has {available} MiB available for {path}, needs {needed} MiB')
env = os.environ
try:
allocation = number('JOBS allocation', env['JOBS'], 64) if env.get('JOBS') else None
requested = number('jobs input', env['REQUESTED_JOBS'], 64) if env['REQUESTED_JOBS'] else allocation or 1
jobs = min(requested, allocation) if allocation else requested
minimum = number('min-free-mib', env['MIN_FREE_MIB'], 1048576)
workspace = Path(env['GITHUB_WORKSPACE']).resolve()
checkout = Path(env['CHECKOUT'])
root = (workspace / checkout).resolve()
if not env['CHECKOUT'] or checkout.is_absolute() or workspace not in (root, *root.parents):
raise ValueError(f'checkout path must be relative to the workspace: {checkout}')
lock = Path(env['PROJECT'], 'ziran.lock')
lock_data = lock.read_bytes() if lock.is_file() else None
digest = hashlib.sha256(lock_data).hexdigest() if lock_data is not None else 'none'
commit = env['COMMIT']
fetch = env['FETCH'].lower() == 'true'
if not commit or fetch:
if lock_data is None:
raise ValueError(f'missing lock file: {lock}')
toolchain = json.loads(lock_data)['toolchain']
if not commit:
commit = toolchain['commit']
if not isinstance(commit, str) or not re.fullmatch('[0-9a-f]{40}', commit):
raise ValueError(f'expected a full Ziran commit hash, got {commit!r}')
sources = Path(env.get('XDG_CACHE_HOME') or Path.home() / '.cache', 'ziran', 'sources')
probe(root, minimum)
probe(Path(env['RUNNER_TEMP']).resolve(), minimum)
if fetch:
probe(sources.resolve(), minimum)
except (OSError, ValueError, KeyError, TypeError) as error:
sys.exit(f'::error::Ziran setup preflight: {error}')
with open(env['GITHUB_OUTPUT'], 'a') as output:
for name, value in {'commit': commit, 'lock': digest, 'root': root,
'sources': sources, 'jobs': jobs}.items():
print(f'{name}={value}', file=output)
print(f'Ziran setup preflight: {commit}, {jobs} make jobs, minimum {minimum} MiB per destination')
PY
if [ -n "$PACKAGES" ]; then
sh "$GITHUB_ACTION_PATH/../../../scripts/ci_packages.sh" --check
fi
if [ -z "$COMMIT" ]; then
COMMIT=$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["toolchain"]["commit"])' "$lock")
fi
if ! printf '%s' "$COMMIT" | grep -Eq '^[0-9a-f]{40}$'; then
echo "::error::The Ziran commit is not a full commit hash: $COMMIT"
exit 1
fi
case "$RUNNER_OS-$RUNNER_ARCH" in
Linux-X64)
platform=linux-x64
;;
Linux-ARM64)
platform=linux-arm64
;;
*)
platform=
;;
esac
# A compiler built on a newer image needs its newer C library, so
# cached build trees are kept per image.
libc=$(getconf GNU_LIBC_VERSION 2>/dev/null | tr ' ' '-' || true)
{
echo "commit=$COMMIT"
echo "lock=$digest"
echo "platform=$platform"
echo "system=${ImageOS:-local}-${libc:-nolibc}"
echo "root=$GITHUB_WORKSPACE/$CHECKOUT"
echo "sources=${XDG_CACHE_HOME:-$HOME/.cache}/ziran/sources"
} >> "$GITHUB_OUTPUT"
# The script of this action's version, so every project gets its fix
# whichever Ziran it locks.
@@ -116,6 +163,77 @@ runs:
read -r -d '' -a names <<< "$PACKAGES" || true
timeout 1200 sh "$GITHUB_ACTION_PATH/../../../scripts/ci_packages.sh" "${options[@]}" "${names[@]}"
- name: Check native tools and resolve the build cache key
id: native
shell: bash
env:
COMMIT: ${{ steps.resolve.outputs.commit }}
run: |
set -euo pipefail
require_tool() {
if ! command -v "$1" >/dev/null; then
echo "::error::Ziran setup requires $1 on PATH"
exit 1
fi
}
read -r -a compiler <<< "${CC:-cc}"
read -r -a host_compiler <<< "${HOST_CC:-cc}"
for tool in make tar find touch tee grep "${compiler[0]}" "${host_compiler[0]}" "${AR:-ar}"; do
require_tool "$tool"
done
platform=
libs=()
source='int main(void) { return 0; }'
if [ "$RUNNER_OS" = Linux ]; then
require_tool "${OBJCOPY:-objcopy}"
require_tool "${HOST_OBJCOPY:-objcopy}"
case "$RUNNER_ARCH" in
X64) platform=linux-x64 ;;
ARM64) platform=linux-arm64 ;;
esac
if [ -z "${PACKAGE_LIBS:-}" ]; then
source='extern int RAND_bytes(unsigned char *, int); int main(void) { unsigned char x; return RAND_bytes(&x, 1) != 1; }'
libs=(-lcrypto)
fi
fi
probe=$(mktemp -d "$RUNNER_TEMP/ziran-native.XXXXXX")
trap 'rm -rf "$probe"' EXIT
if ! printf '%s\n' "$source" | "${compiler[@]}" -x c - -o "$probe/probe" "${libs[@]}"; then
echo "::error::Ziran setup could not compile and link with ${compiler[*]}; check the diagnostics and native development dependencies above"
exit 1
fi
libc=$(getconf GNU_LIBC_VERSION 2>/dev/null || true)
libc=${libc// /-}
# Jobs do not change the generated objects. Build overrides and compiler
# identities do, and must not share the default prebuilt or cached tree.
config=(CC HOST_CC CFLAGS CPPFLAGS LDFLAGS BOOTSTRAP BOOTSTRAP_CFLAGS
AR OBJCOPY HOST_OBJCOPY PACKAGE_LIBS RUNTIME_LIBS SANITIZE_FLAGS
CMAKE GEN_ZI2C MAKEFLAGS ZIRAN_DEFINES)
overrides=false
for name in "${config[@]}"; do
if printenv "$name" >/dev/null; then
overrides=true
fi
done
fingerprint=$({
for name in "${config[@]}"; do
if printenv "$name" >/dev/null; then
printf '%s=%s\0' "$name" "${!name}"
fi
done
"${compiler[@]}" --version
"${compiler[@]}" -dumpmachine
"${host_compiler[@]}" --version
"${host_compiler[@]}" -dumpmachine
} | python3 -c 'import hashlib, sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())')
system="${ImageOS:-local}-${libc:-nolibc}"
{
echo "system=$system"
echo "key=ziran-build-v2-$RUNNER_OS-$RUNNER_ARCH-$system-$COMMIT-$fingerprint"
echo "platform=$platform"
echo "overrides=$overrides"
} >> "$GITHUB_OUTPUT"
- name: Check out Ziran
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
@@ -124,40 +242,78 @@ runs:
path: ${{ inputs.path }}
persist-credentials: false
- name: Download the prebuilt build tree
id: prebuilt
if: steps.resolve.outputs.platform != ''
- name: Restore the exact build cache
id: cache
continue-on-error: true
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ inputs.path }}/build
key: ${{ steps.native.outputs.key }}
- name: Verify the restored build tree
id: verify
shell: bash
env:
ROOT: ${{ steps.resolve.outputs.root }}
ASSET: ziran-${{ steps.resolve.outputs.commit }}-${{ steps.resolve.outputs.platform }}.tar.gz
COMMIT: ${{ steps.resolve.outputs.commit }}
KEY: ${{ steps.native.outputs.key }}
CACHE_HIT: ${{ steps.cache.outputs.cache-hit }}
run: |
set -uo pipefail
set -euo pipefail
if [ "$(git -C "$ROOT" rev-parse HEAD)" != "$COMMIT" ]; then
echo "::error::Ziran checkout does not match requested commit $COMMIT"
exit 1
fi
if ! git -C "$ROOT" diff --quiet HEAD --; then
echo '::error::Ziran checkout has changes to tracked build inputs'
exit 1
fi
started=$SECONDS
if [ "$CACHE_HIT" = true ]; then
if python3 "$GITHUB_ACTION_PATH/../../../scripts/toolchain_package.py" cache-verify "$KEY" "$ROOT/build"; then
echo 'valid=true' >> "$GITHUB_OUTPUT"
echo "Ziran cache: verified exact hit in $((SECONDS - started))s, skipping prebuilt download"
exit 0
fi
echo '::warning::Rejected exact Ziran cache entry; using the normal fallback'
else
echo 'Ziran cache: exact miss'
fi
# A failed or prefix restore can leave a partial tree behind.
rm -rf "$ROOT/build"
- name: Download the prebuilt build tree
id: prebuilt
if: steps.verify.outputs.valid != 'true' && steps.native.outputs.platform != '' && steps.native.outputs.overrides != 'true'
shell: bash
env:
ROOT: ${{ steps.resolve.outputs.root }}
ASSET: ziran-${{ steps.resolve.outputs.commit }}-${{ steps.native.outputs.platform }}.tar.gz
run: |
set -euo pipefail
base=https://github.com/ziranlang/ziran/releases/download/toolchains
work="$RUNNER_TEMP/ziran-prebuilt"
rm -rf "$work"
mkdir -p "$work"
# A just-published asset can answer 504 for a while, longer than
# curl's default 1+2+4 s of retries, so keep retrying for 2 minutes.
for tool in curl sha256sum; do
if ! command -v "$tool" >/dev/null; then
echo "::warning::Ziran prebuilt download requires $tool; building locally"
exit 0
fi
done
work=$(mktemp -d "$RUNNER_TEMP/ziran-prebuilt.XXXXXX")
trap 'rm -rf "$work"' EXIT
started=$SECONDS
echo "Ziran prebuilt: trying $ASSET"
# Newly published assets can return 504 for longer than curl's usual retries.
retry=(--retry 12 --retry-delay 10 --retry-max-time 120 --connect-timeout 10)
if curl -fsSL "${retry[@]}" --max-time 180 -o "$work/$ASSET" "$base/$ASSET" &&
curl -fsSL "${retry[@]}" --max-time 30 -o "$work/$ASSET.sha256" "$base/$ASSET.sha256" &&
(cd "$work" && sha256sum --check --quiet "$ASSET.sha256") &&
tar -xzf "$work/$ASSET" -C "$ROOT"; then
echo "found=true" >> "$GITHUB_OUTPUT"
echo 'found=true' >> "$GITHUB_OUTPUT"
echo "Ziran prebuilt: verified download in $((SECONDS - started))s"
else
rm -rf "$ROOT/build"
echo "No prebuilt build tree for $ASSET"
echo "Ziran prebuilt: unavailable after $((SECONDS - started))s"
fi
rm -rf "$work"
- name: Restore the cached build tree
id: cache
if: steps.prebuilt.outputs.found != 'true'
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ inputs.path }}/build
key: ziran-build-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-${{ steps.resolve.outputs.commit }}
- name: Build Ziran
id: build
@@ -166,9 +322,11 @@ runs:
ROOT: ${{ steps.resolve.outputs.root }}
COMMIT: ${{ steps.resolve.outputs.commit }}
PREBUILT: ${{ steps.prebuilt.outputs.found }}
CACHED: ${{ steps.cache.outputs.cache-hit }}
CACHED: ${{ steps.verify.outputs.valid }}
JOBS: ${{ steps.resolve.outputs.jobs }}
run: |
set -euo pipefail
started=$SECONDS
toolchain=built
if [ "$PREBUILT" = true ]; then
toolchain=prebuilt
@@ -185,48 +343,94 @@ runs:
rm -f "$ROOT/build/$name"
fi
done
stamp="$RUNNER_TEMP/ziran-build-stamp"
touch "$stamp"
stamp=$(mktemp "$RUNNER_TEMP/ziran-build-stamp.XXXXXX")
find "$ROOT/build" -exec touch -r "$stamp" {} +
rm -f "$stamp" "$ROOT/build/obj/cmd/zir/zir_load.o"
fi
jobs=$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)
log="$RUNNER_TEMP/ziran-make.log"
make -C "$ROOT" -j"$jobs" all 2>&1 | tee "$log"
log=$(mktemp "$RUNNER_TEMP/ziran-make.XXXXXX")
trap 'rm -f "$log"' EXIT
make -C "$ROOT" -j"$JOBS" BUILD_DIR=build all 2>&1 | tee "$log"
"$ROOT/build/bin/ziran" version
compiled=$(grep -c -- ' -c -o ' "$log" || true)
rm -f "$log"
echo "Ziran $COMMIT: $toolchain build tree, $compiled C files compiled"
echo "Ziran $COMMIT: $toolchain build tree, $compiled C files compiled in $((SECONDS - started))s with $JOBS jobs"
{
echo "toolchain=$toolchain"
echo "compiled=$compiled"
} >> "$GITHUB_OUTPUT"
echo "$ROOT/build/bin" >> "$GITHUB_PATH"
- name: Record the built tree's cache inventory
id: inventory
if: steps.build.outputs.toolchain == 'built' && steps.cache.outputs.cache-hit != 'true'
shell: bash
env:
ROOT: ${{ steps.resolve.outputs.root }}
KEY: ${{ steps.native.outputs.key }}
run: |
if python3 "$GITHUB_ACTION_PATH/../../../scripts/toolchain_package.py" cache-write "$KEY" "$ROOT/build"; then
echo 'ready=true' >> "$GITHUB_OUTPUT"
else
echo '::warning::Ziran build succeeded but its build tree could not be cached'
fi
- name: Save the build tree
if: steps.prebuilt.outputs.found != 'true' && steps.cache.outputs.cache-hit != 'true'
if: steps.inventory.outputs.ready == 'true'
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ inputs.path }}/build
key: ziran-build-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-${{ steps.resolve.outputs.commit }}
key: ${{ steps.native.outputs.key }}
# Package checkouts can hold programs built inside them, so they are kept
# per image as well.
- name: Restore the package checkouts
id: sources
if: inputs.fetch == 'true'
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.resolve.outputs.sources }}
key: ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-${{ steps.resolve.outputs.lock }}
key: ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.native.outputs.system }}-${{ steps.resolve.outputs.lock }}
restore-keys: |
ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.resolve.outputs.system }}-
ziran-sources-${{ runner.os }}-${{ runner.arch }}-${{ steps.native.outputs.system }}-
- name: Fetch the locked packages
id: fetch
if: inputs.fetch == 'true'
shell: bash
working-directory: ${{ inputs.project }}
env:
ZIRAN: ${{ steps.resolve.outputs.root }}/build/bin/ziran
run: '"$ZIRAN" fetch --locked'
ROOT: ${{ steps.resolve.outputs.root }}
JOBS: ${{ steps.resolve.outputs.jobs }}
run: |
set -euo pipefail
started=$SECONDS
# Fetch still checks the locked graph. When this launcher already is
# the lock's toolchain, skip forwarding to a second build of it.
python3 - <<'PY'
import json, os, subprocess, sys
from pathlib import Path
env = os.environ.copy()
root = env['ROOT']
lock = json.loads(Path('ziran.lock').read_text())
toolchain = lock['toolchain']
origin = subprocess.check_output(['git', '-C', root, 'config', '--get', 'remote.origin.url'], text=True).strip()
origins = ('https://git.waozi.xyz/ziranlang/ziran', 'https://github.com/ziranlang/ziran')
commit = subprocess.check_output(['git', '-C', root, 'rev-parse', 'HEAD'], text=True).strip()
same_origin = any(origin in (url, url + '.git') and toolchain.get('url') in (url, url + '.git')
for url in origins)
prepared = same_origin and commit == toolchain.get('commit') and not Path('ziran.local.toml').exists()
if prepared:
env['ZIRAN_PINNED_LAUNCHER'] = '1'
print('Ziran locked package fetch: using the prepared compiler', flush=True)
status = subprocess.run([env['ZIRAN'], 'fetch', '--locked'], env=env).returncode
if status:
sys.exit(status)
if prepared:
with open(env['GITHUB_OUTPUT'], 'a') as output:
print('prepared=true', file=output)
PY
echo "Ziran locked package fetch: $((SECONDS - started))s"
# A new lock starts from the previous lock's checkouts, so without this
# the saved cache keeps every commit ever locked and grows until runners
@@ -240,11 +444,15 @@ runs:
ZIRAN: ${{ steps.resolve.outputs.root }}/build/bin/ziran
SOURCES: ${{ steps.resolve.outputs.sources }}
KEEP: ${{ runner.temp }}/ziran-locked-checkouts
JOBS: ${{ steps.resolve.outputs.jobs }}
PREPARED: ${{ steps.fetch.outputs.prepared }}
run: |
python3 - <<'PY'
import json, os, re, shutil, subprocess
from pathlib import Path
sources, keep = Path(os.environ['SOURCES']).resolve(), Path(os.environ['KEEP'])
if os.environ['PREPARED'] == 'true':
os.environ['ZIRAN_PINNED_LAUNCHER'] = '1'
lock = json.loads(Path('ziran.lock').read_text())
names = [package['name'] for package in lock['packages']] + (['ziran'] if 'toolchain' in lock else [])
used = set(keep.read_text().split()) if keep.exists() else set()
@@ -260,3 +468,10 @@ runs:
removed += 1
print(f'Kept {len(used)} locked package checkouts; removed {removed} unused')
PY
- name: Save the locked package checkouts
if: inputs.fetch == 'true' && steps.sources.outputs.cache-hit != 'true'
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.resolve.outputs.sources }}
key: ${{ steps.sources.outputs.cache-primary-key }}
+73 -22
View File
@@ -14,13 +14,9 @@ concurrency:
cancel-in-progress: true
jobs:
check:
name: check (${{ matrix.shard }}/2)
name: check
runs-on: ubuntu-24.04
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
shard: [1, 2]
steps:
- uses: actions/checkout@v4
# site_pages.sh marks std modules shipped in the latest v* tag.
@@ -28,10 +24,21 @@ jobs:
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 and Wasm tools, and the private display for the test scripts
go-version: '1.25'
# tests/zstd_go_cases.zi builds against this module with GOPROXY=off,
# and the module itself requires Go 1.25.
- name: Fetch the Go Zstandard module for the offline Go checks
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 tools and the private display for the test scripts
timeout-minutes: 5
run: sh scripts/ci_packages.sh ccache ripgrep gcc-mingw-w64-x86-64 wine wine64 xvfb xauth ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip gcc-mingw-w64-x86-64 wine wine64 xvfb xauth libsdl2-dev ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
# The emcc checks use the Emscripten the playground and the site use;
# Ubuntu's emscripten package is 3.1.6, and its emcc is a symlink to a
# wrapper that cannot run under its resolved name.
- name: Set up Emscripten
uses: emscripten-core/setup-emsdk@v15
with:
version: '6.0.6'
- name: Keep compile results between runs
uses: ./.github/actions/compile-cache
with:
@@ -39,7 +46,42 @@ jobs:
- name: Build the toolchain
run: make
- name: Run the language, backend, and portable runtime checks
run: env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=4 CHECK_SHARD=${{ matrix.shard }}/2
run: env -u DISPLAY -u WAYLAND_DISPLAY WINDOWS_REQUIRED=1 ARM_REQUIRED=1 WASM_REQUIRED=1 ZIRAN_WASM_CC=clang-18 make check CHECK_JOBS=4
- name: Pack the tested Ziran toolchain
id: toolchain
if: github.server_url == 'https://git.waozi.xyz' && github.event_name == 'push' && github.ref == 'refs/heads/master' && (env.BUILD_NATIVE != 'true' || steps.native.outputs.current == 'true')
env:
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
run: |
output="build/toolchains/$GITHUB_SHA"
if [ "$BUILD_NATIVE" = true ]; then
gitea-native-build run python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
else
python3 scripts/toolchain_package.py pack "$GITHUB_SHA" "$output"
fi
printf 'directory=%s/%s\n' "$SOURCE" "$output" >> "$GITHUB_OUTPUT"
- name: Keep the verified toolchain archive
if: steps.toolchain.outputs.directory != ''
uses: actions/upload-artifact@v4
with:
name: toolchain-${{ github.sha }}
path: ${{ steps.toolchain.outputs.directory }}
if-no-files-found: error
- name: Publish the toolchain to Gitea Packages
if: steps.toolchain.outputs.directory != ''
env:
SOURCE: ${{ steps.native.outputs.source || github.workspace }}
OUTPUT: ${{ steps.toolchain.outputs.directory }}
ZIRAN_TOOLCHAIN_PACKAGE_USER: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_USER }}
ZIRAN_TOOLCHAIN_PACKAGE_TOKEN: ${{ secrets.ZIRAN_TOOLCHAIN_PACKAGE_TOKEN }}
run: |
if [ -z "$ZIRAN_TOOLCHAIN_PACKAGE_USER$ZIRAN_TOOLCHAIN_PACKAGE_TOKEN" ]; then
echo "Gitea package writer is unavailable. The toolchain is in this run's artifacts."
exit 0
fi
for descriptor in "$OUTPUT"/*.json; do
python3 "$SOURCE/scripts/toolchain_package.py" publish "$GITHUB_SHA" "$descriptor"
done
- name: Show how much the compile cache saved
if: always()
run: ccache --show-stats || true
@@ -47,7 +89,7 @@ jobs:
if: failure()
uses: actions/upload-artifact@v4
with:
name: check-logs-${{ matrix.shard }}
name: check-logs
path: build/check-logs/
macos:
runs-on: macos-latest
@@ -69,14 +111,10 @@ jobs:
cd "$RUNNER_TEMP/hello"
test "$("$ziran" run)" = "Hello, world!"
sanitize:
name: sanitize (${{ matrix.shard }}/2)
name: sanitize
runs-on: ubuntu-24.04
# A shard takes 15-20 minutes; runner speed varies by about twice.
# Runner speed varies; execute the whole lean suite under both sanitizers.
timeout-minutes: 35
strategy:
fail-fast: false
matrix:
shard: [1, 2]
steps:
- uses: actions/checkout@v4
# site_pages.sh marks std modules shipped in the latest v* tag.
@@ -84,16 +122,27 @@ jobs:
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version: '1.24'
go-version: '1.25'
# tests/zstd_go_cases.zi builds against this module with GOPROXY=off,
# and the module itself requires Go 1.25.
- name: Fetch the Go Zstandard module for the offline Go checks
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
- name: Install ripgrep and Vorbis for the test scripts
timeout-minutes: 5
run: sh scripts/ci_packages.sh ccache ripgrep ffmpeg libvorbis-dev python3-markdown
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip xvfb xauth libsdl2-dev ffmpeg libvorbis-dev python3-markdown
# The emcc checks use the Emscripten the playground and the site use;
# Ubuntu's emscripten package is 3.1.6, and its emcc is a symlink to a
# wrapper that cannot run under its resolved name.
- name: Set up Emscripten
uses: emscripten-core/setup-emsdk@v15
with:
version: '6.0.6'
- name: Keep compile results between runs
uses: ./.github/actions/compile-cache
with:
key: sanitize
- name: Run the checks under AddressSanitizer and UBSan
run: env -u DISPLAY -u WAYLAND_DISPLAY make sanitize CHECK_JOBS=4 CHECK_SHARD=${{ matrix.shard }}/2
run: env -u DISPLAY -u WAYLAND_DISPLAY make sanitize CHECK_JOBS=4
- name: Show how much the compile cache saved
if: always()
run: ccache --show-stats || true
@@ -101,7 +150,7 @@ jobs:
if: failure()
uses: actions/upload-artifact@v4
with:
name: sanitizer-check-logs-${{ matrix.shard }}
name: sanitizer-check-logs
path: build/sanitize/check-logs/
fuzz:
runs-on: ubuntu-24.04
@@ -135,7 +184,7 @@ jobs:
path: package
- uses: actions/setup-go@v5
with:
go-version: '1.24'
go-version: '1.25'
- name: Build the current toolchain
run: make
- name: Build the package's locked native library
@@ -143,7 +192,9 @@ jobs:
- name: Test every backend from source and saved IR with the current compiler
working-directory: package
run: |
python3 "$GITHUB_WORKSPACE/scripts/test_native_package.py" \
"$GITHUB_WORKSPACE/build/bin/ziran" run --target=c \
--root "$GITHUB_WORKSPACE/scripts" --module-path "$GITHUB_WORKSPACE/tests" \
"$GITHUB_WORKSPACE/scripts/test_native_package.zi" -- \
--ziran "$GITHUB_WORKSPACE/build/bin/ziran" \
--tools "$GITHUB_WORKSPACE/build/bin" \
--source "tests/${{ matrix.package }}_test.zi" \
+8 -2
View File
@@ -4,12 +4,12 @@ name: Publish website
# whenever a push to master changes it. The repository secrets
# CLOUDFLARE_API_TOKEN (Cloudflare Pages: Edit) and CLOUDFLARE_ACCOUNT_ID
# authorize it; without them the job finishes without deploying.
# By hand: npx wrangler pages deploy site --project-name=ziran --branch=master
# Deploy only through this GitHub Actions workflow; never invoke Wrangler locally.
on:
push:
branches: [master]
paths: ['site/**', 'web/playground.c', 'web/bundle.c', 'scripts/build_playground.zi', 'scripts/site_target*', 'tests/site_targets.sh', 'cmd/zir/**', 'cmd/package*.zi', 'cmd/compiler_*.zi', 'bootstrap/**', 'std/**', 'Makefile', '.github/workflows/site.yml']
paths: ['examples/**', 'site/**', 'web/playground.c', 'web/bundle.c', 'scripts/build_playground.zi', 'scripts/site_target*', 'scripts/site_library_targets.py', 'scripts/site_kernel_targets.py', 'scripts/site_standard_benchmarks.zi', 'scripts/site_benchmark_*.zi', 'bench/standard_cases.zi', 'bench/json_text.py', 'scripts/site_numbers.zi', 'bench/results/standard/**', 'scripts/benchmark_samples.py', 'bench/results/wasm-tier-*.json', 'tests/site_targets.sh', 'cmd/zir/**', 'cmd/package*.zi', 'cmd/compiler_*.zi', 'bootstrap/**', 'std/**', 'Makefile', '.github/workflows/site.yml']
workflow_dispatch:
concurrency:
@@ -35,6 +35,9 @@ jobs:
fi
- uses: actions/checkout@v4
if: steps.credentials.outputs.present == 'true'
with:
# Receipt checks read inputs at the commits that measured and published them.
fetch-depth: 0
- name: Set up Emscripten
if: steps.credentials.outputs.present == 'true'
uses: emscripten-core/setup-emsdk@v15
@@ -43,6 +46,9 @@ jobs:
- name: Build the browser playground
if: steps.credentials.outputs.present == 'true'
run: |
rm -rf site/examples
mkdir site/examples
cp examples/*.zi site/examples/
make -j2 all
build/bin/ziran run --target=c scripts/build_playground.zi
node tests/playground_runtime.cjs
+9
View File
@@ -1,7 +1,16 @@
/build/
/backup/
/tests/build/
/.fuse_hidden*
/work/
# zi2c locks the directory it writes, including a seed directory
.build.lock
__pycache__/
/.wrangler/
/site/assets/playground-runtime.js
/site/assets/playground-runtime.wasm
.wrangler/
# Editor settings local to one machine (the shared tasks.json stays tracked)
/.vscode/settings.json
# Command Code agent state
/.commandcode/
+93
View File
@@ -0,0 +1,93 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Ziran: Inspect assembly (scalar fixture)",
"type": "process",
"command": "env",
"args": [
"-u",
"DISPLAY",
"-u",
"WAYLAND_DISPLAY",
"-u",
"XAUTHORITY",
"-u",
"DBUS_SESSION_BUS_ADDRESS",
"HARMONY_DESKTOP_RECOVERY=0",
"build-queue",
"--",
"python3",
"scripts/inspect_assembly.py"
],
"options": {
"cwd": "${workspaceFolder}"
},
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [],
"presentation": {
"clear": true,
"panel": "dedicated",
"reveal": "always"
}
},
{
"label": "Ziran: Inspect assembly (choose source and entry)",
"type": "process",
"command": "env",
"args": [
"-u",
"DISPLAY",
"-u",
"WAYLAND_DISPLAY",
"-u",
"XAUTHORITY",
"-u",
"DBUS_SESSION_BUS_ADDRESS",
"HARMONY_DESKTOP_RECOVERY=0",
"build-queue",
"--",
"python3",
"scripts/inspect_assembly.py",
"--source",
"${input:assemblySource}",
"--entry",
"${input:assemblyEntry}",
"--root",
"${input:assemblyRoot}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [],
"presentation": {
"clear": true,
"panel": "dedicated",
"reveal": "always"
}
}
],
"inputs": [
{
"id": "assemblySource",
"type": "promptString",
"description": "Ziran source file, relative to the repository",
"default": "tests/spec/assembly_scalar.zi"
},
{
"id": "assemblyEntry",
"type": "promptString",
"description": "Direct-backend entry (MODULE:FUNCTION)",
"default": "assembly_scalar:Answer"
},
{
"id": "assemblyRoot",
"type": "promptString",
"description": "Module root, relative to the repository",
"default": "tests/spec"
}
]
}
+76 -21
View File
@@ -4,26 +4,81 @@ Ziran owns the language, compiler tools, `.zir`, portable `.zx` output,
standard modules, and runtime. Keep this repository usable for programs that
do not import a UI library.
- Do not put Inbe application code, screens, assets, workflows, or platform
policy in Ziran. Those belong in `../inbe`.
- Do not put Kryon widgets or UI-specific compiler cases in Ziran. Kryon is an
ordinary library in `../kryon`, imported by applications that need it.
- Add a capability here only when it is useful to non-graphical programs as a
language or standard-library feature. Keep the source, checked `.zir`,
native targets, and portable VM behavior aligned.
- Use the current Ziran syntax directly. Do not add legacy Kryon/KIR/KRB
compatibility paths.
- Do not preserve old source spellings, command flags, binary formats, or
runtime entry points for backward compatibility. Remove executable legacy
paths when replacing them; keep rejection tests that enforce the current
language rules.
- Run relevant checks with `DISPLAY` and `WAYLAND_DISPLAY` removed. Any test
that needs a display must use a private Xvfb/Xephyr display.
- Test with `make check` (every check, run in parallel on `BUILD_QUEUE_JOBS`)
and `make check-bootstrap`; `make check CHECK_FILTER=text` reruns only the
checks whose name contains `text`. Full logs are in `build/check-logs/`.
## Layout
- `cmd/` compiler and tools (`ziran`, `zi2c`, `zi2go`, `zi2zx`, `zx2native`,
`zx2wasm`, `zi-edit`, `zi-fmt`, `zi-api`, `zi-inspect`, `zi2zir`).
- `bootstrap/` generated C seeds; refresh with `make update-bootstrap`.
- `std/` standard modules; `tests/` retained checks; `proofs/` Lean model.
- `bench/` benchmark drivers; retained receipts in `bench/results/`.
- `docs/` user and contributor documents; `plans/` open work;
`ASSEMBLY/` machine-IR and ZX format specs; `site/` generated website.
- `scripts/` site and release helpers; `templates/` project templates.
## Commands
- Build: `make`; install: `make install-user` (into `~/.local/bin`).
- Checks: `make check` and `make check-bootstrap`. `make check
CHECK_FILTER=text` runs every check whose name contains `text`. Full logs
land in `build/check-logs/`.
- Run checks with `DISPLAY` and `WAYLAND_DISPLAY` removed; any test that needs
a display uses a private Xvfb/Xephyr.
- Proof model: `make proof-model LEAN=/path/to/lean` (see docs/LAWS.md).
## Question -> document
| Question | Document |
| --- | --- |
| How do I compile, run, or package a program? | docs/USAGE.md |
| Which targets and features are supported today? | docs/IMPLEMENTATION_STATUS.md, docs/FEATURES.md |
| How do packages, projects, and locks work? | docs/PACKAGES.md |
| What does the compiler pipeline do? | docs/ARCHITECTURE.md |
| How do I write Ziran (syntax by example, habits from other languages, std signatures)? | docs/REFERENCE.md (site/llms.txt is generated from it) |
| What is the language syntax (directives, enums, imports)? | docs/LANGUAGE_DIRECTION.md |
| How do owned values and recoverable failures behave? | docs/OWNED_VALUES.md |
| What do diagnostic codes and JSON diagnostics look like? | docs/DIAGNOSTICS.md |
| How do tools edit and query source programmatically? | docs/AUTHORING.md, docs/API_DISCOVERY.md, docs/SEMANTIC_EDIT.md |
| How do laws and proof certificates work? | docs/LAWS.md |
| What is `.zir`? | docs/ZIR.md |
| What is `.zx` and how is it linked? | docs/ZX.md, ASSEMBLY/zx-executable-format.md, ASSEMBLY/zx-library-format.md |
| How does direct native code generation work? | ASSEMBLY/README.md, ASSEMBLY/machine-ir.md, ASSEMBLY/lowered-format.md |
| How is Unicode handled? | docs/UNICODE.md |
| How do benchmarks run? | bench/README.md, bench/standard/README.md |
| What work is still open? | plans/open-work.md |
## Rules
- Scope: no Inbe application code (`../inbe`); no Kryon widgets or
UI-specific compiler cases (`../kryon` is an ordinary library). Add a
capability here only when non-graphical programs benefit. The exception
is ZX Runner and the platform layer it hosts (window, drawing, input,
media) on Linux and Android, which belong here even though they are
visual (owner, 2026-11-23); widgets stay in UI libraries.
- No backward compatibility: use current Ziran syntax only. Remove legacy
spellings, flags, binary formats, and entry points; keep the rejection
tests that enforce current rules.
- Keep source, checked `.zir`, native targets, and instruction-engine
behavior aligned. Generated output carries only the code a program reaches;
shrink output by removing what is not needed.
- Module roots are ordinary repeatable search folders. Keep package manifests,
CLI forwarding, editor paths and loader storage dynamically sized; do not add
a folder-count cap or library-specific compiler handling. Preserve resolution
ordering and use normal input-size, allocation and operating-system bounds.
CLI forwarding, editor paths, and loader storage dynamically sized; no
folder-count caps or library-specific compiler handling.
- Write retained test logic and helpers in Ziran. Remove redundant tests and
unused helpers instead of growing a parallel suite. Run every retained
check; never substitute sharding or skipped tests.
- Keep private transfer and recovery state under the ignored `backup/`.
Keep benchmark reports under tracked `bench/results/`; temporary compiler
and test outputs under `build/`.
- Benchmarks run directly on Alpha's physical host, never virtualized. If
Alpha is unavailable, wait instead of measuring elsewhere. Record the host
in every report; collect both sides of a comparison on the same host.
Exclude anomalies with the symmetric 1.5xIQR rule (inclusive interpolated
quartiles) for every target and platform; keep raw samples and excluded
indices.
- Shared checkout: commit on master through the shared index. `git add` only
your own paths, then `git commit -- <those paths>`, so other lanes' staged
paths stay out. Never `git add -A`, a private `GIT_INDEX_FILE`, plumbing
that writes commits or moves HEAD, a rebase, reset or stash; never touch
files another lane is editing.
- Deploy the website only through `.github/workflows/site.yml` on CI. Never
invoke Wrangler directly from a local terminal.
@@ -0,0 +1,98 @@
# Step 01 — Freeze the execution contract and completion matrix
Status: in progress. The experimental [scalar prototype](README.md) does not close this step's completion gates. Delivery order, plan review and per-row cutover rules are in [milestones](milestones.md); the Alpha physical-host baseline of the old engines was captured at milestone M0, before they were removed.
The [assembly-target gap policy](gap-policy.md) is normative. A missing
implementation is a named failing matrix cell with a stable diagnostic; no
fallback, downgrade, skipped probe, emulated run, or legacy engine can satisfy
that cell.
## Objective
Upgrade `.zx` into a portable executable instruction format and add a direct native compilation path. Preserve `.zir` as the checked language interchange format. Make every transformation inspectable, including the final linked instructions. QBE is outside this plan.
The intended architecture is:
```text
.zi -> .zir -> lowered portable IR -> .zx container
| |
+--------+---------+
|
optimization and target lowering
|
machine IR -> registers and stack frames
|
instruction encoding -> object code
|
native linker -> executable
.zx -> instruction verifier -> portable interpreter
.zx -> instruction verifier -> same native backend -> executable memory
```
Assembly listings are views of the instruction stream used for encoding, not a required write-and-reparse stage. Final disassembly reads the actual linked or loaded bytes.
## Ordered implementation files
1. [Contract and completion matrix](01-contract-and-completion-matrix.md).
2. [Lowered IR and verifier](02-lowered-ir-and-verifier.md).
3. [Complete language lowering](03-language-lowering.md).
4. [Portable instruction engine](04-portable-instruction-engine.md).
5. [ZX format and linking](05-zx-format-and-linking.md).
6. [Optimization and first native backend](06-optimization-and-native-backend.md).
7. [Architecture and platform coverage](07-architecture-and-platform-coverage.md).
8. [Assembler, object files, and native linker](08-assembler-objects-and-linker.md).
9. [Native runtime, cache, and host integration](09-native-runtime-and-integration.md).
10. [Inspection, performance, and final cutover](10-inspection-performance-and-cutover.md).
## Current repository boundaries
- [The shared IR schema](../cmd/compiler_ir.zi) represents typed statements, expression graphs, declarations, source spans, laws, and proofs.
- [The ZX container](../cmd/compiler_bundle.zi) packages verified instructions, assets and the host interface; [the embedding API](../cmd/zir/zir_host.c) runs them on [the portable instruction engine](../cmd/compiler_exec.zi).
- [The architecture contract](../docs/ARCHITECTURE.md) changes only after replacement paths are verified.
- Current working-tree changes belong to their existing tasks. Record a baseline and coordinate overlapping files before implementation; never absorb unrelated changes into this feature.
## Required decisions and deliverables
- [x] Create a [feature-by-target matrix](feature-matrix.md) from current compiler capability reporting, tests, and documented limitations. Name each feature, reference fixture, source/saved-IR behavior, portable behavior, native behavior, and required execution platform.
- [ ] Separate portable language behavior, native language extensions, CPU requirements, OS services, and foreign-runtime requirements. A Go-only foreign type does not become a portable native type by renaming its representation.
- [ ] Set the native language coverage target to all currently supported C-native language semantics, plus all currently supported portable ZX semantics. Keep C and Go output available. List legitimate target-specific exclusions explicitly.
- [x] Cover the maintained Linux, Android, Windows, macOS, and browser/WebAssembly combinations. Derive exact CPU/OS/ABI rows from the live toolchain and repository; include existing 32-bit ARM support. New architectures such as RISC-V are explicit extensions, not an unbounded definition of completion. The [target registry](07-architecture-and-platform-coverage.md#target-registry-and-preflight) lists every row.
- [x] Specify numeric behavior, memory and pointer rules, ownership, cleanup, initialization, traps, call order, concurrency, fuel checkpoints, and capability contracts before assigning opcodes: the [execution contract](execution-contract.md).
- [x] Define the new format as an incompatible executable-format revision: [revision 28](zx-executable-format.md), chosen against the writer it replaced. A file of another revision is rejected.
- [x] Define backend APIs and ownership: verified portable program, target description, machine program, encoded image, and loaded instance. Separate immutable code from mutable instance state. See the [contract layers](execution-contract.md#contract-layers).
- [x] State that validated native code is not an operating-system sandbox. Keep malformed-input rejection, capability restrictions, and native process isolation claims distinct.
- [x] Define debug and release policies. Semantic checks remain correct in both; stripping inspection metadata is an explicit build choice.
- [x] Record that cross-compilation, successful encoding, a child-agent receipt, or a saved benchmark report does not establish target execution correctness.
- [ ] Assign every non-Implemented matrix cell a stable Gap diagnostic or a
deliberate Excluded contract. Verify rejection before output replacement,
initialization, host calls or entry execution.
- [x] Make engine and target selection explicit. Portable, native, Wasm, C and
Go are separate contracts; none may rescue another after preflight fails.
The implementation keeps those routes distinct: portable runs
verified LIR, native means direct verified-LIR-to-machine-code/platform output,
and the separately selected C and Go backends generate source that can be
compiled into platform binaries. Native slice comparison and host ABI gaps stop
before output replacement; they do not select any of the other routes.
## Proposed implementation ownership
Implement reusable compiler/runtime modules in Ziran under `cmd/`, following the existing compiler modules. Add only necessary C embedding and OS glue at the existing boundaries. Proposed module names in later steps are implementation targets, not files claimed to exist today. Use the current C backend to bootstrap new Ziran code initially, then verify the new backend can build those modules itself.
## Definition of 100% complete
Every required matrix cell has fresh execution evidence; no required cell is
silently skipped or satisfied by a fallback. Every remaining gap has its stable,
side-effect-free error and stays visibly incomplete. Both source and saved
`.zir` reach the same lowered semantics. `.zx` runs without reparsing semantic
statement text or requiring embedded executable `.zir`. Native AOT and native
ZX execution use the same code generator without generated C, an external
assembler, or an external linker on the promised direct path. External
OS libraries remain allowed dependencies.
All ten exit gates must pass. A smaller scalar prototype is a milestone, never the finished upgrade. There is no promise of universally optimal machine code: performance acceptance uses declared workloads and measured regressions, not the phrase “absolute performance.” Missing hardware, signing facilities, or tools remain named incomplete gates.
## Verification and handoff
Save the baseline matrix, reproducible fixture list, explicit non-goals, and ownership map in this folder or the established documentation/report locations. Do not create release tags or bump the product version for planning. Step 02 may proceed once the semantic and portability contracts are concrete enough to encode and validate.
+96
View File
@@ -0,0 +1,96 @@
# Step 02 — Implement lowered portable IR and its verifier
Status: in progress; [typed scalar/aggregate schema and verifier](README.md), including checked global-derived pointers and procedure values. Complete memory, capability and language coverage remain pending. Depends on [step 01](01-contract-and-completion-matrix.md). Next: [complete language lowering](03-language-lowering.md).
The schema carries the [gap policy](gap-policy.md) through target preflight:
unsupported required operations and target extensions have stable identifiers
and cannot be rewritten as calls into another engine or backend.
## Objective
Create a structured, serializable representation of executable operations below `.zir`. It must support efficient interpretation and native lowering while retaining useful optimization and debugging facts. Do not make portable instructions expose physical registers, host addresses, or a particular calling convention.
## Existing integration points
- [Checked compiler records](../cmd/compiler_ir.zi).
- [ZIR reader and writer](../cmd/compiler_zir_serial.zi).
- [Scalar semantic helpers](../cmd/zir/zir_scalar.h).
- [Compiler embedding contract](../docs/COMPILER_API.md).
Proposed new modules: `cmd/compiler_lowered_ir.zi`, `cmd/compiler_lowered_verify.zi`, and `cmd/compiler_lowered_text.zi`. Keep binary ZX framing in step 05 rather than coupling instruction records to file offsets.
## Typed console service boundary
The direct console path represents output as effectful `HostCall` instructions,
not as generated C/Go or an untyped call to a process address. Its reserved
module is `ziran.platform`. The byte-output signature is exactly
`ziran.platform.write_all(u64 fd, *u8 bytes, u64 count) -> void`, with Host
calling convention, no variadic parameters, and no body. Here `*u8` is a
verified Ziran pointer token, not a raw host address. The native veneer resolves
that token to permitted byte storage and checks the requested extent before
issuing an operating-system write.
`compiler_lowered_verify.zi` admits this one pointer parameter only for that
exact module, name, arity, and type signature. It does not relax the ordinary
host-capability restriction on pointers or pointer-containing aggregates. The
native encoder independently validates the service signature; matching a name
alone cannot authorize a different ABI.
Literal-format `print` evaluates all arguments before its first output call.
It then emits literal byte writes and Ziran-owned signed-integer,
unsigned-integer, and boolean formatting services. The scalar formatter names
are `ziran.print.signed(s64)`, `ziran.print.unsigned(u64)`, and
`ziran.print.bool(bool)`, all returning void in the same reserved module.
`HostCall` retains its effect ordering through optimization. Float-format
service records may be inspected or serialized, but native ELF emission must
reject them with the named float-format gap until an exact formatter exists.
This console binding does not claim general foreign-call, host-trampoline, or
cross-target support; see [the runtime contract](09-native-runtime-and-integration.md).
## Implementation work
- [ ] Define program, module, type, function, basic-block, value, instruction, constant, global, import, and debug-location records with stable IDs.
- [ ] Use SSA values and block parameters for register-like values. Represent mutable/address-taken storage through explicit memory operations. Specify block-parameter semantics so interpreter and native phi elimination agree.
- [ ] Define integer widths and signed operations explicitly. Specify narrowing, sign/zero extension, overflow, shift counts, division edge cases, comparison, and conversion behavior from current Ziran semantics.
- [ ] Define float32/float64 operations, bitcasts, NaN-sensitive comparisons, signed zero, conversions, and rounding assumptions. Do not introduce implicit fast-math permissions.
- [ ] Extend the existing checked global/frame pointers, procedure values and
immutable string byte/count representation to heap-derived pointers, slices,
unions, vectors and the remaining string operations without assuming a fixed
host pointer width. Keep code, data and capability references distinct.
The M1 subset now includes checked frame-local aggregate/procedure storage,
bounded derived slice addresses, byte equality, readonly data and typed
byte-view/pointer-free aggregate capabilities. Unions, resizable vectors,
general ownership and raw host pointers remain open or deliberately rejected.
- [ ] Separate portable logical type identity from target physical layout. Keep field/element access and layout queries symbolic until target layout is known; explicitly mark native-layout-dependent declarations and required host ABI descriptors.
- [ ] Define loads, stores, copies, zeroing, address calculations, calls, branches, returns, traps, and unreachable terminators. Specify alignment, access width, alias assumptions, and permitted overlap for each memory operation.
- [ ] Preserve effect order with an explicit effect dependency or another equally checkable ordering contract. Calls, stores, cleanup, volatile/atomic operations, and fuel checkpoints must not move unsafely.
- [ ] Specify atomics and memory ordering only where supported by the language contract. Declare unsupported operations instead of interpreting ordinary loads as atomic.
- [ ] Define source-origin IDs and transformation-origin chains, including generated cleanup, inlined calls, generic instances, host adapters, and native variants.
- [ ] Attach conservative optimization facts such as known ranges, alignment, readonly arguments, and ownership. Distinguish verifier-derived facts from producer assertions; unsafe producer claims cannot authorize code motion or unchecked access.
- [ ] Implement deterministic traversal and textual dumps. Stable IDs must not depend on pointer values, allocator order, timestamps, or nondeterministic hash iteration.
- [ ] Implement a structural verifier for IDs, types, terminators, predecessor lists, argument arity, use-before-definition, dominance, block parameters, entry points, and reachable symbol signatures.
- [ ] Implement memory/effect and layout validation. Reject invalid offsets, contradictory alignments, malformed constant data, impossible call conventions, and illegal native-only operations in portable code.
- [ ] Bound decoder allocation and graph work by checked input sizes and explicit resource budgets. Use iterative algorithms where attacker-controlled depth could exhaust the compiler stack.
- [ ] Provide recoverable structured diagnostics with function, block, instruction, and source context. Library errors must not abort the host process or leak partially built programs.
- [ ] Represent required target features and Gap identifiers explicitly. The
verifier rejects an operation outside the selected target contract; it never
erases it, serializes it as a no-op, or substitutes a portable/native helper.
## Tests
Add `tests/lowered_ir_cases.zi` and `tests/lowered_verifier_cases.zi`, with shell launchers following the repository's existing check discovery.
- Positive fixtures: straight-line arithmetic, diamonds, loops, nested loops, block parameters, memory-backed locals, indirect calls, and multiple return fields.
- Negative fixtures: cycles in value definitions, invalid dominance, duplicate IDs, wrong block arity, missing terminators, bad types, impossible layouts, effect-order violations, and malformed debug references.
- Determinism: rebuild equivalent programs under different allocation histories and compare serialized instruction content and text dumps.
- Lifetime: retain a verified lowered program after closing its original `.zir` owner; verify ownership is explicit and no borrowed storage becomes invalid.
Run builds and local tests through `build-queue --` with `DISPLAY` and `WAYLAND_DISPLAY` removed. This step requires no benchmark claims.
## Exit gate
All defined instruction forms have documented semantics and verifier coverage. A malformed program cannot become executable merely because it has a “checked” flag. Every unresolved required operation remains a visible Gap with a stable diagnostic. No new saved format relies on C struct padding or process pointers. The schema, verifier, and printer are usable independently of a specific CPU backend.
## Handoff
Deliver the schema, opcode/effect/layout tables, diagnostics, deterministic fixtures, and verifier API to steps 03–05. Record any operation whose semantics remain unresolved; do not fill the gap with generated source text.
+63
View File
@@ -0,0 +1,63 @@
# Step 03 — Lower the complete supported language into executable operations
Status: in progress; [scalar, record, fixed-array, procedure-value and restricted global/pointer lowering](README.md). Complete language coverage remains pending. Depends on [step 02](02-lowered-ir-and-verifier.md). Next: [portable instruction execution](04-portable-instruction-engine.md).
Missing lowering follows the [gap policy](gap-policy.md): it is a stable,
source-located compiler error and an open matrix cell, never a request to
evaluate the AST, generate C, or select another engine.
## Objective
Translate checked `.zir` into the new portable executable model without recovering program meaning from statement text. Cover the full matrix from step 01; use a small arithmetic subset only to establish the lowering framework.
## Existing integration points
- [Checked program schema](../cmd/compiler_ir.zi) and [semantic body utilities](../cmd/compiler_zir_lower.zi).
- [Current statement, expression, and call emission](../cmd/compiler_zir_lower.zi) as behavior references, not source-generation dependencies.
- [Current semantic cleanup implementation](../cmd/compiler_ir_cleanup.zi).
- [Current native symbol/layout planning](../cmd/compiler_machine_elf.zi).
- [Current assembly metadata](../cmd/zir/zir_asm.c) and [SIMD classification](../cmd/compiler_simd_metadata.zi).
Proposed modules: `cmd/compiler_lower.zi`, `cmd/compiler_lower_expr.zi`, `cmd/compiler_lower_control.zi`, `cmd/compiler_lower_storage.zi`, and `cmd/compiler_lower_calls.zi`. Split further only when responsibilities require it.
## Implementation work
- [ ] Lower concrete checked functions after generic specialization and compile-time selection. Preserve declaration ownership, imported names, public/private linkage, and stable function identity.
- [ ] Lower expressions in the language's evaluation order. Named arguments evaluate in source order, then map to parameter positions; do not accidentally inherit machine ABI order.
- [ ] Lower short-circuit logic, conditional expressions, branches, every supported loop form, and named break/continue into explicit blocks and edges.
- [ ] Lower returns through a shared, checkable cleanup mechanism. Preserve `defer`, owned-vector/text destruction, moves, temporary lifetime, early exits, and unwind behavior wherever the target contract supports it.
- [ ] Extend the implemented mutable scalar locals, checked global/frame
pointers, nested record/fixed-array paths, immutable string literals/copies,
result records and aggregate copies to local aggregate/procedure-value
address-taking, heap-derived pointers, slices, dynamic aggregates, remaining
string operations and enum storage. Preserve zero initialization and copy
behavior.
M1 now lowers local aggregate/procedure address-taking, borrowed fixed-array
and byte-view slices, checked string indexing/comparison and ordered runtime
initializers. Resizable owned aggregates, generated cleanup/moves, unions and
remaining enum-storage coverage keep this broader item open.
- [ ] Make alias-sensitive assignments and in-place aggregate results correct when a later argument mutates the destination or a global aliases an argument. Optimizations must not change old-value reads.
- [ ] Emit explicit bounds/trap operations before optimization. Carry enough range and effect information for later verified check elimination; do not copy C-only proof shortcuts without their preconditions.
- [ ] Lower direct/indirect calls, procedure values, callbacks, foreign C calls, varargs, startup functions, and function-address equality. Record ABI intent without assigning physical argument registers yet.
- [ ] Represent language/runtime helpers through typed symbols with defined semantics. Implement helpers in Ziran where possible; inventory every remaining dependence on generated C macros, headers, or compiler intrinsics.
- [ ] Lower portable SIMD to explicit lane types and operations. Preserve saturation, wrapping, masks, lane order, shuffles, and signedness; keep native vector width selection for target lowering.
- [ ] Lower parallel regions into ordinary outlined procedures plus typed runtime operations. Preserve captures, reductions/results, deterministic failure behavior, and synchronization boundaries.
- [ ] Treat GPU offload and OS services as explicit declared backend/runtime capabilities. Implement existing behavior where supported and reject genuine missing facilities before execution without introducing application-specific compiler rules or CPU fallbacks.
- [ ] Preserve `#asm` portable implementations and typed native variant bindings as separate target implementations. A portable build lowers the portable implementation; a direct native build requires a matching architecture/feature variant and rejects its absence. Native templates have explicit operands, effects, clobbers, architecture, and CPU requirements; they cannot become portable opcode semantics.
- [ ] Reject reachable foreign Go objects, Go maps/interfaces, reflection-only tags, or runtime operations in targets that cannot implement them. Retain the Go backend and its existing valid programs.
- [ ] Carry global initialization order, reachability roots, callback roots, exported ABI layouts, diagnostic spans, and law/proof provenance into the lowered program.
- [x] Feed the result through the step-02 verifier unconditionally and make lowering failures recoverable through the compiler API.
## Tests
Create lowering fixtures in Ziran and reuse current behavior tests, including [numeric semantics](../tests/numeric_semantics.sh), [operand order](../tests/spec/native_operand_order_test.zi), [parallel captures](../tests/parallel_captures.sh), [generic assembly](../tests/generic_assembly_cases.zi), and [saved-IR mutations](../tests/saved_ir_mutations.zi).
For each matrix feature, compile from `.zi` and saved `.zir`; compare verified lowered structure, outputs, traps, observable host calls, and cleanup effects against the existing supported execution paths. Add independent expected-result oracles for numeric boundaries and aliasing cases rather than relying only on agreement between backends sharing helper code.
## Exit gate
Every supported source construct has an explicit lowering, a deliberate Excluded contract, or a named Gap with a stable diagnostic. No placeholder operation invokes an AST evaluator, generated C fragment, source-text interpreter, portable body, or alternate backend. All required cells must be implemented before step 10 can declare completion.
## Handoff
Deliver the complete lowered fixture corpus, runtime helper inventory, explicit capability signatures, and source-to-operation mapping. Interpreter and native work can proceed in parallel once the applicable opcode contracts are stable.
@@ -0,0 +1,79 @@
# Step 04 — Execute the portable instruction set directly
Status: in progress; the [isolated verified-LIR engine](portable-execution.md) executes the current verifier-supported subset through `zi2zx run`. Full memory, host-capability, lifecycle/state and target integration remain required. Depends on [steps 02](02-lowered-ir-and-verifier.md) and [03](03-language-lowering.md). Next: [ZX container integration](05-zx-format-and-linking.md).
## Objective
Build a portable execution engine for the new lowered instructions. It is a
semantic reference and an explicitly selected portable target. A host without
native code generation may select it deliberately, but a failed native request
must not select it automatically. It must not walk `.zir` expressions or
reconstruct source statements during execution.
## Existing integration points
- [Host-value translation](../cmd/zir/zir_host_exec.c) and [the embedding API](../cmd/zir/zir_host.c).
- [Portable execution contract](../docs/ZX.md).
Implemented module: `cmd/compiler_exec.zi`. Its immutable storage plan now keeps
scalars in word slots and aliases a dead aggregate source to its `Insert` result
only when a complete use count proves the source has no other consumer.
Proposed additional modules: `cmd/compiler_exec_memory.zi` and
`cmd/compiler_exec_host.zi`. Keep required embedding exports at the existing C
API boundary. Current source/saved-IR and serialized-instruction tests cover
scalar/aggregate operations, direct/indirect calls, instance globals, explicit
frames, budgets and structured traps; they do not establish completion of every
item below.
## Implementation work
- [x] Decode the current verified instruction subset once into a flattened,
immutable execution plan with indexed word/byte slots, cached frame bases and
pointer-based instruction/edge dispatch.
- [ ] Extend arithmetic, memory, call and trap execution from the current
verifier-supported subset to every required portable opcode.
- [x] Implement word-backed scalar slots and fixed aggregate storage for the
current logical layouts while preserving checked pointer provenance.
- [ ] Add dynamic/heap aggregate storage, slices and the remaining memory forms
(typed heap blocks through `resize` exist; address-table reuse does not);
do not replace the language memory model with WebAssembly linear-memory rules.
Checked borrowed slices and instance-owned host-returned byte storage are
implemented; resizable owned collections and their cleanup remain open.
- [x] Execute block-parameter transfers as parallel copies, using direct moves
only when proven safe and scratch storage for overlap, swaps and cycles.
- [x] Execute direct/indirect calls and recursion with owned frames and bounded
work, fuel and frame limits for the current subset.
- [ ] Complete owned-storage lifecycle, runtime global initialization, empty/null
slices, vector cleanup and callback boundaries. Returned fixed aggregates and
immutable string literal bytes/copies/count/data already execute on this path.
Runtime initializers, empty/null slices and host-returned byte ownership are
implemented per instance; vector cleanup and callback retirement remain open.
- [ ] Adapt capability calls using validated typed signatures. Check host result shapes before writing them into execution storage; preserve nested host-to-bundle calls and reentrancy contracts.
Scalar, structural byte-view and pointer-free record/fixed-array calls now use
validated adapters. Nested host-to-bundle calls, reentrancy and native host
trampolines remain open.
- [ ] Specify and implement fuel at stable semantic checkpoints. Optimizations must preserve when exhaustion becomes observable, especially relative to host side effects and traps. Any batched charging requires a proof that timing is equivalent.
- [ ] Implement portable SIMD lane behavior and legal parallel runtime operations without assuming native vector instructions or a host thread count.
- [ ] Keep execution state, host bindings, error state, and mutable globals per instance. Exercise simultaneous instances, nested calls, replacement, and retirement.
- [ ] Preserve snapshot/state migration semantics and library composition. Stable persistent identities must survive harmless instruction ordering changes without equating unrelated layouts.
- [ ] Make debug stepping instruction-based with source mappings and inspectable value slots. Avoid debug-only execution semantics that hide release-mode defects.
- [ ] Retain any existing `.zir` evaluator needed for compile-time execution, laws, or tooling until those consumers are deliberately migrated. Removing ZX dependence does not authorize deleting unrelated evaluator services.
- [ ] Reject every unsupported portable opcode/capability with its stable Gap
diagnostic before side effects. Do not invoke the old VM, native engine,
generated C, or a target-specific helper to make the run appear successful.
## Tests
Add `tests/lowered_exec_cases.zi` and mutation/fault fixtures. Reuse [portable pointers](../tests/portable_pointers.sh), [portable records](../tests/portable_host_records.sh), [string cases](../tests/simd_string_cases.zi), and the retained portable cases under `tests/`.
Require the same results from source lowering, saved-IR lowering, encoded/decoded executable instructions, and the reference engine. Compare traps and host-call traces as well as final return values. Test allocation failures, malformed host responses, recursive callbacks, repeated failures, and cancellation/resource exhaustion without leaking instance state.
Run on the current machine and the required supported hosts; use private displays only where a host test actually needs them. Cross-compiled objects are not portable engine execution evidence.
## Exit gate
All required portable matrix cells run from lowered instructions with no executable `.zir` tree present. The engine rejects unverified programs and Gap operations without switching engines, preserves instance isolation and documented resource behavior, and can supply independent differential results for native backend development.
## Handoff
Deliver the engine API, portable opcode coverage table, executable fixtures, trap/side-effect traces, and state migration tests. Performance tuning of dispatch follows measurement and does not block the semantic reference from being useful.
+54
View File
@@ -0,0 +1,54 @@
# Step 05 — Make ZX a versioned portable executable container
Status: in progress; the [revision-28 executable container](zx-executable-format.md) is the one `.zx` format. It stores verified LIR, runs stripped through the portable engine, and names its host capabilities, module globals and declarations in the host interface section; `ziran bundle`, `ziran run` and the embedding API use it. Library containers, partial composition and native variants remain open. Delivery order: [milestones](milestones.md) M1 and M3. Depends on [steps 02](02-lowered-ir-and-verifier.md)–[04](04-portable-instruction-engine.md). Next: [native code generation](06-optimization-and-native-backend.md).
## Objective
Replace embedded executable `.zir` with the lowered portable instruction program. Keep `.zx` responsible for executable code, linkage, capabilities, libraries, assets, variants, and inspection metadata. A stripped bundle must run without embedded source or semantic IR.
## Existing integration points
- [Container records and codec](../cmd/compiler_bundle.zi).
- [Bundle linker](../cmd/compiler_link.zi), [bundle implementation](../cmd/compiler_bundle.zi), and [asset handling](../tests/bundle_assets.sh).
- [Bundle command](../cmd/zi2zx/main.c), [package bundle execution](../cmd/package_bundle_run.zi), and [format documentation](../docs/ZX.md).
- [Law checking](../cmd/compiler_law.zi) and [proof checking](../cmd/compiler_proof.zi).
Proposed modules: `cmd/compiler_exec_serial.zi`, `cmd/compiler_exec_link.zi`, and `cmd/compiler_exec_variants.zi`. Evolve the existing container owner instead of adding a competing bundle wrapper.
## Implementation work
- [ ] Define a new incompatible ZX revision with explicit section kinds, lengths, alignment, feature requirements, entry IDs, and deterministic ordering. Choose the revision from the live format history at implementation time.
- [ ] Encode functions, blocks, values, instructions, types, relocatable symbolic constants, imports, exports, global initializers, and data without host pointer values or compiler struct layouts.
Revision 28 already serializes ordered initializer IDs and readonly byte data;
imports/exports, relocatable symbols and the public linked representation keep
this container-wide item open.
- [ ] Separate required execution sections from optional source maps, origins, optimization remarks, and original source attachments. Optional executable `.zir` must never be a hidden execution dependency.
- [ ] Preserve asset streaming and binary bytes, deterministic output, write-to-pipe behavior, and existing error semantics. Validate offset/length arithmetic, overlaps, truncation, unsupported required features, and trailing data rules.
- [ ] Lower then link executable symbols and portable type identities. Handle direct/indirect call roots, callbacks, exported layouts, global initialization, function/data address identity, and dead stripping conservatively.
- [ ] Preserve external libraries, thin/add-on bundles, partial-module composition, and their resolution order. Detect duplicate/conflicting definitions and ABI/layout mismatches before instantiation.
- [ ] Recompute capability requirements from verified reachable instructions. Cross-check declared tables, library bindings, and host signatures rather than trusting producer-supplied manifests.
- [ ] Keep law evidence honest. Either revalidate attached proof material against an adequate non-executable witness or report producer evidence as unverified metadata. A checksum, previous checker flag, or matching law table is not a proof of lowering correctness.
- [ ] Verify the executable itself independently of any optional proof/source section. Certificates for removed bounds checks or other privileged assumptions must be checkable by the consumer; otherwise retain the checks.
- [ ] Define native variant records with target CPU, OS/ABI where relevant, required feature masks, common signature, and deterministic selection precedence. If no declared implementation matches the selected target/CPU contract, reject before execution; do not run portable code as a native fallback.
- [ ] Keep generic executable code mandatory for portable bundles. Store native variants as verifiable target-operation/template metadata, not automatically trusted arbitrary machine-code blobs.
- [ ] Validate variant operands, effects, register clobbers, and boundaries before code generation. Keep feature detection baseline-safe and check OS-enabled register state where required.
- [ ] Define explicit target-only artifacts separately when a producer intentionally requires an architecture. The CLI must report that reduced portability and reject unsupported hosts before executing code.
- [ ] Encode the stable Gap identifiers needed for target preflight and inspection.
Unknown required target features reject; they do not select another executable
section, format revision, or engine.
- [ ] Reject old incompatible bundles with an actionable rebuild diagnostic. Keep legacy-format rejection tests; do not maintain two executable formats indefinitely.
- [ ] Include every executable and variant section in cache/content identity while keeping optional debug-only changes from unnecessarily invalidating machine code where a correct split is possible.
## Tests
Extend the retained bundle checks: [provider cases](../tests/bundle_provider_cases.zi), [executable bundles](../tests/executable_bundle.sh), [global reachability](../tests/bundle_global_reachability.sh), and [step limits](../tests/bundle_step_limit.sh).
Add malformed new-section fixtures, required/optional feature mutations, variant incompatibility tests, stripped-bundle execution, deterministic source/saved-IR bytes, and proof-table tampering. Verify functionally identical portable behavior with supported variants selected, masked out, and unavailable.
## Exit gate
New bundles execute using step 04 without semantic `.zir` bodies. Libraries, assets, state, capabilities, law reporting, and diagnostics retain their defined behavior. Old bundles fail clearly. The writer and reader agree on a documented public instruction/container contract rather than private compiler serialization.
## Handoff
Deliver the binary/text format specification, opcode version policy, golden/mutation fixtures, variant contract, and the new bundler/loader path. Keep the installed default unchanged until step 10's integration gates pass.
@@ -0,0 +1,63 @@
# Step 06 — Optimize executable IR and implement the first native backend
Status: in progress; [verified scalar optimization](optimization-pipeline.md) and the machine-only native encoder ([README.md](README.md)). The [target-neutral machine IR](machine-ir.md) boundary, its verifier, deterministic liveness, linear-scan [register allocation](machine-ir.md#register-allocation) with splitting and spilling, a separate allocated-program verifier, and a [direct x86-64 machine-code encoder](machine-ir.md#machine-code-encoder) for verified allocated programs exist for Linux x86-64 SysV. `zx2native` uses that machine path exclusively; native ZX loading remains open. The implemented native call ABI passes and returns general-register values only: float, vector, aggregate and stack-passed call forms are [unsupported forms](machine-ir.md#supported-call-forms) rejected before encoding, not partially implemented. The full optimizer, the full SysV call ABI and external System V aggregate interoperability remain pending.
Direct native code here means Ziran's machine encoder writes machine code and the ELF executable from verified IR, without generated C, an assembler, a C compiler or a system linker. The C and Go targets also produce runnable binaries, but they are separate generated-code exporters with their own toolchains; they are never a fallback for an unsupported native form ([gap policy](gap-policy.md), [distinction](machine-ir.md#direct-native-code-versus-generated-code-exporters)). Depends on stable contracts from [steps 02](02-lowered-ir-and-verifier.md)–[05](05-zx-format-and-linking.md). Next: [target coverage](07-architecture-and-platform-coverage.md).
## Objective
The `zi2zx` CLI runs verified LIR optimization before writing portable ZX.
Both native entry routes read and verify those bytes before selecting direct
LIR or machine-IR target lowering. `--opt` selects optimized source inspection,
not a second optimization pass on ZX input. `--emit wasm` lowers the same
verified ZX to a wasm32 module, which `ziran build --target=wasm` and the
bundle Wasm tier use. Source/debug origin attachments remain a gap.
Implement a native backend shared by standalone compilation and native ZX execution. Start with Linux x86-64 System V as the first execution milestone, then complete the required target matrix in step 07. A first working return-value executable is not completion of this step.
## Existing integration points
- [Scalar contracts](../cmd/zir/zir_scalar.h), [range-analysis behavior](../cmd/compiler_c_range.zi), and [SIMD behavior](../cmd/compiler_vector_x86.zi).
- [Native planning](../cmd/compiler_machine_elf.zi).
- [Existing Go assembly translator](../cmd/compiler_go_asm_x64.zi) for operand/ABI lessons only; Go ABI0 and its runtime assumptions are not Ziran's native ABI.
- [Native and SIMD tests](../tests/simd_native.sh).
Implemented machine-IR modules: `cmd/compiler_machine_ir.zi`, `cmd/compiler_machine_lower.zi`, `cmd/compiler_machine_verify.zi`, `cmd/compiler_abi.zi` (the only module that names target registers), `cmd/compiler_regalloc.zi`, `cmd/compiler_machine_verify_allocated.zi`, and `cmd/compiler_x86_64.zi` with the shared byte encoders in `cmd/compiler_x86_bytes.zi`. Proposed: `cmd/compiler_opt.zi`.
## Implementation work
- [ ] Add a pass manager with explicit preconditions, preserved analyses, verification hooks, timing/counter collection, and deterministic before/after dumps.
- [ ] Implement constant folding, copy propagation, unreachable-block removal, dead instruction elimination, and CFG simplification with exact numeric/effect semantics.
- [ ] Add range propagation, redundant-check elimination, common subexpression elimination, and conservative load/store optimization. Invalidate facts on aliasing writes and effectful calls.
- [ ] Implement inlining with recursion/growth limits, source-origin chains, and the existing `#inline`/`#cold` meaning. Include cross-module decisions in dependency/cache identities.
- [ ] Add loop optimizations only when arithmetic, aliasing, exit, fuel, and trap conditions permit them. Do not treat signed overflow, float reassociation, or host side effects as compiler conveniences.
- [ ] Lower to target instructions while retaining virtual registers. Model fixed registers, tied operands, condition flags, call clobbers, vector register classes, addressing modes, and literal pools explicitly.
- [x] Implement liveness and a register allocator with splitting/spilling, call-aware live ranges, parallel-copy resolution, and deterministic output. Emit reasons and locations for every spill/reload. ([allocation](machine-ir.md#register-allocation), `tests/regalloc.sh`)
- [x] Verify the allocated program: no overlapping live assignments, missing definitions, broken ties, clobbered live values, invalid register classes, or unresolved parallel copies. It also rejects unimplemented call forms and relocation addends the target cannot hold, so they never reach an encoder; allocation publishes only a verified program and leaves the owner's input intact on any failure.
- [ ] Implement SysV argument/result classification, stack alignment, caller/callee-saved registers, aggregate passing, varargs, callbacks, indirect calls, and externally named symbols.
- [ ] Generate prologues/epilogues, frame layout, unwind information, stack/resource checks, and target-correct returns. Keep source/inline locations through all inserted instructions.
- [ ] Implement baseline scalar integer/float instruction selection first, then every required SIMD lane operation and supported CPU variant. Preserve a runnable baseline when optional features are unavailable.
- [ ] Integrate typed native assembly operands and clobbers with allocation. Implement the supported GNU template/constraint surface or issue explicit unsupported-form diagnostics; never drop a selected assembly block silently.
- [ ] Give separately selected portable and native implementations identical external semantics. Validate result/operand layouts; do not assume that an annotated template is proved equivalent merely because another body is checked. A missing native variant is a Gap error, not permission to execute the portable implementation.
- [ ] Implement runtime calls and parallel-region helpers through the same typed ABI machinery, with stable entry points for the native engine.
## Tests
Add independent native-backend fixtures for register pressure, spills across calls, fixed-register division/shifts, flags, cyclic copies, float edge cases, stack alignment, aggregate ABI classes, varargs, and C callbacks.
Current machine-IR local tests: `tests/machine_ir_cases.zi` covers lowering, ABI constraints and malformed-MIR rejection. `tests/x86_encoder_cases.zi` covers exact encoded bytes, relocations, fuel and traps, and rejection of unsupported float and stack call forms and out-of-range global-address addends. `tests/regalloc.sh` covers allocation, the allocated verifier, incoming-argument order, and late failures that leave the owner's program intact. They use `--target=c` only to run the test programs.
Compare optimized/unoptimized new-native output with the portable instruction engine and existing C execution. Use external handwritten C/assembly ABI fixtures as independent callers/callees where practical. Inspect actual encoded instructions after step 08; text snapshots alone cannot validate encoding or execution.
Run all builds through `build-queue --`. Performance measurements occur only
directly on Alpha's physical host, with raw samples and the repository's
symmetric 1.5×IQR rule. Reject virtualization and leave measurements pending
when Alpha is unavailable rather than substituting another host.
## Exit gate
All required Linux x86-64 feature cells execute with the new backend. Debug/release, source/saved IR, standalone/native ZX entry adapters, callbacks, SIMD, and spill-heavy code agree with their independent expectations. Optimization diagnostics identify which pass changed code and why. Any remaining provisional assembler/linker dependency is explicitly temporary until step 08.
## Handoff
Deliver shared machine/ABI interfaces, the complete first-target implementation, allocation verifier, target fixture corpus, and optimization remarks. Freeze common backend contracts before parallel target implementation to avoid competing register/ABI models.
@@ -0,0 +1,146 @@
# Step 07 — Complete architecture, ABI, and platform coverage
Status: planned. Depends on [step 06](06-optimization-and-native-backend.md). Coordinates with [encoding/linking](08-assembler-objects-and-linker.md) and [runtime integration](09-native-runtime-and-integration.md).
## Objective
Run one portable executable program across the maintained platform matrix while allowing explicit CPU variants. Match existing promised coverage rather than declaring a Linux-only backend to be the completed ZX upgrade.
## Existing integration points
- [Wasm lowering of verified ZX](../cmd/compiler_zx_wasm.zi) and [wasm bundle integration](../cmd/zir/zir_zx_wasm.c).
- [Browser execution integration](../cmd/zir/zir_zx_wasm_web.c).
- [Target diagnostics](../tests/target_diagnostics.sh), [ARM/CPU feature tests](../tests/assembly_features.sh), and [wasm tests](../tests/zx_wasm.sh).
- [Platform and runtime coverage documentation](../docs/IMPLEMENTATION_STATUS.md).
Proposed modules: `cmd/compiler_target.zi`, `cmd/compiler_aarch64.zi`, `cmd/compiler_arm.zi`, `cmd/compiler_wasm.zi`, and platform-specific ABI modules under `cmd/`. Keep target tables explicit and dynamically sized where appropriate.
## Implementation work
- [ ] Establish exact target triples, pointer widths, endianness, data models, object formats, stack rules, symbol rules, and feature baselines from the step-01 matrix.
- [ ] Implement AArch64 instruction selection, calling conventions, stack frames, relocatable addresses, NEON operations, literal placement, branch ranges, and platform-reserved registers.
- [ ] Implement the maintained 32-bit ARM target: ARM/Thumb policy, instruction availability, 64-bit scalar operations, soft/hard-float ABI distinctions, alignment, NEON variants, interworking, and veneers.
- [ ] Complete x86-64 Windows and macOS ABI differences, including Windows shadow space/unwind requirements and platform-specific symbol/TLS/layout rules. Include additional x86 platform rows only where the matrix requires them.
- [ ] Complete Apple ARM64 rules, Android ABI/API requirements, TLS, dynamic loading, instruction-cache synchronization, and platform limits on executable memory.
- [ ] Add required 32-bit x86 support if current maintained targets promise it; do not hide a missing target behind the x86-64 implementation. New RISC-V support is separately scoped unless explicitly included in step 01.
- [ ] Lower the same portable IR directly to WebAssembly instructions, function tables, structured control flow, data, imports, and exports. Preserve numeric traps/conversions and the declared memory model at the wasm boundary.
- [ ] Support browser AOT generation and the portable instruction engine when runtime native compilation is unavailable. Do not keep generated C/Emscripten as the hidden code generator for the new ZX instruction path.
- [ ] Implement baseline and optional SIMD modes, including legal wider-vector decomposition. Match lane results with the portable engine; explicit native variants select only on compatible CPUs/OS state.
- [ ] Centralize feature discovery and target requirement matching. Cross-compilation must use the requested target description, never the build machine's CPU flags.
- [ ] Keep OS APIs in typed host capabilities or native foreign adapters. A Windows/Linux/macOS service binding is distinct from AVX/NEON instruction availability.
- [ ] Define exact failures for absent host facilities, unavailable executable memory, missing CPU requirements, unsupported native extensions, and unavailable platform toolchains.
- [ ] Supply unwind/debug mappings and profiler registration hooks for every native target, not just Linux x86-64.
## Target registry and preflight
[`cmd/compiler_target.zi`](../cmd/compiler_target.zi) holds the registry: one
row for every CPU/OS pair `TargetDescribe` accepts, each with exactly one
gap-policy state, its implemented CPU features and OS services, and the
milestone that closes it. `TargetPreflight` checks a target description and
its `TargetRequirements` (CPU features, OS services) against that row; only an
Implemented row passes. `ziran capabilities --json` prints the registry as
`assembly_targets`, and `ziran capabilities --assembly-target=ROW[+FEATURE...]
[--os-service=NAME]... [INPUT...]` runs the preflight before any input is read.
| Row | ABI | State | Diagnostic | Milestone |
| --- | --- | --- | --- | --- |
| `x86_64-linux` | SysV | Gap | `assembly.gap.target-unimplemented` | M2–M3 |
| `x86_64-android` | SysV | Gap | `assembly.gap.target-unimplemented` | M4 |
| `x86_64-windows` | Win64 (kernel32 boundary only) | Gap | `assembly.gap.target-unimplemented` | M5 |
| `x86_64-macos` | Apple64 | Gap | `assembly.gap.target-unimplemented` | M5 |
| `armv7-linux`, `armv7-android` | AAPCS32 | Gap | `assembly.gap.target-unimplemented` | M4 |
| `aarch64-linux`, `aarch64-android` | AAPCS64 | Gap | `assembly.gap.target-unimplemented` | M4 |
| `aarch64-windows` | Win64 | Gap | `assembly.gap.target-unimplemented` | M5 |
| `aarch64-macos` | Apple64 | Gap | `assembly.gap.target-unimplemented` | M5 |
| `wasm32-browser`, `wasm32-wasi` | Wasm | Gap | `assembly.gap.target-unimplemented` | M4 |
No general registry row is Implemented yet. Linux x86-64 machine IR,
allocation, encoding and opt-in ELF output exist, but the native ZX loader and
runtime cutover are open, so that row stays a Gap until its M2–M3 gate passes; a partial stage
such as `TargetMachineLoweringSupported` never implements a row. The
`zx2native --target ARCH --platform OS`
selector implements the rows whose registry entry names an `executable`
container: `x86_64-linux` writes an ELF and `x86_64-windows` a PE32+ `.exe`
([`compiler_machine_pe.zi`](../cmd/compiler_machine_pe.zi)). A Linux
registration may also name an `ar(1)` archive of ELF64 x86-64 objects; the
executable links the members its capabilities reach and stays static
([`compiler_x86_archive.zi`](../cmd/compiler_x86_archive.zi)), and anything
outside that subset is `assembly.gap.machine-archive` naming the capability,
member and symbol. Both carry the
same text, constants and data
([`compiler_x86_image.zi`](../cmd/compiler_x86_image.zi)) and runtime
([`compiler_x86_runtime.zi`](../cmd/compiler_x86_runtime.zi)), whose only
per-OS parts are its primitives: Linux system calls, or kernel32 calls through
the image's IAT with Win64 shadow space, 16-byte alignment and volatile
registers ([`compiler_x86_win64.zi`](../cmd/compiler_x86_win64.zi)). Code
inside the program keeps the Ziran-internal convention on both. The PE imports
only what its runtime calls, is DYNAMIC_BASE/HIGH_ENTROPY_VA with base
relocations for the pointer runtime's addresses and NX_COMPAT, and commits an
8 MiB stack, so frames need no probes; every function with a prologue carries
x64 unwind data (.pdata and .xdata), and a console gets each line once it ends
where a redirected descriptor gets whole buffers. Both images also supply the
ZX Runner's file and clock services themselves
([`compiler_x86_host.zi`](../cmd/compiler_x86_host.zi)): a program that imports
`FileStatusHost`, `FileReadHost`, `FileWriteHost`, `FileRemoveHost`,
`FileRenameHost`, `DirectoryMakeHost`, `DirectoryListHost`,
`MonotonicNanosecondsHost` or `WallMillisecondsHost` with the signatures
`std/guest_files.zi` and `std/guest_clock.zi` declare gets a veneer after the
library ones instead of a host-capability gap. The linker keeps these apart
from library imports, so the ELF stays static and the PE imports only what its
veneers call. Linux veneers make the system calls directly with the path in a
4 KiB stack slot; Windows veneers widen UTF-8 paths to UTF-16 with
`MultiByteToWideChar`, convert listed names back with `WideCharToMultiByte`,
and import `GetFileAttributesExW`, `CreateFileW`, `ReadFile`, `WriteFile`,
`DeleteFileW`, `MoveFileExW`, `CreateDirectoryW`, `FindFirstFileW`,
`FindNextFileW`, `FindClose`, `QueryPerformanceCounter`,
`QueryPerformanceFrequency` and `GetSystemTimeAsFileTime` as needed. A read
or a listing grows a heap block through the runtime's resize entry, at least
doubling it, and shrinks it to the final length; the block stays allocated.
The built-in veneers carry no unwind records, since the unwind writer covers
the program's own functions only. Every other described row
fails before input/output with
`assembly.gap.machine-platform-service-unavailable` because it has no
executable writer or process-entry/`write_all`/exit runtime. Once a registry row
is Implemented, a CPU feature it does not implement (including another
family's, such as `neon` on x86-64) fails with `assembly.gap.cpu-feature`,
and a missing OS service (`process-entry`, `executable-memory`, `threads`,
`files`, `clock`, `dynamic-library`) fails with `assembly.gap.os-service`;
the row check comes first. Typed host capabilities and read-only data keep
their own `assembly.gap.*` codes. General registry preflight is reached through
`ziran capabilities`.
[Target diagnostics](../tests/target_diagnostics.sh) check every row, code,
and source/saved-IR rejection; [machine IR cases](../tests/machine_ir_cases.zi)
check registry coverage and every state.
## Execution matrix and tests
For every required CPU/OS/ABI row, record:
| Evidence | Required outcome |
| --- | --- |
| Source and saved `.zir` | Equivalent lowered instructions and behavior |
| Same portable `.zx` bytes | Successful supported execution across applicable hosts |
| Native AOT | Real executable launch, correct ABI interactions, expected results |
| Native ZX or documented interpreter-only host | Correct loader/capability/state behavior |
| CPU features enabled and masked | Correct declared-variant dispatch; stable preflight error when no implementation matches |
| Debug/unwind/profile data | Correct function and source attribution |
| Negative target cases | Clear diagnostics before invalid execution |
Run semantic tests under emulation when useful and on real hardware where ABI, OS integration, or CPU feature behavior requires it. Test phones on the owner-authorized USB Moto; preserve Wireless Debugging. GUI tests use private displays and only their own processes.
Emulation, cross-compilation, a lower-feature implementation, or another engine
does not close the selected target/feature cell. Missing target hardware leaves
the cell Unknown; missing implementation leaves it Gap.
Benchmarks run directly on Alpha's physical host only; the runner rejects
virtualization. Emulated correctness results are not native performance
measurements. If a required host is unavailable, retain its matrix cells as
incomplete rather than reporting 100% coverage.
## Exit gate
Every required row has execution evidence and every opcode has either correct target lowering or a documented portable implementation. The same portable bundle does not require platform-specific rebuilding to execute its baseline behavior. Platform-specific variants and capabilities remain explicit.
## Handoff
Deliver target tables, ABI/encoding requirements, cross-platform fixtures, hardware limitations, and execution receipts to steps 08–10. Do not infer a platform passed merely because another platform uses the same CPU family.
@@ -0,0 +1,50 @@
# Step 08 — Encode instructions, write objects, and link executables directly
Status: in progress; [direct Linux x86-64 ELF with scalar/aggregate code and static data](README.md). Relocatable objects and a general native linker remain pending. Depends on machine/target contracts from [steps 06](06-optimization-and-native-backend.md) and [07](07-architecture-and-platform-coverage.md).
## Objective
Complete the path from allocated machine instructions to native binaries without generated C, an external assembler, or an external linker on required targets. Keep optional external-tool comparison modes for validation, not as an undeclared dependency of the promised direct build.
## Existing integration points
- [Current C executable driver](../cmd/zi2c/main.c) and [build orchestration](../cmd/compiler_c_backend.zi) provide entry, diagnostics, cache, and failure-preservation behavior to retain.
- [Native entry tests](../tests/native_entry.sh) and [link-flag tests](../tests/native_link_flags_cases.zi) provide existing executable/FFI expectations.
- [Build rules](../Makefile) and [native runtime build selection](../assembly.mk).
Proposed modules: `cmd/compiler_encode_x86.zi`, `cmd/compiler_encode_arm.zi`, `cmd/compiler_encode_aarch64.zi`, `cmd/compiler_object.zi`, `cmd/compiler_elf.zi`, `cmd/compiler_coff.zi`, `cmd/compiler_macho.zi`, `cmd/compiler_link_native.zi`, and `cmd/compiler_disassemble.zi`.
## Implementation work
- [ ] Implement instruction encoding for every emitted opcode and addressing form, including immediate widths, extension prefixes, branch displacement, vector encodings, and target feature validation.
- [ ] Define symbolic fixups independently of object format. Resolve local labels, literal pools, branch relaxation, long-branch veneers, alignment, and padding to a stable final layout.
- [ ] Print assembly directly from the same allocated/finalized instruction records used by the encoder. Annotate function, source origin, bytes, CPU requirements, stack offsets, and generated instructions.
- [ ] Provide a reader for the emitted textual listing that reconstructs its supported instruction/directive subset. This enables round-trip inspection without requiring text parsing during ordinary compilation. Do not silently imply support for every external assembler dialect.
- [ ] Keep existing user `#asm` syntax support a separate compatibility task: parse and bind the supported templates and constraints, including labels/directives where allowed. On the direct assembly target, require a matching declared target/feature implementation and issue a stable diagnostic when absent; do not execute the portable body or invoke another backend.
- [ ] Write relocatable ELF, COFF, and Mach-O objects for required rows. Include text/data/readonly/BSS/TLS sections, symbols, visibility, alignment, relocations, unwind records, and debug references.
- [ ] Implement archive reading and symbol extraction, COMDAT/coalescing rules where required, weak symbols, unresolved references, duplicate definitions, section garbage collection, and retained exports/callback roots. Landed slice: a `NAME.library` registration may name an `ar(1)` archive of ELF64 x86-64 objects ([`compiler_x86_archive.zi`](../cmd/compiler_x86_archive.zi)); the reached members' text, read-only data, writable data, zero fill, GOT entries and relocations go into the static Linux ELF and each capability's veneer calls its member directly. Anything outside that subset (TLS, `init_array`, an undefined or duplicate symbol, an unsupported relocation) is the stable `assembly.gap.machine-archive` diagnostic naming the capability, the member and the symbol.
- [ ] Link supported executable/shared-object forms: ELF program headers and dynamic records, PE imports/exports and relocation tables, and Mach-O load commands/fixups as required by the maintained targets.
- [ ] Implement startup/entry handling and runtime helper linkage for console programs and libraries. Preserve command arguments, exit status, global initialization, thread/runtime setup, and foreign callbacks.
- [ ] Resolve ordinary OS and third-party libraries through explicit target search paths and format-aware symbol handling. Existing compiled foreign libraries are valid inputs; compiling their C sources is outside Ziran code generation.
- [ ] Inventory C-compiler-driver conveniences previously supplied by `CC`: CRT selection, sysroot, libc, dynamic loader, TLS, compiler support routines, and default libraries. Replace each with explicit native driver configuration and diagnostics.
- [ ] Define the supported native link-option surface. Preserve C-target pass-through options on the C backend; reject options that have no new-native equivalent instead of ignoring them.
- [ ] Implement platform-required executable authentication/signing integration where needed for a runnable artifact. Use installed OS signing facilities and explicit credentials; do not claim that a written Mach-O/PE file alone proves launchability.
- [ ] Write outputs atomically, preserving the last valid executable on failure. Cache object contributions using target, ABI, backend, flags, dependencies, and runtime identities.
- [ ] Produce relocation/link maps, section sizes, resolved symbol addresses, inserted stubs, padding, and a source-linked disassembly from actual final bytes.
- [ ] Expose the same encoder and relocation primitives to the in-memory loader in step 09; do not create an unrelated JIT instruction encoder.
## Tests
Add Ziran encoding/object/linker test programs. Compare individual instruction bytes against an independent assembler/disassembler; test boundary immediates, all register forms, branch expansion, relocation overflow, and malformed input objects.
Round-trip the supported listing form through parsing/encoding and compare resulting sections and fixups. Link new-native objects with independently compiled C callers/callees and, where useful, the system linker as a reference. Then run the fully internal link path with external C compiler, assembler, and linker commands unavailable.
Exercise executable launch, dynamic imports, TLS, callbacks, shared libraries, debug/unwind loading, missing symbols, archive ordering, failed writes, and preservation of installed outputs on each required OS. Run all builds through `build-queue --`; use private display fixtures where needed.
## Exit gate
Required standalone builds produce runnable binaries using the internal code generator, encoder, object writer, and linker. Listings match the encoded instruction stream; final disassembly accounts for linker-added code. No external-tool or alternate-engine fallback exists on the direct path; a missing internal facility is a visible Gap.
## Handoff
Deliver encoded-image APIs, relocations, link maps, independent byte/ABI fixtures, platform signing requirements, and final byte-to-source mappings to steps 09–10.
@@ -0,0 +1,138 @@
# Step 09 — Integrate native ZX execution, AOT builds, caching, and hosts
Status: in progress. Linux x86-64 has an AOT slice and native ZX loading,
and Linux AArch64, Android included, has native ZX loading; `ziran run
app.zx` and the embedding API use it by default on those rows,
with the engine's pointer checks; a persistent code cache, the element-type
check on pointer access and the remaining targets are still planned. The current startup/syscall work is not a completion claim. Depends on
[steps 04](04-portable-instruction-engine.md)–[08](08-assembler-objects-and-linker.md).
Next: [inspection and final cutover](10-inspection-performance-and-cutover.md).
## Objective
Run `.zx` through the explicitly selected shared native backend or explicitly
selected new instruction interpreter. Integrate source builds, packages,
libraries, hosts, cache, and embedding APIs without relying on generated C for
new-native code generation and without switching engines after a gap is found.
The experimental pipeline is source → `.zir` → linked LIR → verify →
LIR optimization → portable ZX bytes → verified read, followed by either the portable interpreter or direct target
lowering to a platform binary. Generated C and Go routes can also produce
binaries through their own toolchains, but they are not native here and cannot
substitute for the direct route.
Host capabilities remain portable typed interfaces. Each direct target owns
separate ABI veneers for entry, calls, operating-system services, and exit. The
initial Linux x86-64 console contract uses a static executable with its own
`_start`, no libc/CRT/dynamic linker, `write` syscall 1 through a `write_all`
loop that handles partial progress and `EINTR`, and `exit_group` syscall 231
rather than syscall 60. That opt-in AOT slice is implemented and executed.
A program that calls host capabilities links them instead from registered host
libraries by name: PT_INTERP and PT_DYNAMIC name the system dynamic linker and
each library, one System V veneer per capability
([`compiler_x86_host.zi`](../cmd/compiler_x86_host.zi)) calls through the slot
its GLOB_DAT relocation fills, and the process entry, console and exit stay
Ziran's own.
Standard output is buffered, 8 KiB at a time and line by line on a terminal as
in C, and written before any write to another descriptor, before a trap's exit
and at exit, so its bytes and their order match direct writes. Its resize runtime, emitted with the x86 encoder
([`compiler_x86_runtime.zi`](../cmd/compiler_x86_runtime.zi)), recycles freed
blocks through power-of-two size classes instead of mapping and unmapping each
growth; a block over 1 MiB is its own mapping and grows by `mremap`.
Native ZX loading on linux-x86_64, linux-aarch64 and linux-armv7
([`zir_host_native.c`](../cmd/zir/zir_host_native.c), with each architecture's
veneers and relocation fields in `zir_host_native_<arch>.c`; ARMv7's also
hold the 64-bit divide and int64/float conversion helpers A32 lacks)
compiles the bundle's verified program with the same machine pipeline, copies
the image into RW pages, resolves its relocations against the instance's own
data, host veneers, trap stub and resize runtime, and only then makes the code
RX; no mapping is ever writable and executable. Compiled code is shared by
open bundles of the same content digest on the same CPU and kept briefly
after the last closes. Each instance owns its globals, fuel counter, stack
limit and resizable storage. A trap returns through `longjmp`, prints a
`zx.runtime` diagnostic naming the function, block and (with a debug
attachment) source line, and ends that instance; nothing restarts on the
engine.
With checks on, native data pointers are checked as the engine checks them
(checks are opt-in with `#checks`). A pointer is a
token naming a slot of the instance's pointer table, version and offset; every
load, store, byte comparison and platform-service argument resolves it
against a live slot of the same version, within its size and, for writes,
writable. Each run of `allocate` takes fresh zeroed bytes from the frame arena
under a slot on the frame's chain, and `Return` ends the chain and gives the
arena back. `resize` ends the old block's slot once the runtime has moved or
freed it; a request that does not fit gives null and keeps the old block.
Globals are slots 1..G, read-only ones without the writable flag. The host
bridge resolves the views it copies and gives returned views read-only slots.
The engine also checks a pointer's element type on each access; native code
does not yet.
`ziran build FILE.zi` composes `zi2zx` and `zx2native`, so source-native output
serializes and reads the same ZX image as direct `zx2native`; neither route
lowers source-side LIR directly. The required payload is stripped of source
origins; `zi2zx --debug` writes them to the optional debug attachment, bound
to the program section's identity, and `zx2native --emit map` names source
lines from it without changing a byte of the executable. Bundles and the
bundle Wasm tier use this shared instruction route.
For literal-only hello, direct instruction selection emits no stack frame or
spill slots, uses short constants, and writes the literal from read-only data.
The ELF file places `.rodata` immediately after `.text`, with congruent file
offsets and virtual addresses on distinct RX/R pages, and carries `.data` only
as a zero-length section header when no writable storage exists. `_start` and
each function's symbol retain positive bounded text extents;
inlined platform service declarations are omitted from the symbol table,
so the static executable has no undefined symbols or misleading trap aliases.
## Existing integration points
- [Embedding API](../include/ziran_host.h), [bundle lifecycle](../cmd/zir/zir_host.c) and the [engine bridge](../cmd/zir/zir_host_exec.c), which translates host values for the [portable instruction engine](../cmd/compiler_exec.zi) and for the [native ZX loader](../cmd/zir/zir_host_native.c).
- [Wasm lowering](../cmd/compiler_zx_wasm.zi) and [browser integration](../cmd/zir/zir_zx_wasm_web.c).
- [Package entry](../cmd/package_entry.zi), [options](../cmd/package_options.zi), [bundle run](../cmd/package_bundle_run.zi), and [capability reporting](../cmd/package_capabilities.zi).
Proposed modules: `cmd/compiler_native_load.zi`, `cmd/compiler_native_cache.zi`, `cmd/compiler_exec_instance.zi`, and a native backend command entry integrated into the existing package driver.
## Implementation work
- [ ] Expose one compile API taking verified executable IR, target description, optimization policy, and runtime ABI. AOT objects and in-memory images differ in output handling, not instruction semantics.
- [ ] Implement in-memory layout, symbol resolution, relocations, executable-memory allocation, write/execute transitions, instruction-cache synchronization, unwind registration, and teardown for supported platforms.
- [ ] Do not trust persisted executable bytes solely because a neighboring metadata file claims they were verified. Define cache integrity, ownership, atomic installation, invalidation, and refusal behavior explicitly.
- [ ] Key cache entries by executable content, linked libraries, target/ABI, actual selected CPU features, backend/runtime identities, optimization settings, and instrumentation semantics. Keep mutable instance state outside cached code.
- [ ] Preserve concurrent compilation, concurrent instantiation, nested calls, independent globals, reentrant host capabilities, cancellation, failures, and lifecycle retirement. Cache cleanup must not unload code still referenced by a live instance.
- [ ] Implement typed host trampolines using the shared ABI layer. Preserve aggregate/string/slice/function signatures, checked host returns, error propagation, and callback roots.
- [x] Implement and verify the first target-owned console ABI veneer for the
opt-in Linux x86-64 AOT path. Its Ziran-owned formatter accepts literal
format strings, strings/text views, booleans, every fixed signed and unsigned
integer width, and `%%`; `write_all` retries partial progress and `EINTR`.
Floating-point formatting and every unavailable target service remain stable
named gaps. Other target rows remain unchecked.
- [ ] Preserve execution budgets, stack checks, source-aware traps, parallel workers, persistent state, migration, snapshots, and module/library initialization across native and interpreted modes.
- [ ] Make the engine-selection contract explicit. A native request fails
clearly if unsupported and never starts the interpreter. A portable request
never executes native code. A command may have one documented default, but
preflight failure never changes that selection.
- [ ] Add direct-native build/run targets to the package driver and target capability reports. Keep existing C/Go/wasm commands and legitimate target-specific bindings usable.
- [ ] Integrate package dependency recipes, native artifact caching, sysroots, host providers, assets, executable entries, libraries, install paths, and incremental rebuild dependencies.
- [x] Replace the browser's generated-C bundle compilation path with direct wasm output from the same portable IR. Interpreter execution remains an explicit separate mode where browser/runtime policy permits it, never a direct-Wasm fallback.
- [ ] Build runtime helpers through the new backend and verify self-hosting of the new compiler modules. Retain the established bootstrap mechanism; regeneration must be deterministic and locally checked.
- [x] Remove TinyCC and generated-C dependencies from the new native ZX path after their replacement tests pass. Remove build/library dependencies only when no other maintained consumer needs them. TinyCC, the generated-C ZX route and `libziran-vm.a` are gone.
- [x] Reconcile embedding API changes deliberately. Preserve semantic contracts, update callers through their owning projects, and reject retired entry points where repository policy requires a clean cutover. `BundleUsePortableVm` and `BundleInstantiatePortable` are deleted; Kryon calls neither.
- [ ] Verify installation from the current working tree at the stable executable path. Do not require a commit first, replace the owner's running application, or produce alternate task-specific binaries.
## Tests
Extend [native run](../tests/native_run.sh), [portable entry](../tests/portable_entry.sh), [bundle providers](../tests/bundle_provider_cases.zi), [cache tests](../tests/native_cache.sh), [object reuse](../tests/native_object_reuse_cases.zi), [build concurrency](../tests/native_cache_parallel.sh), [browser lifecycle](../tests/zx_web_lifecycle.sh), and [install tests](../tests/install_user_cases.zi).
Add cold/warm cache correctness, interrupted writes, incompatible CPU cache reuse, stale runtime ABI, corrupted entries, load/unload races, nested host callbacks, parallel failure, and mutable-state separation. Test from stripped bundles with no C compiler available. Run independent native AOT and native ZX instances against the same fixture expectations.
Use the full native local stack. All builds go through `build-queue --`; tests remove inherited display variables or use private displays. Dedicated performance measurement belongs on Alpha, not the desktop.
## Exit gate
The new-native standalone and ZX paths share code generation and encoding, all required hosts/packages work, cold/warm execution is correct, and current-tree installation is verified. No AST, generated-C or interpreter fallback remains on a path advertised as the new native engine. Every required downstream gap has a stable error and remains incomplete until implemented and executed.
## Handoff
Deliver API/CLI behavior, cache/runtime identities, lifecycle tests, package/host integration evidence, installed-path verification, and remaining platform limitations for final inspection and cutover.
@@ -0,0 +1,70 @@
# Step 10 — Complete inspectability, validate performance, and cut over
Status: in progress; [lowered instruction dumps, optimization counters and bounded native byte-range maps](README.md). Complete pipeline inspection, profiling, performance validation and cutover remain pending. Depends on all preceding steps. This is the only step that may declare the complete upgrade finished.
## Objective
Make bottlenecks traceable from source to executed instructions, validate the complete feature/platform matrix, replace the old ZX execution contract, and install the locally verified toolchain. Inspection functionality is developed alongside steps 02–09; it is not postponed until this final gate.
## Existing integration points
- [Inspection command](../cmd/inspect.zi), [compiler profiling](../cmd/zir/zir_profile.h), and [package explain](../cmd/package_explain.zi).
- [Compiler command](../cmd/package_entry.zi), [compile-command reporting](../cmd/package_compile_commands.zi), and [feature reporting](../cmd/package_features.zi).
- [Check discovery](../tests/check_plan.zi), [build/test rules](../Makefile), and [benchmark instructions](../bench/README.md).
- [Architecture](../docs/ARCHITECTURE.md), [ZIR](../docs/ZIR.md), [ZX](../docs/ZX.md), [usage](../docs/USAGE.md), and [implementation status](../docs/IMPLEMENTATION_STATUS.md).
Proposed modules: `cmd/compiler_inspect_exec.zi`, `cmd/compiler_debug_map.zi`, and `cmd/compiler_profile_native.zi`. Final CLI spellings are implementation decisions; document them as proposed until they actually exist.
## Inspectability deliverables
- [ ] Provide deterministic dumps for ZIR, initial portable IR, optimized portable IR, selected machine IR, allocated machine IR, assembly, object metadata, link map, and final executable disassembly.
- [ ] Map source spans and inline/generic origin chains to instructions, addresses, symbols, and stack locations. Preserve many-to-many mappings when optimization combines or duplicates operations.
- [ ] Explain eliminated checks, folded expressions, inlining decisions, missed vectorization, dispatch selection, spills/reloads, frame sizes, call sites, and linker-generated stubs/padding.
- [ ] Produce human-readable output and structured JSON for each stage. Large programs support bounded function/block/address selection; tools must not require dumping an entire binary to inspect one function.
- [ ] Keep assembly/listing output tied to the actual encoder and final disassembly tied to actual bytes, including relocated addresses. Label estimated costs separately from measured costs.
- [ ] Generate source/line and unwind metadata suitable for platform debuggers and profilers. Register JIT functions and address ranges where supported, unregister on retirement, and keep sampled addresses attributable after code moves/unloads.
- [ ] On Linux, integrate available `perf`/JIT symbol-map facilities; supply the corresponding supported mechanisms on other maintained platforms. Record missing hardware counters explicitly rather than fabricating cycle data.
- [ ] Attribute samples to functions, instructions, inline frames, CPU variants, and host bridges. Report hot-path execution, spills, cache/branch evidence, and host-call overhead only when measured data supports the claim.
- [ ] Make stripped and debug artifacts share an explicit build identity and compatible sidecar maps. Inspection output must state the code identity, target, variant, optimization policy, and whether addresses describe AOT or loaded code.
## Correctness and integration closure
- [ ] Close every required cell in the step-01 matrix with fresh real execution evidence. Keep target-specific exclusions distinct from missing implementation.
- [ ] Verify the [gap policy](gap-policy.md): every remaining Gap has a stable
diagnostic and no side effects; capability and inspection output expose it;
no fallback, downgrade, skip, emulation or legacy engine is counted as support.
- [ ] Run source/saved-IR/new-ZX, optimized/unoptimized, AOT/native-ZX/interpreter, optional variants, foreign ABI, callbacks, concurrency, assets, libraries, persistence, and malformed-input suites.
- [ ] Run every retained local test with `make check` and `make check-bootstrap`. Do not substitute filtering, sharding or the retired `make check-full` workflow for the repository's physically pruned suite.
- [ ] Run sanitizer/fuzz/resource-bound campaigns against new decoders, verifiers, object readers, loaders, and instruction execution. Store minimized cases as Ziran fixtures and fix relevant failures.
- [ ] Verify new-backend self-hosting and bootstrap reproducibility, standalone output without external compilation/link tools, browser wasm execution, and supported downstream hosts on the full local stack.
- [x] Confirm old-format rejection and retire old ZX-specific AST execution and C/TinyCC generation only after replacements pass. Preserve compile-time/law tooling evaluators and optional C/Go backends still in use. A file of another revision is rejected with no fallback reader; the semantic bundle writer and reader, the portable VM, bundle libraries and the TinyCC ZX route are removed.
Run every build and compiling test through `build-queue --`; remove `DISPLAY` and `WAYLAND_DISPLAY` unless a private display fixture supplies them. Missing target hardware or local integration dependencies are blockers to their completion cells, never a reason to substitute a CI promise.
## Performance acceptance
- [ ] Define workload-specific regression budgets before measuring. Cover arithmetic, branch-heavy loops, records/arrays, strings, calls, register pressure, SIMD/codec kernels, parallel regions, host crossings, cold compile/startup, warm-cache startup, memory use, and binary size.
- [ ] Benchmark only on Alpha's physical host directly, rejecting
virtualization and preserving the actual host, CPU/OS features, toolchain
identities, flags, workload inputs, selected engine, and output correctness.
If Alpha is unavailable, leave performance verification pending.
- [ ] Compare new-native AOT and native ZX with the M0 receipts of the removed TinyCC path, portable instruction execution, and independent C/Go controls where meaningful. Compare matched semantics, safety checks, and feature levels.
- [ ] Retain all raw samples and excluded indices. Apply the same symmetric 1.5×IQR rule with inclusive interpolated quartiles to every target/platform comparison.
- [ ] Investigate regressions using source-linked final disassembly and measured profiles. Fix common lowering/allocation/runtime causes before adding workload-specific instruction cases.
- [ ] Report gains and losses by workload. Do not replace missing measurements with an “absolute fastest” claim or confuse cross-compilation with benchmark execution.
- [ ] Deliver the owner's requested full before/after ZX comparison when the implementation is finished: old portable VM and old C/TinyCC-native ZX against the new portable instruction engine and new-native ZX, plus direct AOT and matched C/Go/Wasm controls where supported. Show absolute timings, speedup/slowdown ratios, cold compilation and startup, warm-cache startup, warm throughput, memory use, generated code/bundle size, raw samples, excluded indices, and named missing measurements. The old engines are removed, so their before measurements are the receipts and correctness oracles captured on Alpha at [milestone](milestones.md) M0; historical results from a different host or workload are not the before measurement. Interim comparison 1 followed M1, and interim comparison 2 follows M3; this final report supersedes them.
## Documentation, installation, and publication
- [ ] Update format/opcode specifications, language/native target boundaries, capability reporting, CLI help, embedding API docs, error guides, and inspection examples.
- [ ] Update `CHANGELOG.md` under `Unreleased`. Regenerate affected documentation/site outputs through existing scripts; translate touched locale content where applicable.
- [x] Install from the current working tree at the stable path and verify the installed tool can compile, inspect, and run representative new-format programs. Do not terminate the owner's running applications. Done on Omega on 2026-11-15 with `make install-user` from the working tree. The installed `ziran` runs the examples, and `ziran bundle` writes revision-28 `.zx`. `zi2zx --emit lir` and `zx2native --emit map` inspect it. `ziran run app.zx` executes it natively: a bounds trap reports "native execution failed", where `--backend engine` reports "portable execution failed", and its `zx2native` ELF exits with 125. The local receipt is `build/check-logs/m3-installed-tool-2026-11-15.txt`.
- [ ] Keep implementation uncommitted until the complete feature set and meaningful required local tests pass. Missing required verification leaves the work uncommitted.
- [ ] Follow the owner's applicable commit/push authority at implementation time, preserving unrelated work. A release/version bump/tag requires an explicit release request and the existing version workflow.
- [ ] If pushed under applicable authority, report “pushed, CI not checked yet” without waiting for or polling CI. Website publication follows the existing GitHub workflow only; verify deployment separately when it is actually requested/performed.
## Final exit gate and completion receipt
All ten steps are complete only when the portable instruction format, reference engine, complete required native target matrix, internal encoders/linkers, native ZX runtime, inspection/profiling surfaces, self-hosting, and installation have executed successfully under their required tests. Any Gap, Unknown, fallback, downgrade, skip, emulated substitute, or legacy-engine substitute keeps the corresponding gate open. Record exact remaining limitations instead of rounding partial coverage to 100%.
The final receipt names changed components, local test coverage, benchmark host/results, target execution coverage, installed behavior, and independently confirmed commit/push/release/deployment states. A successful build, commit, or agent handoff alone is not a completion receipt.
+353
View File
@@ -0,0 +1,353 @@
# Direct assembly implementation
## State
The upgrade is not finished: the M4-M6 rows are open work in
[plans/open-work.md](../plans/open-work.md). `zi2zx` lowers checked source or
saved `.zir` to verified, typed SSA, and `zx2native` directly encodes a Linux x86-64 ELF
executable. Every `.zx` is the [revision-28 executable
container](zx-executable-format.md) of those verified instructions: `zi2zx`
writes it, and `ziran run` and the embedding API
run it on the portable instruction engine. The C, Go and wasm source-output
routes are separate.
Delivery order and the plan review are in [milestones](milestones.md).
The [gap policy](gap-policy.md) is normative: unsupported direct-target work
fails with a stable diagnostic and remains visible in the completion matrix;
portable, legacy and alternate backends are never fallback success paths.
The experimental direct pipeline is:
```text
.zi -> .zir -> lowered LIR -> verifier -> LIR optimizations -> .zx
| |
--emit lir verified ZX reader
|
portable interpreter OR target lowering
|
ELF + native range map
```
The compiler tools still use the normal compiler bootstrap. Once built,
`zx2native` writes machine bytes itself: it does not generate C or launch an
assembler, C compiler, or system linker to produce this executable.
## Implemented boundary
- Fixed-width signed/unsigned integers, bools, float32 and float64, local scalar
bindings, arithmetic, ordered/unordered comparisons and checked conversions.
- Branches, lazy `&&`, `||` and `ifx`, while and counting loops, loop exits, and
direct scalar calls including recursion. Portable calls support the checked
value shapes below. Machine-native calls support at most six general-register
arguments and one general-register result; float, vector, aggregate and
stack-passed call forms fail before encoding as named gaps.
- Record and fixed-array construction, extraction, local field/index mutation,
record-returning direct calls, nested value copies and simultaneous aggregate
block transfers in lowered IR and the portable engine. Local fixed arrays
accept dynamic integer indices with signedness-aware bounds checks. Assignment
destinations and every nested index are evaluated once before the right side.
Machine-native aggregate call arguments and results remain explicit gaps.
- Portable procedure values, arguments/results and indirect calls through local
slots, record fields and fixed-array elements. Procedure slots are checked
tokens with explicit signatures: null, invalid and wrong-signature targets
trap instead of becoming arbitrary machine addresses. Dispatch is currently an
unoptimized matching scan. External C/System/Host callbacks remain unsupported.
- Static integer/bool constant globals and zero-default records/fixed arrays,
including nested field mutation, imported globals, file-private definitions
and local shadowing in source/saved IR and the portable instruction engine.
Global/record-field addresses, pointer arguments/results and dereference
reads/writes also lower to checked address operations. Assignments evaluate
the destination once before the right-hand side; compound assignments retain
the preceding value even when a call mutates an alias. Local bool, integer,
float, pointer, record, fixed-array and procedure-value bindings can have
their address taken; such locals become checked frame allocations. Dynamic
fixed-array element addresses
rooted in globals or checked pointers are bounds-checked, including nested
records/arrays and addresses returned across procedure calls.
Retained tests compare C, Go and the portable instruction engine, including
a call-valued dereference assignment. Dependency-ordered
runtime module initializers execute once per portable instance before entry;
a failed initializer is sticky and entry is not started. Native ELF runs the
same ordered initializer list before entry. Mutable global state, readonly
constant storage and initializer state are owned by the execution instance.
- Block-parameter SSA with simultaneous edge copies, explicit ordered effects,
copied source origins, and a bounded verifier that rejects invalid definitions,
dominance, CFG edges, types, and effect order.
- Deterministic raw x86-64 encoding and ELF output with `.text`, `.rodata`,
`.data`, `.bss`, `.symtab`, `.strtab`, `.dynamic` and `.shstrtab` section
headers. `_start` and each program function's symbol carry their linked
address and byte extent, so final disassembly, debuggers and profilers have
meaningful labels; the section table describes the same bytes the program
headers map.
- Static globals and checked global/record-field pointer slots in direct ELF,
with zero/scalar initialization, packed aggregate loads/stores, pointer
parameters/results and separate RX text, read-only data and RW data segments.
Writes through read-only data tokens trap. Native code checks a pointer
token's liveness, version, writability and bounds in constant time from the
token itself; unlike the engine it does not yet check the pointee's element
type. No generated-C bridge is used.
- Verified lowered IR supports frame-local allocation of every current scalar,
record, fixed-array and procedure-value type in both the portable engine and
native ELF.
Every execution receives fresh zero-default or explicitly initialized storage.
Native active-frame descriptors preserve aliases through calls and recursion;
stale, wrong-type, forged, and exhausted-generation tokens trap with status 125.
- `#foreign host_api` calls lower to bodiless `Host` functions and explicit
`host.call` instructions from source and saved IR. A host value is a bool,
integer, float, pointer, which crosses as an opaque handle, or a record,
fixed array or view (`string`, `[]T`) of host values, nested at most 64
deep. Procedure values and types that reach themselves through a view are
rejected. The platform services are the named functions of the
`ziran.platform` module; a function of that name elsewhere is an ordinary
host capability. The revision-28 container records the recomputed capability
count. Embedders use `LirExecBindHost` for the scalar ABI or
`LirExecBindHostTyped` for the typed ABI. Typed scalars and pointers cross in
`bits`. Every other value crosses in `bytes` as one host image: the value's
own bytes, then the elements of each view inside it. In the image a view's
two words are the byte offset of its first element from the start of the
image and its element count; an empty view is two zero words. Arguments are
validated and copied. Returned views become instance-owned read-only storage
that remains valid for globals and later calls; a malformed image fails the
call and keeps nothing. A host's changes to an argument image are not copied
back yet.
A `--bind` provider already present in the checked Ziran program lowers to a
direct portable call. Native output accepts only the exact typed
target-owned console services described below; arbitrary host capabilities
still fail until native host trampolines exist.
- A registered host library may instead be an `ar(1)` archive of ELF64 x86-64
relocatable objects (`cc -c`, `ar rcs`). The Linux executable links the
members its capabilities reach, once each, carrying their text, read-only
constants, writable data, zero fill and relocations, and each capability's
veneer calls its member directly, so the executable stays static and has no
dynamic record. Absolute, PC32/PC64, PLT32, 32/32S, SIZE and GOT-relative
relocations are applied; TLS, constructor arrays, an undefined or duplicate
symbol and an unsupported relocation are the stable
`assembly.gap.machine-archive` diagnostic naming the capability, member and
symbol. A Windows image links no archive yet.
- `string` lowers to the record `{data: *u8, count: s64}`. Literals become
deduplicated read-only byte-array globals (empty literals use a null data
pointer); copies, reassignment, returns, `.count`, `.data`, checked indexing,
slicing and equality/inequality work in source, saved IR and the portable
engine. Slices use checked `{data, count}` views over fixed arrays or other
byte views, including empty/null views. Stores through read-only bytes trap.
Machine-native output supports the read-only data section, checked indexing,
byte equality and checked text views over frame-allocated fixed byte arrays,
including nonzero and nested slices, with allocation generation, owner-frame,
extent and lifetime validation. Slice shapes outside the verified
checked-token forms remain outside this implemented subset.
String concatenation is not a current checked-language string operation.
- A verified, target-neutral [machine IR](machine-ir.md) boundary is the only
`zx2native` lowering path. It lowers the current LIR subset for Linux x86-64
SysV with virtual registers, fixed-register constraints, explicit flags, call
clobbers and parallel copies. Deterministic allocation, an allocated-program
verifier and x86-64 encoding feed the internal ELF writer.
- The machine Linux x86-64 console veneer emits a static ELF with its own
`_start`, Linux `write` syscall 1 through a partial-write/`EINTR` retry loop,
and `exit_group` syscall 231. Standard output is buffered (line by line on a
terminal) and flushed before other descriptors' writes, traps and exit. It has no libc, CRT, `PT_INTERP` or `PT_DYNAMIC`.
Literal formatting covers strings/text views by byte length, bools, every
fixed signed/unsigned integer width, float32/float64 values and `%%`. Other
platform services are named hard gaps.
- `--emit lir` and `--emit map` inspection views. Map ranges are half-open,
relative to `.text`, and identify function, block and instruction.
Native always reads the verified, optimized ZX image, even for source input;
the current required ZX payload strips source origins, so native map origins
are empty. Source LIR inspection retains origins. Debug attachments and full
source-to-native mapping remain a hard gap. LIR schema 4 rejects older ZX
payloads at a rebuild boundary. Textual names are quoted and escaped rather
than allowed to inject extra lines into the instruction listing. Metadata
names and paths must be nonempty, NUL-free valid UTF-8; malformed wire metadata
is rejected before reaching JSON output, while valid Unicode is preserved.
- `--emit zx` always optimizes and writes the deterministic portable executable;
`--input zx` verifies and consumes it without source or `.zir`.
Source ELF output serializes and reads that same ZX boundary first, so a ZX
image gives byte-identical native output through either entry route. No
standalone `.lirb`, `--emit exec` or `--input exec` route remains. The internal
instruction codec is only a ZX payload.
- `--run` executes the same verified instructions in the bounded portable
engine that runs every bundle, with independent fuel, work and frame limits.
- Recoverable errors for unsupported constructs and atomic file replacement;
rejected programs do not overwrite an existing output.
- ZX production always transforms a separately owned copy of verified instructions
with exact scalar constant folding, identity-copy propagation, common
subexpression elimination, constant-branch CFG simplification and
nontrapping dead-instruction removal. Each enabled pass
is verified. Source `--opt --emit lir` exposes the transformed program, while
`--opt --emit opt-report` emits deterministic JSON transformation counters.
Trapping operations, ordered effects and executed fuel checkpoints remain
observable. This is not the complete optimization pipeline or register allocator.
This is a stack-slot backend, **not** an optimizing register allocator. It has
no demonstrated performance advantage. Native `Fuel` records emit no bytes and
appear as zero-length map ranges: execution is unmetered AOT, not the proposed
budgeted ZX instruction engine. Explicit native traps terminate with status 125.
## Build, inspect, execute
From the repository root:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- sh -eu <<'SH'
make zx-tools JOBS=2
build/bin/zi2zx --root tests/spec --entry assembly_scalar:Answer \
--emit lir -o build/assembly_scalar.lir tests/spec/assembly_scalar.zi
build/bin/zi2zx --root tests/spec --entry assembly_scalar:Answer \
-o build/assembly_scalar.zx tests/spec/assembly_scalar.zi
build/bin/zx2native --emit map -o build/assembly_scalar.map.json build/assembly_scalar.zx
build/bin/zx2native --emit elf -o build/assembly_scalar build/assembly_scalar.zx
status=0
build/assembly_scalar || status=$?
test "$status" -eq 42
SH
objdump -D -b binary -m i386:x86-64 --start-address=0x80 --adjust-vma=-0x80 build/assembly_scalar \
> build/assembly_scalar.disasm
```
The address adjustment makes disassembly addresses match the map's text-relative
offsets for this ELF layout. These offsets are neither source line numbers nor
addresses from a running process. `--emit lir -o -` and `--emit map -o -`
write inspection data to standard output; ELF output requires a file path.
`--emit zx -o -` writes portable executable ZX bytes to standard output.
`--diagnostics=json` includes structured diagnostic codes.
Maps report actual ELF file/text/data sizes, file offsets and virtual addresses
in `image`. An image with no writable state has one program header and a
128-byte text offset; one with globals, fuel, traps or buffered output has
two and a 176-byte text offset, and its data follows the text in the file,
mapped one page higher. Use the reported
`text_virtual_address` rather than the scalar example's fixed adjustment when
disassembling another image. Reported addresses describe the linked AOT ELF,
not an observed running process or a future relocatable/JIT code allocation.
`identity` is SHA-256 of the complete actual ELF, including initialized data
and symbol metadata, so a sidecar can be checked against the exact executable.
`variant` and `abi` label the baseline x86-64/internal-ABI implementation.
`optimization_request` identifies the canonical verified-basic optimization
boundary. `--opt` on ZX input does not rerun passes. Maps
encode the image to obtain this identity; they are inspection work, not a
cheap source-only preview or a runtime performance measurement.
Native maps support bounded output without renumbering identities:
```sh
build/bin/zx2native --emit map --function-id 0 --block-id 0 \
-o build/assembly_scalar.block.map.json build/assembly_scalar.zx
build/bin/zx2native --emit map --address-begin 35 --address-end 80 \
-o build/assembly_scalar.address.map.json build/assembly_scalar.zx
```
Function/block IDs refer to the selected lowered program (after `--opt`, if
enabled). A block filter requires a function ID. Address windows are nonempty,
half-open text-relative byte ranges and can intersect a function/block filter.
Matching instructions keep their complete original ranges rather than being
clipped; zero-byte sites are included when their position lies in the window.
Filtered maps retain full extents for selected functions and only referenced
origins plus their parent chains. An empty intersection is explicit, not an
error or an excuse to dump the whole program. `selection`, `selected_ranges`
and `total_ranges` distinguish filtered output from a complete byte map.
These options bound inspection output, not compilation work: the current
encoder still verifies and lays out the complete program.
```sh
build/bin/zi2zx --root tests/spec --entry assembly_scalar:Answer \
-o build/assembly_scalar.zx tests/spec/assembly_scalar.zi
build/bin/zi2zx --emit lir -o - build/assembly_scalar.zx
build/bin/zx2native -o build/assembly_scalar build/assembly_scalar.zx
build/bin/zi2zx run --fuel 10000 --work 100000 \
build/assembly_scalar.zx
build/bin/zi2zx --opt --emit lir -o build/assembly_scalar.optimized.lir \
build/assembly_scalar.zx
build/bin/zi2zx --opt --root tests/spec --entry assembly_scalar:Answer \
--emit opt-report -o build/assembly_scalar.opt.json tests/spec/assembly_scalar.zi
```
Only source `--emit lir` is unoptimized by default. All ZX, portable execution,
native map and ELF production goes through optimization and verified ZX bytes.
Reports require source input and `--opt` explicitly and can also use `-o -`.
Their `work` and `scratch_bytes` fields are bounded compiler-accounting counters,
not elapsed time, process RSS or a performance measurement. A shorter listing or
smaller executable is not evidence of faster execution.
The scalar fixture deliberately returns **42**, not zero. Source and saved-IR
tests require byte-identical lowered dumps, maps and executables. Native map
tests check that ranges cover the exact encoded instruction bytes without gaps.
Retained regressions also compare successful source programs with the C backend
and exercise integer/bool conversion, returning constant loops, loop exits,
non-truncating shift counts and executable permissions on unchanged output.
Generated ELF execution is required on Linux x86-64; other hosts still validate
encoding and inspection data, without claiming target execution.
## Still required
The upgrade is not complete. Outstanding language and runtime work includes
resizable owned vectors and other dynamic collections, their generated
cleanup/move paths, nested or reentrant host-to-bundle calls, foreign
C/system services, concurrency and the remaining matrix operations. The ZX
container still needs complete library composition and capability metadata
cross-checking; slice shapes outside the checked-token subset, native
aggregate call forms and arbitrary host trampolines remain gaps. The open
M4-M6 rows are tracked in [plans/open-work.md](../plans/open-work.md).
Unsupported constructs fail explicitly; there is no silent fallback to C, Go
or another engine inside the portable/native assembly route. The C and
Go backends remain separate source-output routes that can compile platform
binaries when explicitly selected. Mixed signedness comparisons require explicit
casts. The bounded revision-28 ZX reader validates container identities, the
instruction schema, entry and declared capabilities before native lowering.
Benchmark receipts live under `bench/results/` and
[bench/zx_compare.md](../bench/zx_compare.md). An interim result does not
close the full upgrade's feature or validation gates.
## Implementation and local tests
- [Lowered schema](../cmd/compiler_lowered_ir.zi) and
[verifier](../cmd/compiler_lowered_verify.zi).
- [Instruction codec](../cmd/compiler_exec_serial.zi),
[wire format](lowered-format.md), [portable engine](../cmd/compiler_exec.zi).
- [Executable container binding](../cmd/compiler_exec_link.zi) and
[format](zx-executable-format.md); [machine IR](../cmd/compiler_machine_ir.zi),
[lowering](../cmd/compiler_machine_lower.zi) and [verifier](../cmd/compiler_machine_verify.zi).
- [Checked-language adapter](../cmd/compiler_zir_lower.zi),
[CLI](../cmd/zi2zx/main.c), [build integration](../assembly.mk).
- [Source/saved-IR integration tests](../tests/assembly_cases.zi),
[verifier fixtures](../tests/spec/compiler_lowered_verify_test.zi),
and [machine ELF/map tests](../tests/machine_elf.sh).
- [Comparison processor](../bench/assembly_compare.zi),
[report schema and methodology](performance-report.md), and
[synthetic report tests](../tests/assembly_compare_cases.zi). These validate
reporting, not a measured compiler/runtime speedup.
```sh
env -u DISPLAY -u WAYLAND_DISPLAY make
make CHECK_FILTER=direct_assembly check
make CHECK_FILTER=compiler_lowered_verify check
sh tests/lowered_serial.sh build/bin/ziran
make CHECK_FILTER=lowered_exec check
sh tests/machine_elf.sh build/bin/ziran
make CHECK_FILTER=assembly_compare check
make check-bootstrap
```
These are local tests, not GitHub CI results. Benchmarks must run directly on
Alpha's physical host, with virtualization rejected. The final
report must include matched before/after ZX startup, throughput, memory and
artifact sizes, raw samples, excluded samples and any regressions; no speedup
is claimed until those measurements exist. The report processor keeps absolute
medians, favorable factors and candidate metric percentage changes distinct;
missing or noncomparable cells remain visible.
## Ten-step completion plan
The steps define completion; [milestones](milestones.md) define the delivery
order, per-row cutover and interim measurement points.
1. [Execution contract and completion matrix](01-contract-and-completion-matrix.md)
2. [Lowered IR and verifier](02-lowered-ir-and-verifier.md)
3. [Complete language lowering](03-language-lowering.md)
4. [Portable instruction engine](04-portable-instruction-engine.md)
5. [ZX format and linking](05-zx-format-and-linking.md)
6. [Optimization and native backend](06-optimization-and-native-backend.md)
7. [Architecture and platform coverage](07-architecture-and-platform-coverage.md)
8. [Assembler, objects and linker](08-assembler-objects-and-linker.md)
9. [Native runtime and integration](09-native-runtime-and-integration.md)
10. [Inspection, performance and cutover](10-inspection-performance-and-cutover.md)
+118
View File
@@ -0,0 +1,118 @@
# Ziran execution contract
Status: decisions required by [step 01](01-contract-and-completion-matrix.md). This document is normative for the lowered portable instructions of [step 02](02-lowered-ir-and-verifier.md). The implementation is the checked tree represented by [compiler IR](../cmd/compiler_ir.zi), its [lowering](../cmd/compiler_zir_lower.zi), the [portable instruction engine](../cmd/compiler_exec.zi) that runs every `.zx`, and their retained fixtures.
The direct target follows the [gap policy](gap-policy.md): target selection is a
contract, and an unsupported operation fails rather than selecting another
engine or semantic implementation.
## Contract layers
1. **Checked language graph:** `.zi` or saved `.zir` produces one checked typed graph. Statements, expressions, source spans, foreign/effect facts, ownership facts, laws, and proof certificates remain in this layer; executable instruction text is not reparsed from statement text.
2. **Verified portable program:** lowering turns each reachable function into typed basic blocks with explicit control flow, effects, value definitions, portable layouts, call/cleanup regions, and capability imports. Verification rejects malformed structure, type mismatches, invalid dominance, impossible layouts, and missing effects before an image can be loaded.
3. **Immutable encoded image:** the `.zx` executable container owns immutable code, type/layout metadata, constants, entry identity, capabilities, assets, laws, and optional inspection metadata. It contains no host pointers, C structure padding, process addresses, or executable `.zir` requirement.
4. **Loaded instance:** one immutable image may create many instances. An instance owns mutable global slots, call stacks, owned allocations, host handles, serial execution ownership, fuel state, and failure state. Code and metadata are never mutated by execution.
5. **Target program:** a target description selects CPU architecture, ISA features, OS ABI, calling convention, endianness, pointer rules, and atomic/thread services. It cannot change portable arithmetic, ownership, call order, traps, or capability identity. A missing selected facility is a preflight error; it never changes the engine or lowers to a serial/CPU substitute.
6. **Machine program and encoded object:** optimization and native lowering consume only the verified portable program and target description. Register allocation, physical stack frames, ABI call sequences, relocation, and encoding belong to these layers.
The backend APIs remain distinct: verify portable program, describe target, build machine program, encode image/object, load instance, run instance, inspect image or instance. No API accepts an unverified graph as executable code or exposes mutable process memory as program code.
## Numeric and scalar semantics
Current fixed integer types are `s8`, `u8`, `s16`, `u16`, `s32`, `u32`, `s64`, and `u64`. Abstract `int`/`integer` and pointer-sized `isize`/`usize` arithmetic use the 64-bit signed/unsigned operation policy on the portable target (matching `size_of(isize) == size_of(usize) == 8`). Bit representations, rather than host signed arithmetic, define operations; [scalar helpers](../cmd/zir/zir_scalar.h) mask to the declared width and reinterpret signed payloads.
- Addition, subtraction, multiplication, signed negation/overflow, and unsigned wraparound wrap at the operand width. Unsigned intermediates are used on all targets so C behavior is defined.
- Signed minimum divided by `-1` wraps to itself; its remainder is zero. Integer division or remainder by zero is a failed execution/trap, not undefined behavior.
- Left shift masks/uses the destination width after an unsigned-width shift; signed right shift sign-extends. A negative count or a count at or beyond the operand width fails on every target.
- Narrowing casts truncate to the destination bit width; widening casts preserve or zero-extend according to source signedness. All 64 signed/unsigned conversion pairs are covered by generated boundary fixtures.
- Comparisons use the operand's signedness and width. Equality on floating NaN is false; float division may produce infinity or NaN. Float-to-integer conversion requires a value representable in the destination type; a nonfinite or out-of-range conversion fails.
- `float32` operations must round each float32 operation once. C, Go, native output and the portable instruction engine all do so; [numeric conformance](../tests/numeric_conformance.json) records the chained-literal case.
- Enums have a checked integer backing width; enum comparison and conversion follow that representation without assuming a native `int` rank.
The current stable numeric cases and their exact fixture are published by [capability reporting](../cmd/package_capabilities.zi) and described in [numeric conformance](../tests/numeric_conformance.json); [numeric semantics](../tests/numeric_semantics.sh) and the [width matrix](../tests/numeric_width_matrix.sh) cover source and saved IR through C, Go, and ZX.
## Portable layouts, values, and memory
The lowered IR needs a deterministic **logical layout** distinct from native ABI layout. It records scalar kind/width/signedness, field order, byte size, alignment, inline/packed eligibility, array length and element layout, union alternatives, enum backing, and ownership/borrow class. Equivalent checked declarations must produce equivalent metadata under different allocation histories. Native alignment, padding, bitfield, vector ABI, calling convention, and address representation are selected only in the target program.
The portable image exposes logical offsets, not tagged C pointers or interpreter value layouts. The engine keeps values in packed instance-owned bytes and reaches them through checked address tokens; that is an implementation choice, not part of the image.
- Scalars, immutable strings, fixed arrays, and copyable records have value semantics. Assignment and parameter passing copy logical values unless an owned storage class explicitly moves.
- Unions select one active alternative; reading the wrong alternative is a checked failure. Records containing references, opaque foreign members, or oversized representations retain explicit logical storage.
- Fixed arrays and vectors have checked indexing and length. Proven-range optimizations may remove a bounds check only while the verifier can reconstruct the same proof.
- `New(T)` allocates zero-initialized storage and returns a pointer class; `free(pointer)` releases it, ignores null, and rejects a freed or non-heap pointer. Types with owned vector storage cannot bypass cleanup. The current contract and physical-OOM boundary are documented in [heap allocation](../tests/heap_new.sh).
- Bundle pointer parameters are opaque host handles: they may be stored, compared with null/equal, and passed to matching capabilities. They cannot be dereferenced as arbitrary process addresses. Native C pointers retain native lifetime rules; this is a target boundary, not a portable aliasing contract.
- Immutable strings have byte length and may contain NUL. A `TextView` is a borrow of a place. Current C mutation observes borrowed bytes; Go and ZX snapshots isolate mutation, as reported by [capabilities](../docs/CAPABILITIES.md). Lowered IR must preserve each target's observable rule through an explicit borrow or snapshot operation rather than pretending one representation is universal.
- Portable state export deep-copies owned strings, arrays, records, enums, scalar lanes, and vectors. Pointers, slices, growable vector backing, and other borrowed/host resources are rejected.
## Ownership and cleanup
The checked graph records move and borrow facts. Lowering must make each effect explicit; a backend may not invent an extra copy, drop, or mutation.
- Direct owned `Vec` locals and parameters drop at block close, return, `break`, and `continue`, including every path through nested control flow. Vectors reachable through record fields and fixed arrays drop recursively. Globals remain shared and are not automatically released.
- A valid move source is a whole local binding, a fresh call result, or a plain record-member path rooted at a local aggregate. A direct move clears its source before a later drop. An aggregate move clears every reachable native vector field; the portable representation invalidates the corresponding logical slots. Moved storage is unreachable thereafter.
- Indexed and pointer-backed member paths and paths rooted at a global remain rejected as move sources. Assignment over an owned direct or aggregate-held vector is rejected. A fresh vector expression statement drops immediately; a member/index access must first bind the fresh result.
- `BuilderFinish` consumes the builder. Native C transfers nonempty bytes and retains them for process lifetime; Go copies an immutable snapshot. Empty native storage may be released. `Text` is an owned record wrapping a vector and follows aggregate move/drop rules.
- Live vector slices and text views restrict mutation, resizing, moving, replacement, and calls whose checked effect summary writes their backing. Checks are field-sensitive where represented: sibling fields remain mutable. Raw foreign declarations have no checked read/write summary and remain the caller's responsibility.
- Scoped cleanup is a region in the instruction graph, not a source-text transformation in the backend. Returns, breaks, continues, traps, and parallel-region exits follow the same explicit cleanup edge set. The current source pass and tests are in [cleanup lowering](../cmd/compiler_ir_cleanup.zi) and [owned values](../docs/OWNED_VALUES.md).
## Calls, effects, concurrency, and fuel
Call arguments evaluate left to right on every target. Named/default binding occurs after argument evaluation. Call results feed directly into the consuming call or operation, but earlier values are read before later calls can mutate them. Compound assignment reads its destination before evaluating the right operand. These rules are fixed by [call order](../tests/call_order.sh) and [compound order](../tests/compound_order_cases.zi).
Every callable and foreign capability carries an explicit effect class: pure, observing, mutating, external/host, allocation, trap, parallel, or combinations accepted by the verifier. Effects drive reordering restrictions, borrow checks, fuel placement, host preflight, and optimization barriers. A pure operation can be controlled only if its result and trap behavior remain indistinguishable.
- Direct, procedure-value, bound-provider, and foreign calls all declare parameter and result layouts. Host marshalling validates signatures and returned record field identities/types. Mutable slice arguments are copied back only after a successful synchronous host call; overlapping mutable slice arguments are rejected.
- A call owns its local cleanup region. Evaluation temporaries remain rooted until the last consumer and call complete. A value a host call returns is released at a later host call once nothing the program can reach names it.
- Portable engine calls nest up to the frame limit its host sets, 65,536 for bundles; a deeper run fails with "nested calls filled the stack". Native and Wasm tiers use explicit stack/budget guards. Recursion exhaustion is a failed execution, not allocator or stack corruption.
- Ordinary native and portable runs are unbounded. A host may select a positive cumulative budget before global initialization. The portable engine, native and Wasm tiers count function entries and loop iterations, with literal-bound loops charged at region entry. Workers in one `#parallel for` region spend from the shared remaining budget, and the run charges all successful iterations when the region ends. Current behavior and tests are documented in [ZX execution](../docs/ZX.md) and [bundle step limits](../tests/bundle_step_limit.sh).
- `#parallel for` currently runs forward C regions on worker threads; existing Go/ZX serial behavior is baseline evidence, not assembly-target support. The direct target rejects a parallel region until that target implements its declared parallel contract. Portable instances support concurrent execution only across distinct instances; each instance and host callback context has one executing owner.
- `#parallel_gpu for` currently has no device backend. The direct target rejects the region with its Gap diagnostic; it never runs or reruns the region on the CPU. A future device implementation must preserve failure and budget semantics without substituting a different engine.
## Traps, capabilities, and isolation
Runtime failures stop the current run and leave the instance marked failed: out-of-bounds access, invalid union access, integer divide by zero, invalid float-to-integer conversion, invalid shift, unreachable code, allocation/cleanup contract failure, stack/fuel exhaustion, host contract violation, or a capability call returning an invalid value. A trap runs no later user code except cleanup already required by the verified failure edge; it must not read freed storage or synthesize a result. Diagnostics retain a source location when inspection metadata is present.
Required host services are capability identities, not dynamic imports: module/function pairs with checked ABI and argument-read/effect metadata. A provider check must reject an unsupported program without running initializers, opening a window, or executing the entry. Missing bindings fail before entry. Validated native code is **not an operating-system sandbox**: malformed-input rejection and capability restrictions do not confine memory, syscalls, signals, or bugs in linked OS libraries. Untrusted execution still requires a process or comparable OS boundary.
There is no native ZX engine yet. Every `.zx` runs on the portable instruction engine, or on the WebAssembly tier where a provider is installed; a tier that cannot run a program fails instantiation and never starts another. The planned direct native backend must preserve the same failure and capability model.
## Debug and release policy
Semantic checks, effects, layouts, control-flow validity, capability ABI, and trap/cleanup edges are mandatory in debug and release. Release optimization may remove only checks it can prove redundant. Stripping names, source spans, variable provenance, law evidence, or disassembly metadata is an explicit encoding choice selected by the producer and recorded in image metadata. Stripped inspection data never changes executable semantics. A debug image may be larger and slower, but a release image cannot rely on unverified assumptions.
## Lowered IR representation decisions
Use typed virtual registers in basic blocks, not source trees and not physical registers. Registers are immutable except explicit mutable-place instructions; SSA-like value definitions must dominate uses. Keep source spans and provenance out of the execution datum, attached in parallel side tables. Functions and blocks need stable IDs, not object pointers. Constants are typed, canonical, and owned by the image.
The graph verifier must prove block termination, edge arity, dominance, type equality, move/borrow validity, cleanup region coverage, layout consistency, effect ordering, fuel edge placement, and capability signatures. It must also reject process pointers, target-specific sizes in portable code, duplicate IDs, cycles among value definitions, and metadata that references missing declarations.
### Concrete opcode categories
Do not assign numeric opcodes in this step. Reserve stable categories, each with typed operands and a separate effects word:
| Category | Required forms | Representation decision |
|---|---|---|
| Constants | scalar, string bytes/range, enum, null pointer, zeroed aggregate, typed SIMD lanes | Intern by canonical typed value; never reparse literal text at run time. |
| Data movement | copy, move, clear, zero-init, union select, view/borrow, snapshot | Destination and source carry logical layout and ownership class; moves clear source slots. |
| Integer arithmetic | add/sub/mul/neg, div/rem, and/or/xor/not, shifts, min/max if currently checked | Parameterize width and signedness; checked div/rem/shift trap classes are explicit. |
| Float arithmetic | add/sub/mul/neg/div/rem-if-supported, compare, classify, round, convert | Keep `f32` and `f64` distinct; no silent double intermediates. |
| Conversion | integer width/sign, integer/float, enum/integer, bitcast only where portable | Model checked range failure; reinterpretation cannot change logical type. |
| Aggregate memory | field read/write, fixed-array index, vector index, union field, slice bounds | Logical offsets and lengths only; target lowering selects ABI. |
| Heap and ownership | allocate-zero, free, retain/release hooks, cleanup region enter/exit | Explicit region terminator handles return, break, continue, and trap edges. |
| Control flow | conditional/unconditional branch, switch/complete enum, loop header, named break/continue, unreachable | One terminator per block; named control-flow IDs are resolved by verifier. |
| Calls | direct, procedure value, bound provider, foreign capability, host marshalling, tail call only if semantics survive | Arguments are explicit ordered operands; defaults/names are lowered before encoding. |
| Effects and fuel | checkpoint, budget set/consume, worker region enter/exit, explicit device/worker failure | A checkpoint is observable and blocks moving an unbounded call/loop; no CPU fallback opcode exists. |
| SIMD | lane insert/extract, element-wise arithmetic/compare/select, reductions currently supported | Lane type/count is portable; ISA lowering is target-only. |
| Text and collections | string length/index/equality, builder append/finish, vector operations currently supported | Preserve borrow versus snapshot and recoverable allocation failure. |
| Capability and instance | capability require/call, state export/import, instance replace boundaries | Capability identity and ABI checks precede entry/upgrade. |
Keep target-specific assembler, OS syscall, atomic, thread, ABI call, and platform-library operations out of the portable opcode stream. Encode them as declared capabilities or explicitly selected native extension records with target descriptions; unsupported combinations must fail at target preflight.
## Non-goals and open boundaries
- The replacement `.zx` format is intentionally incompatible: it is revision 28, and a file of another revision is rejected.
- Go-only opaque maps/types and C callback/assembly extensions do not become portable types by renaming. They remain target extensions with preflight rejection where the portable verifier cannot preserve them.
- Raw native FFI has no checked aliasing/memory-effect contract. Differently typed aliases and arbitrary host-backed aliases remain outside current guarantees.
- Cross-compilation, successful object encoding, a child-agent receipt, or a stored benchmark report does not prove target execution. Completion requires fresh evidence for the exact platform and fixture.
- RISC-V and every architecture beyond the maintained x86-64, 32-bit ARM, AArch64, and wasm32 rows are explicit future extensions, not implicit completion.
+100
View File
@@ -0,0 +1,100 @@
# Current execution feature matrix
Status: current-tree baseline for [step 01](01-contract-and-completion-matrix.md).
`Working` means the implementation and retained source/saved-IR fixture exist;
it is not a claim that this documentation task reran the fixture. `Gap` means
the direct assembly target lacks required work and must reject it explicitly.
`Excluded` is a deliberate target-contract exclusion. `Unknown` means no fresh
execution evidence for this cell is present. Current fallback or downgrade
behavior is recorded only as baseline evidence and is a Gap for the new target;
it never counts as support under the [gap policy](gap-policy.md). `Proposed`
belongs to the ten-step ASSEMBLY plan, not today's implementation.
Primary evidence is [implementation status](../docs/IMPLEMENTATION_STATUS.md), [capability output](../docs/CAPABILITIES.md), [ZX behavior](../docs/ZX.md), the stable feature registry in [features](../docs/FEATURES.json), [capability reporting source](../cmd/package_capabilities.zi), and retained tests. Cross-compilation or presence of a script never counts as target execution evidence.
## Execution modes
The opt-in [direct scalar prototype](README.md) is separate from these existing
engines. It emits Linux x86-64 ELF from checked source/saved IR, but does not
replace ZX or establish portability/performance completion.
| Mode | Current status | Evidence | C | Go | Portable ZX | Native ZX | Wasm | OS boundary |
|---|---|---|---|---|---|---|---|---|
| Generated C output | Working, source and saved IR | [implementation status](../docs/IMPLEMENTATION_STATUS.md), [C target](../tests/c99_target.sh) | emits C | n/a | n/a | lowers to same C backend | can compile selected C to wasm32 | Linux current host; Windows/macOS/Android toolchains have separate fixtures |
| Generated Go output | Working, secondary tier | [capabilities](../docs/CAPABILITIES.md), [call order](../tests/call_order.sh) | n/a | emits Go | n/a | n/a | n/a | Verifiable only where a compatible Go runtime/toolchain executes it |
| Portable instruction engine | Working; runs every `.zx` through `zi2zx run` | [ZX contract](../docs/ZX.md), [engine](../cmd/compiler_exec.zi) | n/a | n/a | runs every bundle | n/a | separate target | Host capabilities and platform console services only |
| Wasm execution tier | Working restricted subset; provider rejection is a hard `zx.wasm` error and never starts another engine | [Wasm tier](../docs/ZX.md) | emitter | n/a | explicit separate engine only | budget model shared | wasm32 | Scalars, owned strings, fixed arrays, records, typed `s64 -> s64` hosts; other constructs must fail direct-Wasm preflight |
## Portable language behavior
| Feature | Current status and target behavior | Evidence |
|---|---|---|
| Fixed-width integers | Working on C, Go, ZX source/saved IR: declared-width wrap, signed-min division/remainder, shifts, casts, bitwise and mixed-width behavior. Wasm uses the same scalar tier inside its subset; unknown outside available Wasm fixtures. | [numeric semantics](../tests/numeric_semantics.sh), [width matrix](../tests/numeric_width_matrix.sh), [manifest](../tests/numeric_conformance.json) |
| Float32/float64 | Working arithmetic, compare, infinity/NaN and range-checked conversion on native C/Go/ZX. lowered IR must not preserve that gap. | [numeric manifest](../tests/numeric_conformance.json), [status](../docs/IMPLEMENTATION_STATUS.md) |
| Implicit widening | Working for the checked feature contract on C, Go, ZX. | [feature registry](../docs/FEATURES.json), [features test](../tests/compiler_inventory_cases.zi) |
| SIMD vectors | Working with identical lanes across native C tiers, Go lane loops, bundles and source/saved IR. C wasm32 may use SIMD128; bundles run vectors lane by lane. CPU feature selection is target-specific. | [status](../docs/IMPLEMENTATION_STATUS.md), [SIMD target](../tests/simd_target.sh) |
| Scalars, strings, enums, plain records | Working in portable subset, including literals, copies, fields, scalar compound assignment, parameters and returns. Pointer-sized `isize`/`usize` lower as portable 64-bit signed/unsigned integers (matching `size_of` = 8); functions/statements outside the verifier subset are rejected. | [ZX subset](../docs/ZX.md), [verifier](../cmd/compiler_lowered_verify.zi), [size scalars](../tests/spec/zx_lowered_size_scalars.zi) |
| Fixed arrays, slices, vector indexing | Working with checked bounds. Generated C may omit only proven bounds checks; portable host slices copy successful mutations back and reject overlapping mutable arguments. | [proven ranges](../tests/proven_index_ranges.sh), [host slices](../tests/host_slices.sh) |
| Compile-time assertions, `#run`, laws | Working as checked language features on all advertised targets; unsupported proof/effect forms or exhausted budgets are rejected/unknown rather than guessed. | [feature registry](../docs/FEATURES.json), [compile run](../tests/compile_run.sh), [laws](../tests/laws.sh) |
| Procedure defaults and procedure values | Working for advertised examples on C, Go, ZX; portable verifier checks slot signatures and rejects C callback procedure types. | [feature registry](../docs/FEATURES.json), [defaults](../tests/call_argument_cases.zi) |
| Print and I/O | Working literal-format print on C, Go, ZX. Rich OS I/O is a library/capability contract, not a portable opcode. | [feature registry](../docs/FEATURES.json), [print](../tests/print.sh) |
| Named imports and linking | Working; bundles follow direct calls, retain required startup/types/laws, and reject unresolved imports or unreachable unsupported code. | [ZX linker](../docs/ZX.md), [bundle provider cases](../tests/bundle_provider_cases.zi) |
## Memory, ownership, and cleanup
| Feature | C | Go | Portable ZX | Wasm | Evidence |
|---|---|---|---|---|---|
| Zeroed heap allocation/free | Working | Working | Working; rejected use after free/double free | Gap outside documented Wasm subset; direct Wasm rejects | [heap allocation](../tests/heap_new.sh), [Wasm tier](../docs/ZX.md) |
| Owned `Vec` operations | Working | Working, physical OOM may terminate | Working, allocation failures recoverable where declared | Gap outside Wasm subset; direct Wasm rejects | [owned values](../docs/OWNED_VALUES.md), [vector test](../tests/vec.sh) |
| Direct/aggregate vector drops | Working on block, return, break, continue | Working | Working | Gap; direct Wasm rejects until implemented | [aggregate safety](../tests/aggregate_vec_safety.sh) |
| Vector field/member moves | Working with listed source restrictions | Working | Working | Gap; direct Wasm rejects until implemented | [aggregate safety](../tests/aggregate_vec_safety.sh), [move expression](../tests/vec_move_expression.sh) |
| Text and `TextView` | Borrowed bytes observable | Snapshot | Snapshot | Owned strings in Wasm subset; other text forms are a Gap and reject | [capabilities](../docs/CAPABILITIES.md), [text view mutation](../tests/text_view_mutation.sh) |
| Native pointers | Native lifetime/alias responsibility | Native Go pointer rules | Opaque host handles in bundle ABI | Linear-memory boundary/provider values | [ZX host ABI](../docs/ZX.md), [capabilities](../docs/CAPABILITIES.md) |
| Instance global state | Native instance data | Go program state | Independent mutable slots per instance | Independent bindings/linear memory per instance | [component state](../docs/ZX.md), [component engine test](../tests/bundle_component_test.c) |
## Calls, concurrency, fuel, and traps
| Feature | Current behavior | Evidence |
|---|---|---|
| Argument and compound order | Working: left-to-right call arguments; destination read before compound right side on C, Go, ZX. | [call order](../tests/call_order.sh), [compound order](../tests/compound_order_cases.zi) |
| Bounded execution | Working by explicit host selection. The engine and Wasm count calls and loop iterations; cumulative limited open includes initialization and every run. | [ZX limits](../docs/ZX.md), [step limit](../tests/bundle_step_limit.sh) |
| CPU parallel regions | Current baseline: C threads on supported hosts; Go/ZX serial downgrade and reverse-region serialization are assembly-target Gaps. The direct target rejects them until their promised parallel implementation exists. | [parallel test](../tests/parallel.sh), [native worker pool](../tests/spec/native_parallel_windows_test.zi) |
| GPU regions | Every target reports an explicit Gap and rejects GPU selection; there is no CPU fallback. | [capabilities](../docs/CAPABILITIES.md), [assembly blocks](../tests/assembly_blocks.sh) |
| Runtime traps | Working failure boundary: bounds, unreachable, host/fuel/stack and numeric contract failures stop the run. | [ZX contract](../docs/ZX.md), [engine](../cmd/compiler_exec.zi) |
| Host capabilities | Working checked module/function ABI with provider preflight, bindings, mutable slice copyback and no overlap. | [host capabilities](../tests/host_capability.sh), [ZX host ABI](../docs/ZX.md) |
| Component replacement | Working transactional ABI/state migration/rollback for portable components and supported Wasm memory interface. | [component contract](../docs/ZX.md), [web lifecycle](../tests/zx_web_lifecycle.sh) |
## Native extensions and foreign runtimes
| Feature | Working behavior and restriction | Evidence |
|---|---|---|
| GNU assembly variants | Current C/Go behavior may use a checked portable body. For the direct assembly target, a missing matching target/feature implementation is a Gap and rejects at preflight; no portable body or cgo bridge satisfies the cell. | [assembly](../tests/assembly.sh), [ZX assembly](../tests/zx_native_asm.sh), [Go assembly](../tests/go_assembly_cases.zi) |
| C callbacks / `#c_call` | Native C ABI only; Go and ZX target preflight reject it before output. | [capabilities](../docs/CAPABILITIES.md), [compiler inventory](../tests/compiler_inventory_cases.zi) |
| Go foreign types/maps | Go target extension only; opaque identity and scalar-union checks reject unsupported portable lowering. Renaming does not create a portable layout. | [compiler IR](../cmd/compiler_ir.zi), [capabilities](../docs/CAPABILITIES.md) |
| OS libraries | Explicit foreign/library dependencies remain allowed; native platform service portability is defined per OS row, not by opcode presence. | [executable bundle](../tests/executable_bundle.sh), [architecture](../docs/ARCHITECTURE.md) |
| Runtime assembly/C cache | Current native bundle cache is keyed by bundle/libraries/CPU/compiler sources; cached code can bypass program recheck only under documented boundary. | [native execution](../docs/ZX.md) |
## Maintained platform rows
| Platform / target row | Current verified surface | Target-specific restriction | Unknown verification |
|---|---|---|---|
| Linux x86-64, C, ZX and direct ELF | Current development host; source/saved-IR C, Go, ZX, direct `zx2native` ELF, threads, SIMD tiers, OS libraries and retained tests. | Native C parallel threads; SIMD ISA dispatch; Linux process/thread services. | A complete matrix needs fresh named toolchain/hardware evidence per future gate. |
| Linux/Android ARMv7 | Portable ZX and generated C/Go; C SIMD fixtures cover NEON, VFP-only and scalar lanes; Android API 21 streams and optional four-ABI link paths. | 32-bit ARM ABI/CPU feature restrictions; optional NDK/QEMU/phone tooling. | Specific Android OS version/device combinations and non-SIMD execution are not established by this documentation pass. |
| Linux/Android AArch64 | Portable ZX and generated C/Go; NEON codegen and QEMU execution documented. | AArch64 hardware-capability assembly selection; Android toolchain. | Fresh physical-platform coverage beyond documented fixtures is unknown. |
| Linux/Android other CPU | Portable ZX and generated C/Go are the supported route. | No direct native row. | New architecture execution, including RISC-V, is proposed/unknown. |
| Windows generated C/Go | Compiler/runtime platform code and Windows fixtures exist. | No direct native row. | No fresh Windows host execution in this documentation task. |
| Windows portable ZX | The engine has no Linux-only service assumptions. | No native tier. | Fresh Windows host evidence unknown. |
| macOS generated C/Go and portable ZX | Darwin build definitions and package/file fixtures exist. | Darwin SHA/random system libraries and ABI differ. | No fresh macOS execution in this documentation task. |
| Browser/WebAssembly tier | Bundles lowered to wasm32 with per-instance memory, state, budget and lifecycle, tested in headless Chromium. | Subset listed above; unsupported constructs and provider rejection are direct-Wasm gaps. | Other browsers/versions and non-Chromium Wasm hosts are unknown. |
| Wasm32 standalone tools | `zx2wasm` lowers verified ZX; the bundle Wasm tier runs it under an Emscripten `libziran`; optional Emscripten/wasmtime probes for SIMD and file-tree fixtures. | Requires installed Wasm CC/runtime; skipped when probes absent. | Current machine's optional tool availability is not execution evidence for target hosts. |
| Go output on OS | Generated source follows Go runtime. | Serial parallel regions, snapshots, foreign runtime restrictions. | Exact OS/Go version combinations not covered by a fresh matrix run. |
## Retained check surface
The retained suite is physically pruned. `make check` builds the retained tool and runs every discovered `.sh` check unless filtered; `make check-bootstrap` compares checked-in generated compiler sources; both run with desktop display variables removed. This is the suite that must accompany later implementation work. See [Makefile](../Makefile) and [check planning](../tests/check_plan.zi). Hardware/tool-dependent scripts may still skip when their required external probe is absent; a skip is not target execution evidence.
## Unknown and proposed work
**Unknown now:** fresh Windows/macOS/Android/browser execution for this exact revision; Wasm constructs outside the documented subset; Go behavior on every OS/runtime pair; pointer aliases and foreign effects lacking checked summaries; all future-backend target cells until a named fixture runs. Optional-tool skips, cross-compilation, child receipts, and stored benchmark reports remain non-evidence.
**Required step-01 follow-up:** lower the contract into typed basic blocks and verifier records; define portable layouts and effects; encode cleanup/fuel regions explicitly; separate target extension records from portable opcodes; then choose an incompatible `.zx` version against the actual writer in step 05. Feature completion requires fresh source/saved-IR execution evidence for every required matrix cell, with legitimate target exclusions named rather than silently skipped.
+132
View File
@@ -0,0 +1,132 @@
# Assembly-target gap and error policy
Status: normative for the direct assembly target and the revision-28 executable
path. This policy applies to every delivery milestone and completion matrix cell.
## Why gaps are not fallbacks
A fallback makes an unsupported path look successful. It can hide missing
lowering, CPU support, host services, or target validation behind a different
engine, compiler, or semantic implementation. The assembly target therefore has
no fallback state.
Each feature/target cell has exactly one of these states:
- **Implemented** — the named implementation ran on the required target and has
fresh retained evidence.
- **Gap** — required work is missing. Selecting the cell fails before output or
execution with its stable diagnostic.
- **Excluded** — the contract deliberately does not promise the feature for that
target, and capability output names the exclusion.
- **Unknown** — implementation may exist, but the required execution evidence is
absent. Unknown never counts as implemented.
`fallback`, `downgrade`, `skip`, `emulated`, `cross-compiled`, and `legacy engine`
are evidence annotations, not successful assembly-target states. A comparison
may run a legacy or reference engine only when the command selects it explicitly;
that result cannot close a direct-target cell.
## Required failure boundary
The compiler and loader reject a gap at the earliest boundary that has enough
information to identify it:
1. source/lowering rejects unsupported language operations;
2. target preflight rejects CPU, OS/ABI, runtime, capability, and native-extension
mismatches;
3. object/link validation rejects missing formats, relocations, libraries, entry
support, or signing facilities;
4. loading rejects unavailable executable-memory, cache, or host integration.
Every rejection has a stable diagnostic code and reports the selected target,
engine, missing feature or facility, and source origin when one exists. It must
not run module initializers, call a host, open a window, execute an entry, invoke
another backend, or overwrite the last valid output.
Examples of required errors include:
- a native target without a matching `#asm` implementation;
- a required ISA feature absent from the selected CPU contract;
- a parallel or GPU region without its promised target implementation;
- a WebAssembly operation outside the direct Wasm lowering;
- a missing host capability or foreign ABI adapter;
- an unsupported object format, relocation, linker input, or platform signing
facility;
- a request to run a legacy or incompatible executable revision.
## Host capabilities and ABI veneers
Host capabilities and platform ABI veneers are separate contracts. A host
capability is a portable, typed service named by linked ZX instructions and
bound by an embedder or runtime provider. A platform veneer is direct-target
code for entry, calling conventions, syscalls or system libraries, error
handling, and process exit. CPU instruction selection is a third concern.
An implemented host capability does not satisfy a missing direct-target veneer,
and an implemented veneer does not bind a portable host capability. Generated C
or Go bindings are also independent: they may produce working platform binaries
without closing the direct-native target cell. A missing veneer, unsupported
service, or unavailable binding is rejected at preflight or link time without
starting another engine.
The opt-in Linux x86-64 direct console veneer is implemented around an owned
`_start`, Linux `write` syscall 1, `exit_group` syscall 231, and no libc, CRT,
or dynamic linker. Its `write_all` retries `EINTR` and partial progress; other
write failures take the image's fixed trap exit. This is execution evidence for
the experimental AOT slice, not a completed target-row or native-ZX claim.
The implemented machine print subset covers read-only literal format strings,
strings and text views by exact byte length, booleans, every fixed signed and
unsigned integer type, deterministic float32/float64 output, and `%%`. A
missing target-owned formatter, veneer or service reports
`assembly.gap.machine-platform-service-unavailable`. None permits a C/Go route
or portable interpreter to start.
## Target preflight codes
Target preflight uses three stable codes, all hard errors:
- `assembly.gap.target-unimplemented` — the selected CPU/OS row is Gap,
Excluded or Unknown. Only an Implemented row passes.
- `assembly.gap.cpu-feature` — the row does not implement a required CPU
feature, including a feature of another CPU family.
- `assembly.gap.os-service` — the row does not supply a required operating
system service.
The message names the selected row, the `assembly` engine, the row state and
the missing feature or service. The check needs no input, so it runs before
any source or saved `.zir` is read and both report the same gap. `ziran
capabilities --json` lists every row's state and code under
`assembly_targets`; `ziran explain` describes each code.
## Explicit engine and target selection
Portable execution, native execution, direct Wasm, C, and Go are separate
targets. One may be the documented default of a command, but none is a rescue
path for another. An explicit native request never starts the interpreter; an
explicit portable request never invokes native code; direct Wasm never routes
through generated C. Old executable revisions produce a rebuild error instead of
selecting an old runtime.
CPU variants are also explicit target contracts. If the chosen variant requires
features the selected or running CPU lacks, preflight fails. A lower-feature
variant may be selected only when it is an independently declared implementation
of that exact target cell, not a portable body or another engine disguised as
successful native execution.
## Tests and completion accounting
Every Gap cell needs a negative fixture that checks:
- the stable diagnostic code and relevant target/feature fields;
- failure before initializer, host, entry, or output replacement side effects;
- identical rejection from source and saved `.zir` where both inputs apply;
- capability and inspection output reporting the same gap.
Every Implemented cell needs positive source/saved-IR execution evidence on its
named target. Optional tools or hardware may leave a cell Unknown, but tests may
not silently skip it and completion reports may not round it up.
Milestones and final completion count only Implemented cells and explicit
Excluded cells. Any Gap, Unknown, fallback, downgrade, skip, or substituted
engine keeps its gate open.
+285
View File
@@ -0,0 +1,285 @@
# Lowered instruction binary format
Status: foundational codec for steps 02 and 05. This is not the ZX container
revision from step 05, does not wrap checked `.zir`, and is not an installed
execution format by itself.
The implementation is
[`cmd/compiler_exec_serial.zi`](../cmd/compiler_exec_serial.zi). It serializes
the complete current `LirProgram` record with explicit fields. It never copies
a C struct, stores a host pointer, depends on host alignment, or uses native
integer byte order.
## Public API and ownership
The exported Ziran API is:
```zi
LirWrite(program: LirProgram, output: []u8) -> LirCodecResult
LirRead(owner: *LirReadOwner, input: string, limits: LirLimits) -> LirCodecResult
LirReadProgram(owner: *LirReadOwner) -> LirProgram
LirReadFree(owner: *LirReadOwner)
```
Normal generated-module naming applies. C consumers see the
`compiler_exec_serial_` prefix; Go and portable callers use the generated module
API rather than a separate ABI shim.
`LirWrite(program, [])` validates the program and returns the exact required
`size`. A nonempty output shorter than that size returns `Output`, reports the
same size, and changes no byte. A sufficient output receives exactly `size`
bytes; any suffix beyond that size is unchanged. The writer traverses every
table in stored ID order, so the same program produces the same bytes.
`LirReadOwner` must start zero-initialized (ordinary Ziran locals do). `LirRead`
first releases any preceding value, makes three bounded passes (shape, copied
data, then borrowed views), and calls `LirVerify` before reporting success. It
copies all strings and constant byte arrays. The input may therefore be changed
or released as soon as the call returns. On any failure the owner is empty.
`LirReadProgram` returns a borrowed program. Every table, nested slice and
string in it expires at the next `LirRead` or `LirReadFree` on that owner.
Consume those views first. Empty and repeated frees are harmless. The owner
must not be moved or resized while a program view is live, and input to a new
read must not alias the owner's preceding storage.
These rules use ordinary Ziran slices and owned vectors, so they apply to C,
Go, and engine reads without a host-only allocator or garbage-collected
lifetime exception.
## Integer and sequence encodings
Every integer is little-endian and has the width named below:
- `u8`, `u32`, `u64`: unsigned 8-, 32-, and 64-bit values.
- `s32`, `s64`: the two's-complement bit pattern written as `u32` or `u64`.
- `string` and byte slice: `u64 byte_count`, followed by exactly those bytes.
- ID/type/value list: `u32 count`, followed by `count` `s32` elements.
- record/table count: `u32 count`.
Strings and byte slices are binary. Embedded NUL is never a terminator. The
current `LirVerify` policy still rejects NUL in module, source, global and
function names; such a file reaches verification as binary data and returns
`Verify`, rather than being truncated by the codec.
Counts are limited to `INT32_MAX`, because lowered IDs are signed 32-bit
values. The whole encoded file and the default decoded-storage budget are at
most 256 MiB. Caller-supplied `LirLimits` independently bound types, functions,
blocks, values, instructions, decoded storage and graph work. All additions,
multiplications, offsets and lengths are checked before allocation or slicing.
## Header and section directory
The fixed header is 64 bytes:
| Offset | Field | Required value |
|---:|---|---|
| 0 | `u32 magic` | `0x52494c5a` (`ZLIR`) |
| 4 | `u32 format_version` | `1` |
| 8 | `u32 lir_schema_version` | current `LirVersion` |
| 12 | `u32 header_size` | `64` |
| 16 | `u64 required_features` | bit 0 (`base`) only |
| 24 | `u64 flags` | `0` |
| 32 | `u32 section_count` | `1` or `2` |
| 36 | `u32 reserved` | `0` |
| 40 | `u64 total_size` | exact input byte count |
| 48 | `u64 directory_offset` | `64` |
| 56 | `u64 reserved` | `0` |
Each directory entry is 24 bytes:
```text
u32 kind
u32 flags
u64 offset
u64 size
```
Entry 0 is always kind 1 (`core`) with flag bit 0 (`required`). Entry 1, when
present, is kind 2 (`debug`) with flags zero. Directory and section order are
canonical. The core begins immediately after the directory, debug immediately
after core, and the final section ends at `total_size`. Gaps, overlaps, unknown
sections, unknown flags, nonzero reserved fields, truncation and trailing bytes
are rejected. Unknown required-feature bits are rejected before any table
allocation.
Debug is present exactly when the program contains at least one source or
origin. It is omitted when both tables are empty. A consumer that strips debug
must also clear every function/instruction origin to `LirNoId` before producing
a new verified file.
## Core section
Fields occur exactly in this order:
```text
s32 program.version
s32 program.entry
u32 module_count
repeat module_count:
string module
u32 type_count
repeat type_count:
u32 kind
s32 bits
u32 flags # bit 0 signed, bit 1 native_width
s32 element
s64 count
s32 result
list<s32> fields
list<s32> parameters
u32 constant_count
repeat constant_count:
s32 type
u64 bits
bytes data
u32 global_count
repeat global_count:
s32 module
string name
s32 type
s32 constant
u32 flags # bit 0 writable
u32 function_count
repeat function_count:
s32 module
string name
list<s32> parameters
s32 result
u32 calling
u32 flags # bit 0 external, bit 1 variadic
list<s32> values
u32 block_count
repeat block_count:
list<s32> parameters
u32 instruction_count
repeat instruction_count:
u32 op
s32 result
list<s32> operands
u32 edge_count
repeat edge_count:
s32 block
list<s32> arguments
u64 immediate
s32 symbol
u32 alignment
s32 effect
s32 origin
s32 entry
s32 origin
```
This covers every current schema field, including currently verifier-gated
types, constants, calling forms and opcodes. The decoder preserves their bytes
and field values, then lets the authoritative verifier accept or reject the
result. Enum values beyond the current declared range and flag bits outside
the masks above are noncanonical format errors before verification.
## Checked array value operations
LIR schema 3 extends `extract` and `insert` with dynamic fixed-array indices.
Their existing immediate-index forms remain: `extract` takes one aggregate
operand, and `insert` takes an aggregate followed by the replacement value.
The member ordinal is in `immediate`.
Dynamic `extract` takes an array and an integer index. Dynamic `insert` takes
an array, a replacement element and an integer index. Their `immediate` is zero.
The verifier requires an actual array type, a fixed integer index and an exact
element/result type match; a record cannot use either dynamic form.
Execution rejects negative signed indices and indices greater than or equal
to the count, including zero-sized elements and zero-length arrays. Narrow
signed values are interpreted at their declared width. An accepted index
selects the packed element interval; extraction copies that element, and
insertion copies the array before replacing the selected interval. Array
values retain value semantics.
Dynamic operations can trap even when their result is unused. Optimization
must retain that check and its source/effect ordering. Source lowering captures
every destination index and checks it before evaluating the right-hand side.
The native encoder performs a bounds check followed by direct indexed frame
addressing rather than an element-by-element dispatch scan.
## Debug section
```text
u32 source_count
repeat source_count:
string source
u32 origin_count
repeat origin_count:
s32 file
s32 line
s32 column
s32 end_line
s32 end_column
s64 begin
s64 end
s32 parent
```
Source strings are copied like all other strings. Origin parent chains and
file references are checked by `LirVerify`; hostile depth is handled by its
bounded iterative validation.
LIR schema version 3 retains the checked source end-line/end-column coordinates
introduced in schema 2.
Coordinates are one-based; `end_line = end_column = 0` explicitly means the
end position is unavailable. A known end cannot precede the start. Byte offsets
are either an ordered nonnegative pair or `begin = end = -1` when unavailable.
The source/saved-IR adapter preserves the checked graph's line/column positions
and emits unknown byte offsets: that graph does not contain byte coordinates.
It never rereads source text to invent offsets. Format framing remains version
1, but readers reject previous LIR schemas with `Version`; rebuild `.zx`
artifacts rather than mixing different instruction or debug contracts.
## Validation and error boundary
Framing errors are reported as `LirCodecProblem`: magic/version/feature,
flags/field/section, overlap, truncation/trailing, count/limit/allocation,
short output, or invalid owner. A structurally decoded program that fails the
lowered verifier returns `Verify` and the complete `LirDiagnostic`.
The reader does not trust producer flags, a previous successful check, or
optional debug data. It constructs no executable program until the full file
is canonical, all caller limits hold, all owned storage is complete, and
`LirVerify` succeeds. Re-encoding a successful decode is byte-exact.
## Heap blocks
`resize(pointer: *T, old_count, new_count) -> *T` is the one heap instruction.
Its number follows `unreachable`, so every earlier instruction keeps its
encoding. `T` is any sized value type a checked view may hold; both counts are
integers and the result has the pointer's type. A null pointer with
`old_count` 0 allocates, `new_count` 0 frees and gives null, and any other
call gives a block that keeps the first `min(old_count, new_count)` elements
and zero-fills the rest. When the engine cannot hold the request, the result
is null and the old block stays valid. Only a block's own base pointer, with
its exact element count, may be resized or freed. The instruction is effectful
and produces a value, so optimization keeps it and its order.
## Current boundary
- This file has no imports, exports, capability/link tables, assets, native
variants, proofs, signatures, compression, checksum, or content identity.
Those belong to the future incompatible ZX revision and linker in step 05.
- It does not execute instructions. The portable engine is step 04.
- It accepts exactly the current verifier's semantic subset. In particular,
verifier-gated schema fields remain explicitly encoded but cannot become an
executable decoded program until verifier semantics exist.
- Format version 1 has no compatibility promise with the planned final ZX
container. Readers reject other versions with an explicit rebuild boundary.
Run the source/saved-IR C, Go and VM regression with:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- \
sh tests/lowered_serial.sh build/bin/ziran
```
+296
View File
@@ -0,0 +1,296 @@
# Target-neutral machine IR contract
Status: implemented for Linux x86-64 SysV as the verified pre-allocation boundary for the
current lowered-IR subset, deterministic [register allocation](#register-allocation), a
separate allocated-program verifier, and a [direct x86-64 encoder](#machine-code-encoder)
that turns a verified allocated program into an in-memory code image with relocations.
`zx2native` selects this encoder for its only native executable path; a native ZX loader
remains unsupported. The implemented native call ABI is general-register only; float and
vector call arguments and results and stack-passed arguments are [unsupported
forms](#supported-call-forms) that fail with a stable diagnostic.
## Public boundary and ownership
The target surface is defined by `compiler_target.zi`:
- `TargetDescribe` describes supported architecture/OS combinations.
- `TargetValid` checks that a description is canonical rather than accepting a caller-modified
register or ABI model.
- `TargetMachineLoweringSupported` separately states whether the current machine lowerer can
execute that description. At present this is Linux x86-64 SysV only.
The owned machine-IR surface is defined by `compiler_machine_ir.zi`,
`compiler_machine_lower.zi`, `compiler_machine_verify.zi`, `compiler_abi.zi`,
`compiler_regalloc.zi`, `compiler_machine_verify_allocated.zi`, and `compiler_x86_64.zi`
(which reuses the byte encoders in `compiler_x86_bytes.zi`):
- `MachineDefaultLimits` and `MachineDefaultOptions` provide bounded defaults.
- `MachineLower(owner, lir, target, options, limits)` verifies the input LIR, copies its
required metadata, lowers it, verifies the resulting machine IR, and publishes the owner
only after success.
- `MachineProgramView(owner)` returns a borrowed flat view while the owner is valid.
`MachineFree(owner)` is repeatable and invalidates all prior views.
- `MachineVerify(program, limits)` validates the target, table bounds, metadata, register
classes, operand constraints, flags lifetimes, calls, stack objects, parallel copies, and
relocations without repairing malformed input.
- `compiler_abi.zi` is the only module that names target registers. The lowerer, allocator and
verifiers ask it for argument and result registers, call clobbers, the fixed registers of
division and shifts (`MachineAbiFixedRegister`), which call classes the native ABI
implements (`MachineAbiCallRegisterClass`) and which relocation addends a target can hold
(`MachineAbiRelocationAddend`). Its register enum is file-private.
- `RegAllocAllocate(owner, target, limits)` replaces a verified `Virtual` program with a
verified `Allocated` one ([register allocation](#register-allocation)).
- `MachineVerifyAllocated(program, limits)` checks an allocated program independently of the
allocator.
- `MachineX64Validate`, `MachineX64Measure` and `MachineX64Encode` verify and encode an
allocated program ([machine-code encoder](#machine-code-encoder)).
Schema version 2 adds the allocation stage. `MachineProgram.stage` is `Virtual` after
lowering and `Allocated` after `RegAllocAllocate`; every operand carries the SSA `value` it
reads or writes (or none), stack objects carry a frame `offset` and the `value` they hold,
and allocated programs add one `MachineFrame` per function, explicit `Spill`/`Reload`
opcodes with a `MachineSpill` record each, and the per-bank scratch registers.
`MachineOwner` owns every published table. Source names and function names are copied into
its byte table and referenced by offsets; source origins, type shape, aggregate members,
function signatures, globals, CFG records, operands, calls, copies, stack objects, and
relocations do not borrow LIR storage. Lowering the same valid input and target produces the
same table order and contents.
## Representation
`MachineProgram` is a deterministic collection of flat, index-addressed tables. Functions
own contiguous block, virtual-register, and stack-object ranges. Blocks own contiguous
instruction ranges. Instructions own contiguous operand and edge ranges. Edges reference
contiguous simultaneous-copy ranges. Aggregate member and function-parameter type IDs share
the owned `type_ids` table.
Operands distinguish virtual and physical registers, immediates, blocks, functions, stack
objects, and globals. Each operand records its use/define role, register class, optional
fixed register, and optional tie to another operand. Condition results use an explicit flags
virtual: `Compare` defines it and the adjacent `SetCondition` consumes it. Calls carry fixed
argument/result constraints plus general, float, and vector clobber masks. A `Fuel` check is
explicit before liveness: its first operand is the amount, its second names the instance
fuel counter through a `FuelCounter` relocation, and it defines (so clobbers) a fresh flags
virtual. Relocations identify the exact instruction operand and symbol rather than hiding
symbol references in an encoder-specific payload.
The current lowerer covers the verified LIR operations represented by the machine opcode
enum: scalar integer and float operations, comparisons and conversions, aggregate pseudos,
checked-memory/address pseudos, direct and indirect calls, CFG transfers, returns, fuel,
traps, and unreachable control. These are pre-allocation pseudos; their presence does not
claim that a complete native encoder can execute every lowered program.
`Allocate` remains an explicit effectful machine pseudo. Every dynamic execution must
produce fresh storage whose lifetime lasts until that allocating frame exits, including
repeated visits to one instruction in a loop or recursive activation. It therefore is not
represented as `StackAddress` plus one static stack object per instruction site. Allocation
and encoding must preserve the pseudo until they implement that exact dynamic frame-storage
behavior.
Aggregate values are stack-class virtuals whose frame objects follow the plan of
`compiler_machine_aggregate.zi`, the native counterpart of zx2wasm's aggregate slots. Values
whose lifetimes never overlap share one object, so an `AggregateInsert` whose destination is
its source's object changes only its member, and a block parameter that shares its
arguments' object needs no edge copy. On x86-64 an extract read only by extracts in its own
block is a view: `StackAddress` and `FieldAddress` or `ElementAddress` compute its address
once, shared with an earlier view of the same storage and member that dominates it, and
`AggregateExtract`/`AggregateInsert` forms whose aggregate operand is that pointer register
read and change its members in place. A changed view put back where it came from emits
nothing. A dynamic member's trailing immediate, like the optional fourth `ElementAddress`
operand, is the bound the shared LIR facts prove its index below, or 0; a proven index is
not checked.
## Linux x86-64 ABI facts
Register numbers follow x86-64 encoding order. General-register argument constraints are
RDI, RSI, RDX, RCX, R8, and R9; float arguments use XMM0 through XMM7 independently. General
results use RAX and float results use XMM0. Calls record the SysV caller-clobbered general
registers and all sixteen XMM registers. Division fixes the dividend and result to RAX and
clobbers RDX; shift counts use RCX. The lowerer obtains all of these from `compiler_abi.zi`
queries for the described target rather than naming x86-64 registers itself.
The general allocatable mask is `0xffcf`; bits 4 and 5 are excluded by the `0x30` reserved
mask, so RSP and RBP can never be assigned as ordinary virtual register locations. Float and
vector registers are separate logical classes but share the same physical XMM bank
(`float_vector_overlap = true`). Allocation must therefore treat a live float and vector
assignment to the same physical number as interference.
Aggregate sizes use Ziran's packed internal layout. Aggregate arguments/results are
represented through stack objects and are deliberately distinct from the external System V
aggregate classification rules. C, System, and Host calling forms, including external
aggregate ABI, varargs, and callbacks, are rejected explicitly; they are not silently
treated as internal calls.
### Supported call forms
Machine IR describes the whole internal call shape: float arguments carry their XMM
constraints, a seventh integer or any aggregate argument is counted in
`stack_argument_bytes`, and allocation lays out the outgoing area. The implemented native
call ABI is narrower. A call may pass at most six arguments, each a general-class value in
its ABI register in order, and may return nothing or a general-class value in RAX.
`MachineVerifyAllocated` rejects every other call with `Unsupported` at the first offending
argument or result operand, or at the call when it reserves stack argument bytes: float and
vector arguments and results, aggregate arguments, arguments beyond the sixth, and any
outgoing stack bytes. The check runs before an encoder starts, so no unsupported call
reaches encoding or another engine. Incoming stack parameters of a function that is not
called natively remain representable and are verified against the parameter order. The full
SysV argument/result classification, including float and stack passing, is later work,
tracked in `plans/open-work.md`; it is not partially implemented.
## Described targets versus executable targets
Canonical descriptions exist for maintained x86-64, ARMv7, AArch64, and wasm32 OS
combinations so later allocation and backend work shares one target model. A valid
description is not an implementation claim. Linux and Android x86-64, AArch64 and ARMv7
lower, allocate and encode; wasm32, Windows, macOS and WASI fail machine lowering with
`UnsupportedTarget`.
## Register allocation
`RegAllocAllocate(owner, target, limits)` in `compiler_regalloc.zi` takes the owner's
verified `Virtual` program and, on success, replaces it with a verified `Allocated` program.
The allocation is built in a separate owner and verified with `MachineVerifyAllocated`
there; only then are the two owners' tables exchanged with `VecSwap`, which moves storage
without allocating, so no step after the owner starts changing can fail. On any failure,
including one the allocated verifier finds in the built program, the owner keeps its
original program and the `MachineDiagnostic` names the input function, block, instruction,
operand and virtual: an allocated instruction maps back to the input instruction it rewrote,
with operands at the same positions, and a transfer the allocator inserted reports only its
function and virtual. Each function is processed in a fixed order:
1. `MachineVerify` and `MachineVerifyFuel` run first. Every control-flow cycle must pass a
fuel check, and every function a direct call or a taken address can reach must charge fuel
in its entry block before any call. A missing or malformed check fails with `Fuel`.
2. Constraints become explicit transfers. A fixed input is moved into its register just
before the instruction, a fixed result out of it just after, a register parameter out of its
incoming register at entry, and a tied input without a fixed register is copied into a short
interval that the result must reuse. Division keeps the dividend and quotient in RAX and RDX
clobbered across the instruction, shift counts use RCX, and call arguments and results use
their ABI registers.
3. Block liveness is solved over the item order, then each SSA virtual gets one hull
interval with its use positions. Block parameters are defined at the block start; edge-copy
sources are used at the predecessor terminator.
4. Linear scan runs per register bank (general; float and vector share the XMM bank on
x86-64) inside the target's allocatable masks minus one scratch register per bank (R11 and
XMM15). Fixed operands, early clobbers and call clobbers block registers. An interval is
split where its register becomes blocked; under pressure the value with the farthest next
required use goes to memory until that use. Values live across a call take callee-saved
registers (RBX, R12–R15) or are spilled with reason `Call`.
5. Split boundaries, fixed transfers, block-parameter copies and edge location fixes become
`Move`, `Spill` and `Reload` instructions. Each edge's copies are one parallel copy,
sequentialized with cycles broken through the scratch register or a frame `Temporary`; a
branch edge that needs moves gets its own block (`lir_block` is -1). Allocator transfers
preserve flags, so they may sit between a compare and its consumer. A transfer with equal
source and destination register renames a value and encodes no bytes.
6. The frame pointer is pushed on entry. Callee-saved registers the function writes get
`CalleeSave` homes; values, spills and temporaries sit at aligned negative frame-pointer
offsets; outgoing stack arguments occupy the 16-byte aligned bottom of the frame; incoming
stack arguments start 16 bytes above the frame pointer in parameter order. The frame size is
a multiple of 16.
Every `Spill` and `Reload` has a `MachineSpill` record with its value, slot, register,
reason (`Pressure`, `Call`, `Fixed`, `Parameter` or `Cycle`) and nearest source origin.
Flags-class operands or copies, a virtual read-modify-write operand, conflicting fixed
registers, broken ties, call clobber masks that keep caller-saved registers or clobber
reserved ones, non-internal calling forms, unsupported targets and exceeded limits fail
explicitly. Nothing is routed to another engine.
`MachineVerifyAllocated(program, limits)` in `compiler_machine_verify_allocated.zi` is
independent of the allocator. It rejects virtual operands, unresolved edge copies, registers
outside the bank masks (scratch registers only in transfers), fixed-register mismatches,
broken ties, malformed transfers, bad relocations, relocation addends the target cannot hold
(a direct call, function address or fuel counter carries none; a global address carries a
signed 32-bit addend), [unsupported call forms](#supported-call-forms), spill records that
disagree with their instruction, misplaced fuel checks and frame layouts that are
misaligned, overlapping, missing callee-saved homes or whose incoming stack arguments
disagree with the parameter order. A forward dataflow over registers, flags and stack
objects then proves that every use finds its value: a wrong value is `Interference`, a value
lost to a call or clobber is `Clobber`, a missing one is `Undefined`, and a parallel copy
that reads a source it already overwrote is `Copy`.
## Machine-code encoder
`compiler_x86_64.zi` encodes a program that passes `MachineVerifyAllocated` for Linux x86-64
SysV into an in-memory image: code bytes, function, block and instruction offsets, and
PC-relative 32-bit relocations for global addresses, the fuel counter and the trap handler.
Direct calls and function addresses inside the image are resolved by the encoder. A
measuring pass and an exactly sized writing pass must agree on every offset.
`MachineX64Encode` publishes the image only after verification, form checks and measuring
succeed; any diagnostic leaves the output owner unchanged. Every instruction form the
encoder does not implement is a hard diagnostic, never another engine.
### ARMv7 (A32)
`compiler_armv7.zi` encodes for armv7a Linux and Android. LIR is target-neutral: pointers
and function values are 8-byte slots and `s64` is the common integer, while the pipeline
keeps one physical register per virtual. ARMv7 therefore describes its general bank as
register pairs, so allocation, verification and lowering stay as they are:
- Pair n is (r2n, r2n+1) for n = 0..4; pair 5 is (r12, lr), the bank scratch, so r12 and lr
are free inside any instruction and lr is saved by every prologue. r10 is the encoder's
temporary and the base it rebases a frame slot beyond A32's 4 KiB reach into; r11 is the
frame pointer. Calls clobber pairs 0, 1 and 5; pairs 2-4 (r4-r9) are callee-saved.
- A value of 32 bits or less lives in the even register, a 64-bit value in both, low word
first. Raw machine addresses are 32-bit. Floats are d0-d15 (VFPv3-D16), f32 in s(2n); d0-d7
are caller-saved, d7 the float scratch.
- Between generated functions: general arguments in pairs 0 and 1, floats in d0-d5, the rest
on the stack in 8-byte slots; results in pair 0 or d0; the record-result address in r10.
Indirect calls BLX pair 4. The entry widens a narrower result into r1 for its C caller.
Generated code reaches C only through the loader's veneers, so softfp never meets it.
- 64-bit arithmetic is pair sequences. 64-bit divide and remainder and int64/float conversions
call loader helpers through a `RuntimeHelper` relocation (symbol = `MachineHelper`),
operands and result at sp; the helper and resize veneers keep every register but lr.
Addresses are MOVW/MOVT relocation halves (addend 0 and 2); calls and veneers are BL.
- A dynamic element's address goes in lr (the address scratch), leaving r10 for the
instruction's other frame operand, and the frame layout puts the pointer runtime's arena
mark and chain beside the callee saves, so those sequences never rebase.
- Copies and zeroing of 64 bytes or more run a word loop (r10 and lr walk the two sides, r0
counts and is kept at sp meanwhile), as AArch64 runs a 16-byte q31 loop and x86-64 an xmm15
loop, so code size does not grow with record size.
## Direct native code versus generated-code exporters
Direct native code means that Ziran's own encoders write machine code from verified IR, with
no generated C, external assembler, C compiler or system linker. `zx2native` uses the
machine-IR path: it lowers verified ZX through the machine pipeline, writes the resulting
Linux x86-64 image as an ELF executable, and never reroutes unsupported forms to another
engine. Source and saved `.zir` first go through optimized ZX serialization and
verification. In-memory native ZX loading and runtime cutover remain milestone M3.
The C target (generated C compiled by a C toolchain) and the Go target (generated Go built
by the Go toolchain) also produce runnable binaries, but they are separate exporters with
their own toolchains and test rows. They are never a fallback for direct native code: a form
the native path does not implement fails with its diagnostic and is not rerouted to C, Go,
the portable engine or any other backend, as the [gap policy](gap-policy.md) requires. The
focused tests below run their fixtures with `--target=c` only as the test harness; what they
check is the direct native pipeline.
## Focused local test
```sh
env -u DISPLAY -u WAYLAND_DISPLAY HARMONY_DESKTOP_RECOVERY=0 \
build-queue -- make CHECK_FILTER=machine_ir check
env -u DISPLAY -u WAYLAND_DISPLAY HARMONY_DESKTOP_RECOVERY=0 \
build-queue -- make CHECK_FILTER=x86_encoder check
env -u DISPLAY -u WAYLAND_DISPLAY HARMONY_DESKTOP_RECOVERY=0 \
build-queue -- sh tests/regalloc.sh build/bin/ziran
```
The machine-IR fixture checks target descriptions, real LIR lowering, ABI constraints, owned
metadata, deterministic output, dynamic-allocation representation, explicit unsupported
targets/calling forms, bounded limits, malformed MIR rejection and repeatable cleanup. The
x86 encoder fixture checks exact bytes, frames, relocations, fuel, traps, pre-encoding
call/addend rejection and output preservation. The allocation fixture lowers real LIR and
checks register pressure, call splitting, spills and reloads, division and shift registers,
flags, register, memory and aggregate copy cycles, float and vector banks, frame and
incoming stack-argument layout (including out-of-order incoming homes), fuel placement,
deterministic output, explicit unsupported forms, and rejection of malformed allocated
programs at the faulting location. Its late-failure fixtures allocate successfully and are
then rejected by the allocated verifier (a float call argument, a float call result, an
aggregate stack call argument and a direct call relocation with an addend); each checks the
input-location diagnostic and that the owner still holds its unchanged `Virtual` program,
and the addend fixture allocates the same owner once the input is valid. Float call
arguments and results, stack call arguments and global-address addends outside 32 bits fail
in `MachineVerifyAllocated` before any encoder pass runs.
+237
View File
@@ -0,0 +1,237 @@
# Delivery milestones and plan review
The ten step files define **what** 100% means. This file defines the **order**
in which their checklist items are closed, so that real execution and speed
evidence arrives in stages instead of only after every platform, object format
and profiler is finished. No milestone below changes a step's exit gate, and no
milestone is the completed upgrade; only [step 10](10-inspection-performance-and-cutover.md)
can declare that.
## Review of the ten-step plan (2026-11-12)
What the plan gets right:
- One verified portable instruction program (LIR) feeds the interpreter, the
ZX container; native always reads verified ZX before encoding. Listings are views of encoder records,
not a write-and-reparse stage.
- Every boundary is verified and bounded; unsupported constructs fail
explicitly instead of silently falling back to another engine.
- The [gap policy](gap-policy.md) makes missing work observable: a gap has a
stable error and an open matrix cell, never a substituted engine.
- Measurement rules (Alpha physical host, raw samples, symmetric 1.5×IQR) are
strict enough to make the final comparison trustworthy.
What needed to change:
1. **Big-bang completion.** The owner's requested ZX speed comparison was gated
behind step 10, which also requires AArch64/ARMv7/Windows/macOS/wasm
backends, COFF/Mach-O linkers, signing and profiler integration. Nothing
measurable would reach the owner until all of that existed. The milestones
below deliver labeled interim comparisons on the first platform row.
2. **The baseline came last.** Step 10 says to preserve the old engines'
"before" measurement before replacing them, but scheduled it at the end.
The plan now requires a direct physical-host baseline at milestone M0 and
rejects virtualized receipts.
3. **Breadth without a target workload.** Lowering grew construct by construct,
while the actual comparison workload, [`bench/zx_compare.zi`](../bench/zx_compare.zi),
still cannot lower: it needs `#foreign host_api` calls and string values.
Step 03 work is now ordered by a measured corpus-coverage report, starting
with the benchmark workloads.
4. **Two native code paths existed.** The old LIR-to-x86-64 encoder and the
[machine IR](machine-ir.md) boundary had overlapped, so every native feature
risked being implemented twice. They have been merged onto the machine-IR
path and the old encoder is deleted; new native features land only there.
5. **Speed-critical shortcuts were not tracked as debt.** Native procedure and
pointer tokens were dispatched by a linear scan, native code was stack-slot
only, and native `Fuel` emitted no bytes. These became M2 exit criteria and
are done: a pointer token carries its slot, version and offset and is checked
in constant time, a procedure value is a code address called through a
register, values live in allocated registers, and `Fuel` decrements the
instance counter at loop headers and function entries.
6. **Stale status.** Step 05 was still "planned" after the revision-28
container landed, and the README listed the container and machine IR as
wholly outstanding. The statuses now match the code.
7. **Unbounded extras.** The textual-listing re-assembler, the GNU inline
assembly template surface, 32-bit x86 and RISC-V are post-cutover
extensions unless the step-01 matrix names them as maintained rows.
Recorded decision: the checked-IR-to-LIR adapter stays in C
([`compiler_zir_lower.zi`](../cmd/compiler_zir_lower.zi)) because the checker's
program records are C structures. Everything after LIR (verifier, codec,
engine, optimizer, machine IR, encoders, container, linker) stays in Ziran.
Step 03's proposed `compiler_lower*.zi` modules apply only if the checker
itself moves to Ziran.
## Rules that apply to every milestone
- A new language feature lands in LIR, the verifier, the codec and the portable
engine first. Native support follows on the machine-IR path.
- Each row of the platform matrix is cut over separately. A row switches its
default to the new format only after its own gate passes. Before that switch,
the direct target is a named Gap and fails; an explicitly selected legacy
command remains a comparison tool, never a fallback.
- Portable, native, Wasm, C and Go execution are separate targets. A request for
one never routes to another. Missing CPU features, host services, `#asm`
variants, parallel/GPU support, object formats or loaders are preflight errors.
- Every Gap has the stable diagnostic and side-effect-free negative fixture
required by the [gap policy](gap-policy.md). A fallback, downgrade, skip,
emulated run or legacy-engine result cannot close a milestone.
- Interim measurements follow every rule in step 10, are labeled *interim*,
and never replace the final full comparison.
- Hostile-input hardening is mandatory at trust boundaries (ZX container and instruction
decoders, loaders, host results). Internal stages rely on the verifier
instead of duplicating its checks.
## Milestones
| Milestone | Scope | Exit evidence |
| --- | --- | --- |
| **M0** Integrate and baseline | Land the in-flight slices behind one passing local `make check` and `make check-bootstrap`. On Alpha's physical host, measure the old portable VM and old TinyCC native ZX with the M1 workloads, hashing and preserving the exact old binaries. | Green local suites; baseline receipt with raw samples under `bench/results/`. |
| **M1** Workload-complete portable path | Typed host capability calls (`s64 -> s64` first, then scalar/string/record signatures), in-bundle `--bind` providers, immutable strings (literal, copy, `.count`, checked index), runtime global initializers. The revision-28 container lists capabilities recomputed from reachable `HostCall` instructions. Add a C embedding API for the new engine (open, list capabilities, bind, run with fuel) that the existing comparison harness can drive. Unsupported operations are Gap diagnostics, not calls into the old VM. | Corpus-coverage report shows every benchmark workload lowering; source, saved IR and new ZX agree with the oracle; negative fixtures account for every remaining Gap; **interim comparison 1**: explicitly selected new portable engine vs explicitly selected old VM. |
| **M2** Register-allocated x86-64 | Liveness, linear-scan allocation with splitting and spilling, a post-allocation verifier, and machine-IR-to-x86-64 encoding that reuses the existing byte encoders. Fuel at loop back-edges and calls. Constant-time token dispatch. | Every x86-64 fixture passes on the sole machine-IR path; no alternate native encoder remains. |
| **M3** Native ZX on Linux x86-64 (first cutover row) | In-memory loading with W^X pages, relocation of the same encoder output, host trampolines, stack and fuel checks, and a content/CPU/backend-keyed cache. `ziran run app.zx` runs revision 28 natively on linux-x86_64; unsupported native features fail preflight without starting the portable engine. | Full local suite on the new default for that row, including no-fallback negative fixtures; installed tool verified; **interim comparison 2**: explicitly selected new native ZX vs the M0 TinyCC native ZX receipts, plus AOT and C controls. |
| **M4** ARM rows and direct wasm | AArch64 and ARMv7 (USB Moto) machine targets, and direct wasm lowering from LIR. Each row is cut over separately. | Per-row execution evidence; Moto comparison on the device. |
| **M5** Objects, linker and foreign libraries | Relocatable ELF/COFF/Mach-O, archive reading, external C ABI and foreign libraries, Windows/macOS ABIs and required signing. | Step 07/08 rows with real launches. |
| **M6** Inspection closure and final cutover | Unwind/debug/profiler mapping and the owner's **full before/after ZX comparison**. The TinyCC/generated-C ZX path is already removed. | The step-10 completion receipt. |
## Current position
The experimental `zi2zx` pipeline now optimizes verified LIR before producing
ZX, and native source compilation serializes and reads those same ZX bytes.
The standalone instruction artifact/CLI is removed; source LIR remains an
inspection view. Direct Linux x86-64 hello has short constants, fallthrough
edges, frame-free literal writes and compact adjacent read-only file data.
Retained tests require text below 200 bytes, ELF below 1.5 KB and valid retained
function extents, with inlined platform service declarations omitted rather than trap
aliases. Pointer token runs lower with bounds-checked base/index arithmetic.
On the machine-IR path, native code consumes the same fuel checkpoints as
the engine (loop headers and function entries) and AOT executables start with
the same unbounded budget as a bundle run (`zx2native --fuel N` sets one).
Every calling function checks a stack limit and traps on runaway recursion.
Host calls pass and return records, arrays and strings, and the optional ZX
debug attachment (`zi2zx --debug`) gives native maps and native trap
diagnostics source lines. Wasm lowers the same verified ZX, both for
`zx2wasm` and for the bundle Wasm tier.
There is one ZX format. Every `.zx` is revision 28; the semantic bundle writer
and reader, the portable VM with `run --vm`, `BundleUsePortableVm`,
`BundleInstantiatePortable`, `libziran-vm.a`, bundle libraries, TinyCC and the
generated-C native ZX route are removed. On linux-x86_64, `ziran run app.zx`,
`zi2zx run` and the embedding API's `Auto` policy load the bundle's verified
program as native code into W^X memory, with the engine's pointer, freed-block
and bounds checks; a bundle native code cannot run fails before it starts with
a named gap, and nothing falls back to the engine. A browser with the Wasm
provider runs the Wasm tier and other CPUs the engine. The old VM and TinyCC
measurements survive as the M0 baseline receipts.
Tier-0 check elision (2026-11-15, trust-tier steps
0-2): `cmd/compiler_lowered_proven.zi` computes, once per verified program,
each pointer's root (a global, or an `allocate` in the same function) and the
fixed-array indices an interval analysis proves in range. x86-64 lowering
turns a load, store or zero through a rooted pointer into `PointerDirect`
(the root's raw start plus the token's offset); `MachineVerify` rejects any
memory access whose address is not a `PointerResolve`, fresh `ArenaAllocate`
storage or a `PointerDirect` it re-derives to the same root, and
`zx2wasm` reads the same index proofs. A fact carries the pointer's room
(bytes to its root's end that every execution may reach), so a direct read
of a constant text through its view is covered too, and x86-64 drops the
index check of an element proven below its bound (`ElementAddress` with an
immediate bound). `tests/proven_pointer_cases.zi` prints the per-fixture
counts and holds the hostile twins.
M0 integration is done (2026-11-15): the allocator fix, the AArch64
encoder, the native default with checked pointers, the self-hosted C-backend
build/cache/process ports and the legacy deletions are committed. M4's first slice, the explicit
[target registry and preflight](07-architecture-and-platform-coverage.md#target-registry-and-preflight),
lists every CPU/OS row with its gap-policy state; no row is Implemented yet,
so every general registry selection fails preflight with
`assembly.gap.target-unimplemented`. `zx2native` implements
`--target x86_64 --platform linux` (ELF) and, as M5's first slice,
`--platform windows` (PE32+ through kernel32) through the machine-IR pipeline;
other target rows fail with the stable native platform-service gap before
input or output, and AArch64 encodes machine code but has no AOT ELF writer. The revision-28 container, frame-local
`Allocate`, local scalar address-taking and the pre-allocation machine-IR
boundary are implemented. On Omega on 2026-11-15, with native as the
linux-x86_64 default, a clean clone of master passes `make check-bootstrap` and
265/266 of the full `make check`. The one failure is `zstd_go`, which needs
Go 1.25 (Omega has 1.24.4). Native code does not re-check a pointer's element
type: the load-time verifier makes a wrong-type access unrepresentable, and
`tests/verified_loading_cases.zi` shows a retyped load refused by the reader,
`zi2zx run` and `zx2native` before any native code (M3 step 2, closed).
M3 is done (2026-11-15). Interim comparison 2 ran on Alpha's physical host at
`31d291f3` with all 72 samples oracle-verified and the M0 TinyCC rows
byte-identical to their receipt:
[`bench/results/zx-compare-alpha-physical-native-2026-11-15.json`](../bench/results/zx-compare-alpha-physical-native-2026-11-15.json),
summarized in [Interim comparison 2](../bench/zx_compare.md#interim-comparison-2-native-zx-on-linux-x86-64-2026-11-15).
Warm native ZX medians were 0.0483 ms scalar and 0.0633 ms structured per
entry: 11.1× / 16.1× faster than the portable engine, 2.82× / 1.48× slower
than the M0 TinyCC native tier (0.0171 / 0.0427 ms), and about 10× slower
than the C control (0.0046 / 0.0063 ms). M0's Alpha physical-host baseline
and M1's portable-engine comparisons are in
[interim comparison 1](../bench/zx_compare.md#interim-comparison-1-new-portable-engine-2026-11-12)
and the [final pointer-dispatch cohort](../bench/zx_compare.md#final-pointer-dispatch-cohort-2026-11-13).
M1 and M2 are done (2026-11-15): typed host capability calls, in-bundle
providers, and Linux x86-64 SysV liveness, linear-scan allocation with
splitting and spilling, the independent allocated-program verifier and direct
encoding of verified machine IR. The implementation also covers
dependency-ordered once-only runtime initializers, local aggregate/procedure
address-taking, checked portable slices and string comparison, native
readonly data, the no-libc Linux x86-64 console veneer and validated typed
host values with instance-owned returned bytes, released once nothing the
program can reach names them. Resizable collection ownership, reentrant
callbacks and general native string/arbitrary-host instructions remain
explicit gaps. Open work from M4 on is in `plans/open-work.md`.
## Review of M5 and M6 (2026-11-24)
The first review's diagnosis still holds, and M5 is the milestone where it
repeats. M5's exit gate, "Step 07/08 rows with real launches", bundles four
kinds of work whose evidence is not available in the same place:
- ELF static archives and the C ABI for the Linux row are testable in this
checkout; the archive slice landed on 2026-11-24 and `tests/machine_elf.sh`
links, runs and rejects them.
- A real Windows launch is not available here. Wine parity is evidence that
the PE32+ encoding, Win64 ABI, imports and unwind records are right, but it
is emulation and cannot close a native row under the gap policy. The matrix
needs an explicit emulated state: Wine results stay recorded as emulated,
not as a Windows host result.
- Mach-O objects, Apple64 and signing need an Apple host and credentials.
They should stay a named Gap in the target registry until such a host and a
signing identity exist; implementing the container speculatively cannot
produce the required real launch.
- The in-process loader is per row. Linux x86-64, AArch64 and ARMv7 load
native ZX today; Windows and macOS loaders belong to their host slices, not
to a shared "archives" item.
Order the remaining work by the evidence each item can actually produce here:
1. **M5a** Linux ELF: shared objects (done) and static archives (done). Keep
each new C ABI shape and each archive subset behind `machine_elf.sh` plus a
named gap for everything else.
2. **M6a** inspection closure for rows that are Implemented: Linux unwind
registration (`.eh_frame` or an equivalent without libc), the existing
debug attachment, and a supported profiler map, with bounded
source-to-byte attribution. This is local work and can land now.
3. **M5b** a real Windows host run, on hardware or a dedicated CI Windows
runner: the same `tests/zx_windows_parity_cases.zi`, with its current Wine
rows kept as the emulated control. Until then the row stays open.
4. **Native speed** next, because it is the owner-visible deficit and the
receipts exist: Vec growth, unique-use Insert-in-place and borrowed call
arguments, proof-carried bounds elision, the k-nucleotide copy loop, then
the print-heavy examples. These are Alpha-only measurements; do not queue
target breadth ahead of them.
5. **M5c** Mach-O/Apple64 and signing, only when an Apple host and signing
identity are available. **M5d** the Windows loader follows M5b.
6. **M6b** the owner's full before/after comparison on Alpha's physical host
last, because it must compare the finished implementation, not an interim
slice.
Two smaller corrections: step 08 lists a textual listing re-assembler and
every object format for all rows, while the review above intentionally keeps
only maintained target rows and treats the listing as inspection, not a
required assembler dialect; and a "real launch" must be defined in the step-07
matrix as not emulated, so no Wine, emulator or cross-compilation result is
counted as a row's execution evidence.
+177
View File
@@ -0,0 +1,177 @@
# Verified lowered-IR optimization pipeline
Status: bounded scalar pipeline, mandatory before experimental ZX production.
Source `--opt` selects optimized LIR inspection and source optimization reports;
ZX input is never reoptimized. This module does not select target
instructions, allocate registers, or claim a performance result.
The implementation is
[`cmd/compiler_opt.zi`](../cmd/compiler_opt.zi). It consumes a verified
`LirProgram`, builds an independent owned copy, runs enabled transformations in
a fixed order, verifies the program after every enabled pass, and exposes the
verified result for inspection or later execution.
## Public API
```zi
LirOptDefaultOptions :: () -> LirOptOptions
LirOptBuild :: (owner: *LirOptOwner, program: LirProgram, limits: LirLimits,
options: LirOptOptions) -> LirOptResult
LirOptProgram :: (owner: *LirOptOwner) -> LirProgram
LirOptFree :: (owner: *LirOptOwner)
```
`LirOptOwner`, `LirOptOptions`, `LirOptPassCounters`, `LirOptCounters`,
`LirOptResult`, and `LirOptProblem` are ordinary named exported records and
enums. Generated C consumers use normal module-prefixed symbols and records.
The default options enable constant folding, copy propagation, CFG
simplification, and dead-instruction elimination with at most eight folding
rounds.
The input is immutable. `LirOptBuild` first verifies it under the supplied
limits and serializes it through the canonical owning lowered-IR codec before
changing any instruction. The result therefore does not borrow a module name,
function name, type member list, operand list, edge argument, constant, source,
or origin from the caller.
`LirOptProgram` returns a view borrowed from the owner. The view and every
nested slice or string expire at the next build or free on that owner. Building
again from that same borrowed result is supported because the next owned copy
is encoded before the preceding owner storage is released. A failed build
empties a non-null owner. Empty and repeated frees are harmless. A null owner
returns `Owner`.
## Pass order and verification boundaries
The order is fixed and deterministic:
1. Verify the immutable input.
2. Fold exact scalar constants.
3. Propagate proven identity copies.
4. Simplify constant control flow and remove newly unreachable blocks.
5. Remove unused, nontrapping pure instructions.
6. Verify and expose the final owned program.
Each enabled numbered pass calls `LirVerify`, even when it reports no change.
The folding pass re-encodes its appended constant table through the canonical
codec, so no temporary vector or local slice escapes. Structural rewrites
compact values, block parameters, operands, edge arguments, block IDs, entry
IDs, and instruction result IDs together. Every remaining declared SSA value
continues to have exactly one definition.
`LirOptResult.diagnostic` is the authoritative input or pass-verification
diagnostic on failure. Successful results contain the exact input/output
function, block, value, and instruction counts. The four per-pass counter
records separately report runs and changed instructions, values, blocks, and
constants. These counters follow stored function/block/instruction order and do
not depend on allocator order or hashes.
## Implemented transformations
Constant folding implements exact boolean and fixed-width integer arithmetic,
bit operations, negation, comparisons, same-width numeric bitcasts,
boolean/integer conversions, and integer widening or narrowing. Integer
overflow is masked to the declared width. Signed comparison, division,
remainder, and right shift use the portable engine's two's-complement rules.
Division and remainder fold only with a nonzero divisor. A shift folds only
when its count is in range. Unsafe constant divide and shift instructions stay
in the program and retain their traps. Float bitcasts preserve the bits, but
float arithmetic and numeric float conversions are not folded.
Copy propagation currently proves only same-type `Bitcast` identities. It
rewrites every dominated operand and edge argument to the original value.
Dead-instruction elimination then removes the unused identity instruction and
compacts its value ID. It does not guess that conversions or block-parameter
cycles are copies.
CFG simplification turns a branch into a jump only when its condition is a
verified boolean `Constant`. It keeps the selected edge and its arguments,
computes reachability from the function entry, removes only blocks that are no
longer reachable, and remaps every surviving block and value reference.
Dynamic branches, loop headers, backedges, and phi-like block-parameter cycles
are retained.
Dead-instruction elimination reaches a fixed point for unused `Constant`,
`Null`, add/subtract/multiply, integer bit operations, negate, comparisons,
`Bitcast`, `Aggregate`, and immediate-index `Extract` and `Insert` results.
These operations are pure and nontrapping under the current verifier and
portable engine. Dynamic-index `Extract` and `Insert` stay in the program
because their bounds checks can trap, including when their result is unused.
## Preserved behavior
No pass changes the order, count, immediate, or effect number of `Fuel`
instructions. Calls, indirect calls, host calls, loads, stores, allocation,
copy, zeroing, traps, and all other effectful instructions remain ordered.
Unused divide, remainder, shift, and conversion instructions remain because
they can trap. Address operations are retained conservatively. An instruction
that is folded or changed from branch to jump keeps its source origin. Retained
instructions, functions, sources, and origin chains otherwise remain
byte-for-byte data-equivalent through the owning codec.
There is no fast math, reassociation, speculative execution, speculative
memory access, effect motion, or synthetic float behavior.
## Resource bounds
`LirLimits` bounds each input/pass verification, the owned decoded program,
table sizes, instruction/value/block counts, and codec decode. Independently,
the optimizer charges its own deterministic table visits against
`limits.work`. `LirOptResult.work` is only this optimizer-accounted work. It
does not include verifier or codec visits, elapsed time, CPU instructions, or
performance.
Every explicit optimizer scratch vector and encoded buffer is charged against
`limits.bytes`. `LirOptResult.scratch_bytes` is the cumulative logical scratch
allocation charged during the build, including storage already released. It is
not current or peak RSS and does not include the separately bounded owned
decode. Counts and size arithmetic are checked before allocation, folding
rounds are capped at 64, and allocation failure is recoverable.
The codec and verifier retain their own documented fixed format, allocation,
and work bounds. Optimization does not recursively traverse
attacker-controlled SSA or CFG depth.
## Inspection
Keep the original `LirProgram` for the before view and call
`LirOptProgram(owner)` for the after view. Compare the result counters first,
then walk functions, blocks, instructions, origins, and effects in stored
order. The owner view can also be passed directly to `LirWrite`,
`LirExecPlanBuild`, or a native encoder after inspection.
The pass manager does not print dumps or timing internally. A CLI integration
can render the two explicit views and the deterministic counters without
giving the optimizer filesystem or terminal ownership.
## Explicitly unimplemented passes
The following are not represented by placeholder counters or no-op names:
- float arithmetic folding and float numeric-conversion folding;
- block-parameter coalescing, jump threading, and general block merging;
- range propagation, redundant-check removal, common subexpression
elimination, and load/store optimization;
- inlining, loop transformations, vectorization, or fuel-aware code motion;
- machine IR, instruction selection, register allocation, spilling, and ABI
lowering.
Those transformations need separate semantic proofs and verifier boundaries.
Their absence is visible rather than inferred from a generic optimization
level.
## Local test
The retained Ziran fixture performs before/after portable-engine execution,
including loops and block parameters, aggregates, function values, divide and
shift traps, exact Fuel consumption, limits, invalid input, repeated builds,
failed builds, and repeated free. Its launcher runs source and saved IR through
generated C, generated Go, and bundle execution on the engine:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- \
sh tests/compiler_opt.sh build/bin/ziran
```
Performance compilation and measurement are separate work and run only on
Alpha's physical host.
+263
View File
@@ -0,0 +1,263 @@
# ZX performance comparison receipts
`bench/assembly_compare.zi` is the reusable, measurement-free report processor for the ZX
before/after campaign. It reads raw receipts produced on one physical host and atomically
writes a Markdown report with absolute medians, per-case ratios, regressions, missing cells,
raw samples, and audited outlier indices.
This is reporting and collection infrastructure, not a benchmark result. The strict
five-core campaign has not run; that pending work is tracked in `plans/open-work.md`. The
separately labeled portable-engine comparison has run on physical Alpha; it does not measure
the missing new-native cell or establish a native ZX speedup.
## Invocation
```sh
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
build/bin/ziran run --target=c --root bench --module-path . \
bench/assembly_compare.zi -- INPUT.json OUTPUT.md
```
The processor does not invoke a compiler, VM, workload, timer, or remote host.
`bench/assembly_collect.zi` is the separate collector. Its measurement-free plan validation
may run locally:
```sh
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
build/bin/ziran run --target=c --root bench --module-path . \
bench/assembly_collect.zi -- --validate PLAN.json
```
Actual collection runs only in the canonical checkout on Alpha's physical host:
```sh
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
build/bin/ziran run --target=c --root bench --module-path . \
bench/assembly_collect.zi -- PLAN.json bench/results/CAMPAIGN/raw.json
```
The collector checks its plan completely before execution, then attests the fresh hostname,
exact `lscpu` model name, `uname -srmo` result, and `systemd-detect-virt` result `none`. The
plan must name physical host `alpha` and an `alpha...` hostname. A failed attestation occurs
before input hashing, cache changes, or workload commands. This is a host guard, not
permission to run the command from another machine with copied or edited provenance.
### Collector plan, version 1
The plan root has exactly ten members: `schema_version` (exactly `1`), `campaign`,
`physical_host`, `hostname`, `cpu`, `os`, absolute `working_directory`, absolute
`collector_work`, `required_cells`, and `jobs`. `collector_work` must be a child of the
working directory. Required cells use the same four-member schema documented below and may
include modes that have no job; those remain visible as missing cells in the generated
report.
Each job has exactly these 24 members:
| Member | Contract |
| --- | --- |
| `receipt_id`, `case`, `engine`, `selector` | Unique receipt/cell identity and an exact supported engine/selector pair. |
| `phase`, `metric`, `unit` | One documented phase triple: duration in `ns`, throughput in `ops/s`, memory in `KiB`, or size in `bytes`. |
| `command` | Nonempty argv array. The absolute executable must be in `runtime_closure`; no shell parses it. |
| `verification` | Optional argv array run outside the measured interval. Compile and size jobs require it. |
| `runtime_closure` | Nonempty ordered list of `{path, sha256}` objects. It must contain every executable, runtime, header/module manifest, linked dependency, and helper needed to reproduce the selected baseline; every listed digest is checked before and after collection. |
| `workload`, `input_path`, `input_checksum` | Exact workload identity, regular input/artifact path, and `sha256:` digest. |
| `semantic_settings`, `correctness_expected` | Canonical common semantics including `process=fresh-child-per-sample`, and the exact `sha256:` of expected stdout. |
| `iterations`, `repeats`, `warmups`, `timeout_ms` | Positive work per sample, 3–4096 raw samples, phase-checked warmups, and a bounded child timeout. |
| `cache_policy`, `cache_directory` | `private-cold-each-sample`, `private-warm-across-samples`, or `immutable-artifact-no-engine-cache`. Private cache paths must be children of `collector_work`; only those paths are reset. |
| `environment` | Ordered explicit `NAME=value` settings or bare names to remove. Display variables are always removed and desktop recovery is disabled. |
| `artifact` | Measured build/size artifact under `collector_work`, or `-` when the phase does not produce one. |
| `rss_tool` | Absolute GNU/BusyBox time executable for memory jobs, declared in the closure, or `-` for every other phase. |
Every sample starts a fresh child process. Warm phases require at least one discarded warmup
and preserve their private cache across warmups and samples. Cold private caches are reset
before every measured sample. Compile and size jobs remove only their declared artifact
before each sample, then run their separate correctness command. Duration uses monotonic
nanoseconds; throughput requires `timing=internal-kernel-ns`, reads a positive
kernel-nanosecond value from the measured command, and divides exact iterations by that
internal interval, so process startup is not mislabeled as sustained work. Throughput also
requires a separate untimed correctness command. Memory uses the child launcher's peak-RSS
KiB; size uses the freshly produced regular file. Correctness stdout must match the expected
digest for every sample. Any command, timeout, checksum, correctness, or post-run closure
failure aborts without replacing the raw receipt file.
The receipt's `toolchain` preserves the selector, cache/process policy, complete ordered
runtime-closure identities, verification argv, and explicit environment; `flags` preserves
the measured command argv after its executable. The collector emits only the strict
version-1 four-member document accepted by the processor.
Current honest selectors are:
| Engine | Selector | Status |
| --- | --- | --- |
| `old-portable-vm` | `zx-vm` | Only a preserved pre-cutover `ziran` with `run --vm`; the current tree has no VM, and the M0 receipts hold its measurements. |
| `new-portable` | `lowered-portable` | Supported with explicit `zi2zx run`, the engine that runs every `.zx`. |
| `direct-aot` | `direct-aot` | Supported only by executing the exact hashed ELF artifact. It is never relabeled as native ZX. |
| `control-c`, `control-go`, `control-wasm` | matching selector | Supported with an exact absolute command and complete hashed closure. |
| `old-c-tinycc-native` | — | Missing: the TinyCC route is removed, and its pre-cutover CLI default never gave native-only selection proof. |
| `new-native` | — | Missing: there is no native ZX engine until milestone M3. |
Requests for either missing execution mode fail plan validation. They may and should remain
in `required_cells`, where the processor reports them as missing rather than manufacturing
fallback receipts.
## Exact input schema, version 1
The root is an object with exactly these four members:
| Member | Type | Contract |
| --- | --- | --- |
| `schema_version` | integer | Exactly `1`. |
| `campaign` | string | Nonempty campaign identity, at most 256 bytes. |
| `required_cells` | array | 1–512 required cell objects. |
| `receipts` | array | 1–2048 raw receipt objects. |
Each required cell is an object with exactly four nonempty string members:
| Member | Meaning |
| --- | --- |
| `case` | Stable comparison-case identity. This is not the workload checksum. |
| `phase` | Measurement phase. |
| `metric` | Metric name, which determines ratio direction when recognized. |
| `unit` | Exact unit spelling expected from every engine in this cell. |
Every required cell requires one receipt from each core engine:
- `old-portable-vm`
- `new-portable`
- `old-c-tinycc-native`
- `new-native`
- `direct-aot`
Missing core receipts do not make the input malformed. They produce an incomplete status, a
visible `missing` matrix entry, and an explicit item in the missing-cells section.
`control-c`, `control-go`, and `control-wasm` are optional and are compared when present.
Each receipt is an object with exactly these 21 members:
| Member | Type | Contract |
| --- | --- | --- |
| `receipt_id` | string | Unique receipt identity, at most 256 bytes. |
| `case` | string | Stable comparison-case identity. |
| `physical_host` | string | Explicit physical-machine identity. |
| `host_mode` | string | Must be `physical`. |
| `vm` | string | Must be `none`. |
| `cpu` | string | Exact CPU identity captured by the collector. |
| `os` | string | Exact OS/kernel identity captured by the collector. |
| `toolchain` | string | Exact compiler/runtime toolchain identity for this engine. |
| `flags` | string array | Ordered explicit flags, at most 64 entries and 256 bytes each. |
| `workload` | string | Exact workload identity. |
| `input_checksum` | string | Checksum identity of the workload input/artifact. |
| `engine` | string | Core engine, optional control, or an explicitly named future engine. |
| `phase` | string | Measurement phase. |
| `metric` | string | Metric name. |
| `unit` | string | Raw sample and median unit. |
| `semantic_settings` | string | Overflow, precision, feature, seed, and other semantic settings in canonical collector form. |
| `correctness_expected` | string | Expected output/oracle identity. |
| `correctness_actual` | string | Observed output identity; it must equal the expected identity. |
| `iterations` | positive integer | Exact work performed by every sample. |
| `repeats` | integer | 3–4096 and exactly equal to the raw sample count. |
| `samples` | number array | Positive finite JSON numbers in original measurement order. |
All strings are nonempty, contain no control bytes, and are at most 1024 bytes unless a
smaller bound is stated above. The complete input must be a regular file from 2 bytes
through 4 MiB. Across the document, no more than 65,536 raw samples are accepted.
Duplicate required cells, duplicate `receipt_id` values, or duplicate
engine/case/phase/metric cells are rejected. Unknown object members are rejected because
every object has an exact member count and every required member is type-checked.
## Comparability gates
The entire accepted campaign must have one identical `physical_host`, `host_mode`, `vm`,
`cpu`, and `os`, and every receipt must directly identify a physical host and no VM.
Receipts for the same case/phase/metric must also have identical workload and input
checksum, iteration count, unit, semantic settings, and expected correctness identity, and
each receipt's actual correctness identity must equal its expected identity. Any changed
host, VM, CPU, OS, workload, checksum, iteration count, unit, semantics, or correctness
identity rejects the document before output replacement. Toolchains and flags remain visible
per receipt but may differ between engines by design.
The processor never pools duplicate or incompatible batches. A collector that wants another
batch must create a separately identified campaign input instead of relying on implicit
aggregation.
## Statistics and ratio direction
Each receipt is analyzed by the canonical `bench/benchmark_statistics.zi::BenchmarkAnalyze`
implementation:
- symmetric Tukey fences at 1.5×IQR, both tails checked;
- linearly interpolated inclusive first and third quartiles;
- a sample is excluded only when it is strictly outside a fence;
- at least three retained positive finite samples;
- the median is computed from retained samples;
- original raw order and zero-based excluded indices are reported.
Recognized phase/metric pairs and intended normalized favorable factors are:
| Phase | Metric | Better direction | Favorable factor |
| --- | --- | --- | --- |
| `coldcompile` | `duration` | lower | baseline / candidate |
| `coldstartup` | `duration` | lower | baseline / candidate |
| `warmstartup` | `duration` | lower | baseline / candidate |
| `warmthroughput` | `throughput` | higher | candidate / baseline |
| `memory` | `memory` | lower | baseline / candidate |
| `code-size` | `code-size` | lower | baseline / candidate |
| `bundle-size` | `bundle-size` | lower | baseline / candidate |
A favorable factor above 1 is an improvement, below 1 is a regression, and exactly 1 is
unchanged. Every comparable row separately reports candidate metric change as `(candidate -
baseline) / baseline × 100%`, which keeps a lower-is-better duration increase distinct from
the reciprocal favorable factor and never presents factor change as elapsed-time or size
change.
If division of positive finite medians underflows or overflows, the row is marked
`noncomparable: derived ratio outside finite range`; no infinity or NaN claim is written. An
unknown metric is retained with its absolute medians and raw audit but its pair is
explicitly marked `noncomparable: unknown metric direction`. No overall or geometric mean is
calculated, so missing cells cannot disappear inside an aggregate.
The fixed primary comparisons for every available cell are:
1. `old-portable-vm` → `new-portable`
2. `old-c-tinycc-native` → `new-native`
3. `old-c-tinycc-native` → `direct-aot`
Optional C, Go, and Wasm controls are each compared against `old-portable-vm` when their
receipts exist.
## Output and failure behavior
The Markdown output contains:
- campaign completeness and the same-host environment;
- an absolute-median matrix for core and control engines;
- the fixed per-case comparisons with ratio and improvement/regression;
- every missing required engine/phase cell;
- per-receipt workload, checksum, iterations, semantics, toolchain, flags, and correctness
identities;
- explicit sample counts, raw samples in original order, excluded indices, and retained
medians.
All receipt-controlled Markdown and HTML metacharacters are encoded before rendering: pipes,
backticks, backslashes, angle brackets, ampersands, asterisks, underscores, brackets, and
hashes.
The output follows input order and is byte-deterministic for identical input. It is built
completely in memory, then written through `ReplaceFile`, which writes and syncs a private
sibling before renaming it over the destination. Malformed, statistically invalid, or
incompatible receipts return failure without replacing an existing report. An atomic write
failure also returns failure and removes its private sibling.
## Status
`bench/assembly_collect.zi` supplies the strict collector prerequisite for genuinely
selectable modes but cannot complete the five-core matrix: the TinyCC route is removed (the
M0 receipts are its only data), and there is no new-native ZX cell yet. The pending
full-campaign item lives in `plans/open-work.md`. The older `bench/zx_compare.py` harness
produced the labeled interim portable-engine comparison on physical Alpha; see
[`bench/zx_compare.md`](../bench/zx_compare.md#older-receipts) and the retained raw receipt.
That shell receipt is not the strict five-core campaign and cannot close the delivery gate.
Synthetic fixtures validate this report processor independently of the measured interim
results.
+195
View File
@@ -0,0 +1,195 @@
# Portable lowered execution
Status: implemented. This engine is the portable instruction engine:
`libziran` embeds it, and `ziran run` and the embedding API execute
revision-28 `.zx` containers on it.
## Public API
`compiler_exec.zi` exports:
- `LirExecDefaultLimits() -> LirExecLimits`
- `LirExecPlanBuild(program, verify_limits, *plan) -> LirExecResult`
- `LirExecPlanFree(*plan)`
- `LirExecInstanceOpen(*plan, limits, identity, *instance) -> LirExecResult`
- `LirExecInstanceClose(*instance)`
- `LirExecRun(*instance) -> LirExecResult`
- `LirExecCall(*instance, function, arguments) -> LirExecResult`
- `LirExecResultCopy(*instance, output) -> bool`
- `LirExecProblemName(problem) -> string`
A plan verifies the complete `LirProgram`, computes type layouts, indexes every
function value slot, and computes global and frame layouts. It borrows the
program's slices; their backing storage must remain alive and unchanged until
`LirExecPlanFree`.
Plan build and instance open are reusable operations. They release an earlier
value before rebuilding or reopening. A failure leaves the destination closed
and not ready. `LirExecPlanFree` and `LirExecInstanceClose` are safe after
partial initialization and safe to call repeatedly.
The plan and instance structs must be zero-initialized before their first build
or open. This is automatic for ordinary Ziran locals; a generated-C caller uses
the normal `{0}` initialization.
An instance owns all mutable state: global bytes, derived-address provenance,
frame bytes and words, the explicit frame stack, the copied result, and
resource counters. `identity` must be nonzero and unique among instances
whose pointer values can meet. Reopening an instance reconstructs its globals
from the program initializers.
`LirExecCall` accepts scalar arguments in `bits` and record/array arguments in
`bytes`. `LirExecResultCopy` copies a record or array result from
instance-owned result storage.
## Execution model
The engine runs verified instructions only. It does not load `.zir`, evaluate
the source AST, evaluate generated C fragments, or fall back to another
evaluator. When the plan is built, each verified function is translated once
into compact code: one entry per instruction, specialized by operation and
width, with its operands' frame words and storage offsets resolved and each
edge's argument copies listed. One loop runs it. Constants, null, function
addresses and fuel need no code: a frame starts with those words written.
Common pairs run as one entry: a compare and the branch on it, an address
derivation and the load or store that is its only use, a field address that is
only the base of the next derivation, two word extracts, and an add before a
jump. Anything the compact code does not run itself (calls through function
values, host calls, allocation, resizing, traps) and every failure goes to the
reference implementation, which runs one verified instruction at a time;
`LirExecRunReference` runs a whole call that way.
Calls push bounded `LirExecFrame` records onto an explicit vector. Recursion
therefore consumes the configured frame budget rather than the host language
call stack. Each frame has packed storage for records and arrays and one word
per scalar value. Values carry no definedness state: the verifier proves every
use is dominated by its definition and has its operand's type, and values from
outside the plan (call arguments, host results, global images) are checked
where they come in. Block transfers whose arguments could overwrite each other
first copy every argument to frame scratch and then publish all block
parameters, so swaps and other parallel-transfer cycles retain their incoming
values; transfers proven free of overlap copy in order.
Writable globals are instance-local packed byte storage. Pointer values are
opaque tokens naming an instance identity and a checked global-derived
provenance entry. `field.address` derives a checked record member provenance
entry, while `element.address` checks a dynamic fixed-integer index against the
array's count and derives the element's provenance. Both require the exact
parent pointee type, and repeated equivalent derivations reuse a token;
load and store require an exact pointee type. Function addresses use a separate
nonzero function-index encoding and indirect calls recheck the full signature.
Integer arithmetic narrows after each instruction. Signed division implements
the minimum-value divided by `-1` result without invoking host overflow.
Division by zero and shift counts outside the left operand width are structured
failures. A shift count is read using its own verified integer type, including
mixed-width shifts. Numeric conversions implement the verified bool/integer and
fixed integer/float matrix with checked float-to-integer ranges. Floating
negation flips the IEEE sign bit, preserving signed zero and NaN payload bits.
Fuel is consumed only by explicit `fuel` instructions, making it a stable
semantic checkpoint independent of dispatch implementation. Work is charged
separately for instruction dispatch, copies, and aggregate/member traversal.
The compact code charges the work and fuel of a run of instructions (up to the
next one it hands over) when it enters it. When they do not fit, or anything
in the run fails, it gives back what the instructions it has not run were
charged and hands the run to the reference implementation from there, so a
limit or failure stops at the same instruction, with the same remaining work
and fuel, as charging instruction by instruction. Frames, live values, derived
addresses, and total value bytes have independent limits.
Every runtime failure reports a `LirExecProblem`. Failures at an executing
instruction also report function, block, instruction, source origin, remaining
work and fuel, and a trap payload where applicable. Repeated calls reset
transient execution state and counters while retaining the instance's globals.
## Verified coverage
The engine executes every operation and value type currently accepted by
`compiler_lowered_verify.zi`:
| Surface | Implemented forms |
| --- | --- |
| Types | void, bool, fixed signed/unsigned integers, float32/float64, pointers, fixed arrays, records, function addresses |
| Values | constant, null, global address, function address |
| Numeric | add, subtract, multiply, divide, integer remainder, negate, bit operations, shifts, all comparisons, convert, bitcast |
| Aggregate | aggregate, extract, insert |
| Memory | field/checked dynamic fixed-array element address, checked allocate with optional initializer, load, store over instance globals and frame allocations; `resize` heap blocks |
| Calls | direct and indirect portable calls, including bounded recursion |
| Control | fuel, trap, jump, branch, return, unreachable |
Array extraction/insertion accepts both verified literal ordinals and dynamic
fixed-integer indices. Dynamic indices preserve their declared signedness and
width, reject negative and out-of-bounds values before copying bytes, and retain
checks for empty arrays and zero-sized elements.
`Allocate` reserves pointee-sized storage for the executing frame and returns
an identity-checked pointer token bound to that frame and its generation. The
optional initializer must have the exact pointee type and is copied at
allocation time; without one, the new storage has the pointee's zero value.
Accepted pointees are bool, fixed-width integer, `f32`, `f64`, and pointer
values. Aggregate pointees fail the `Allocate` operand rule, while pointers to
function types are rejected by the type verifier. Allocated pointers compose
with load and store; a token whose frame has returned, or whose identity no
longer matches, fails with `.Pointer`. Every execution allocates fresh storage,
including repeated execution of one instruction in loops and recursion, so
allocated pointer values are not stable across executions and are never
meaningful outside the instance that produced them. Total address slots,
including allocations, are bounded by the `addresses` limit.
The conformance cases cover narrowing and wrap, signed-minimum division,
division by zero, invalid shifts, mixed-width shifts, bool casts, checked float
casts, float32 rounding, signed zero, NaN comparisons and payload-preserving
negation, cyclic edge transfers, arrays and records, direct and indirect calls,
initialized and zero-default scalar allocation, same-site loops and recursion,
active aliases, stale and reused-frame pointer failure, instance isolation,
pointer provenance, reuse and repeated close, all runtime limits, structured
origins, repeated failure, and verifier rejection.
The test driver also runs a hand-built executor oracle from source and
entry-pruned saved IR through generated C, generated Go, and bundles on the
engine.
## Exact current boundary
The verifier rejects `copy`, `zero`, and `host.call`; it also rejects
native-width integers, vectors, capabilities,
external functions, non-portable calling conventions, variadics, and
non-writable global addresses. Plan construction returns `InvalidProgram` with
the verifier diagnostic for these forms. They are not silently skipped.
Heap blocks live in the instance-owned bytes beside host-returned storage. A
block's address names the block and its generation. `resize` and free end that
generation, so every address derived from the old block fails with `.Pointer`
afterwards, as a pointer into a returned frame does. The last block of the
owned bytes grows and shrinks in place; dead blocks at the end are given back.
Heap bytes count against `value_bytes`, and a request beyond it gives a null
result instead of a failure, so `VecPush` can report it.
Consequently this slice provides checked frame-local scalar allocation and
typed heap blocks, but does not yet provide arbitrary byte memory,
host callbacks, native-width or SIMD values,
capability values, state serialization or
migration, thread-safe concurrent use of one instance, or parallel/SIMD
dispatch. The executable `.zx` reader, `ziran run`, and the embedding API
route bundles through this engine; the Wasm tier and native ELF output are
separate `zx2wasm` and `zx2native` lowering routes.
## Local verification
Run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY build-queue -- \
make CHECK_FILTER=lowered_exec check
```
The focused test reports:
```text
lowered exec: verified engine and source/saved C, Go and bundle local tests passed
```
Performance comparison is intentionally absent here. The required before/after
`.zx` benchmark belongs to the completed integrated objective and must run on
the Alpha physical host, never on a desktop or VM.
+68
View File
@@ -0,0 +1,68 @@
# Inspect direct assembly in VS Code
The repository tasks run the experimental direct backend's real supported
inspection path without rebuilding the compiler or falling back to C:
```text
source -> .zir -> LIR -> verification -> LIR optimization -> portable .zx
-> verified ZX read -> direct target lowering -> ELF + map -> disassembly
```
Use **Terminal: Run Build Task** and select **Ziran: Inspect assembly (scalar
fixture)**. It uses `tests/spec/assembly_scalar.zi` with entry
`assembly_scalar:Answer`. The **choose source and entry** task prompts for a
different source, entry and module root. The same operation is available at the
repository root:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY \
-u DBUS_SESSION_BUS_ADDRESS HARMONY_DESKTOP_RECOVERY=0 \
build-queue -- python3 scripts/inspect_assembly.py \
--source tests/spec/assembly_scalar.zi \
--entry assembly_scalar:Answer \
--root tests/spec
```
Every successful run publishes only a complete stable
`build/vscode-assembly/inspection/` set:
| Artifact | Contents |
| --- | --- |
| `checked/*.zir` | canonical checked compiler output |
| `lowered.lir` | checked, unoptimized source LIR inspection |
| `lowered.zx` | linked, verified and optimized portable executable |
| `optimized.lir` | the selected `--opt` instruction listing |
| `optimization.json` | deterministic optimization transformation counters |
| `final.elf` / `final.map.json` | optimized native image and its byte map |
| `final.disasm` | actual final ELF disassembly with text-relative addresses |
| `manifest.json` | source, tool and artifact hashes plus exact commands |
The helper verifies that `final.map.json` identifies the complete SHA-256 of
`final.elf`. It reads `image.text_virtual_address` from that map and passes its
negative value to `objdump --adjust-vma`; no ELF base or scalar-fixture offset is
hardcoded. `final.disasm` records the same ELF identity and adjustment, while the
manifest hashes every advertised artifact.
`objdump` (normally from GNU binutils) is an explicit inspection dependency. It
does not assemble or link the program: `zx2native` reads verified ZX and directly
encodes ELF. Pass `--objdump PATH` when a compatible tool has another name. Missing
tools, unsupported source, compiler errors, identity mismatches and disassembly
errors stop at the failing stage. A failed run does not replace the last complete
artifact set, and there is no fallback compiler.
The tasks require the existing `build/bin/zi2zir`, `build/bin/zi2zx`, and
`build/bin/zx2native`. If
native compiler work makes them stale, finish that work and rebuild through the
shared queue before inspecting:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY \
-u DBUS_SESSION_BUS_ADDRESS HARMONY_DESKTOP_RECOVERY=0 \
build-queue -- make assembly
```
This view exposes only the currently implemented ZIR, verified lowered
instructions, basic optimization counters, native range map, ELF and
disassembly. It does not claim machine IR, register-allocation state,
source/unwind debug metadata, profiler/JIT mapping, or support for examples
outside the direct backend's documented lowering boundary.
+248
View File
@@ -0,0 +1,248 @@
# ZX executable instruction container — revision 28
This document specifies the `.zx` executable format. The format owner is `cmd/compiler_bundle.zi`;
`cmd/compiler_exec_link.zi` binds it to the deterministic LIR codec and
verifier (current payload schema 4). `zi2zx` writes it; `ziran run`, `zi2zx run`,
the embedding API (`include/ziran_host.h`), `zx2wasm`, and `zx2native` read it.
Checked packages use the [ZX library format](zx-library-format.md).
## Integers, limits and ordering
All integers are unsigned little-endian unless a field is explicitly signed.
The complete file is bounded to 268,435,456 bytes. Section count is 3–1,024.
The instruction payload is non-empty and at most 268,435,456 bytes. Asset names
and lengths use the existing u32 codec and its canonical validation.
Directory kinds are strictly increasing and unique. Every writer section uses
alignment 8. A reader accepts power-of-two alignment through 4,096 for optional
extensions, but requires the offset to equal the first aligned byte after the
previous section and every intervening padding byte to be zero. It rejects
integer overflow, unordered/duplicate entries, gaps, bad padding, overlap,
truncation, and trailing bytes. There is no recovery scan or legacy fallback.
## Header (64 bytes)
| Offset | Width | Value |
| ---: | ---: | --- |
| 0 | 4 | `5a 58 00 00` (`ZX\0\0`) |
| 4 | 4 | format revision `28` |
| 8 | 4 | header size `64` |
| 12 | 4 | directory record size `32` |
| 16 | 8 | required feature mask, `1` for apps or `3` with module linkage |
| 24 | 8 | optional feature mask |
| 32 | 4 | section count |
| 36 | 4 | container flags; zero |
| 40 | 8 | exact total file length |
| 48 | 8 | directory offset; `64` |
| 56 | 4 | identity algorithm; `1` means SHA-256 |
| 60 | 4 | reserved; zero |
Required feature bit 0 retains the manifest contract name `portable-lir-schema-3`.
The internal payload independently carries and verifies current LIR schema 4.
Required feature bit 1 advertises module linkage. A reader requires bit 0 and
rejects unknown required bits. A revision-28 reader that knows only bit 0 rejects
a module bundle. Optional bits are non-executable hints and may be ignored.
Any other revision is unsupported, and the reader never sends a payload to the
`.zir` parser.
## Directory record (32 bytes)
| Offset | Width | Meaning |
| ---: | ---: | --- |
| 0 | 4 | section kind |
| 4 | 4 | flags; bit 0 means required |
| 8 | 8 | absolute file offset |
| 16 | 8 | byte length |
| 24 | 4 | power-of-two alignment |
| 28 | 4 | reserved; zero |
Implemented kinds are:
| Kind | Required | Meaning |
| ---: | --- | --- |
| 1 | yes | fixed executable manifest |
| 2 | yes | deterministic stripped internal instruction payload |
| 3 | yes | canonical assets, including an empty table |
| 4 | not accepted as required | reserved native variants |
| 5 | iff required feature bit 1 is set | module linkage bytes |
| `0x80000001` | no | opaque debug attachment |
| `0x80000002` | no | opaque source attachment |
| `0x80000003` | no | host interface: the names an embedder sees (below) |
| `0x80000100` and above | no | producer extension attachments |
An unknown optional section is bounded and skipped. An unknown required section
rejects before LIR decoding. A required kind-4 section rejects as an unsupported
native variant; arbitrary machine bytes are never selected or executed.
## Host interface (kind `0x80000003`)
The section is mandatory and nonempty when required feature bit 1 is set.
Its directory flags are zero in both app and module bundles.
The instruction payload is structural: a record is its field types, a string
is `{data, count}`. An embedder's host values carry names, so `zi2zx` writes
them here, as UTF-8 text of tab-separated lines. Type nodes come
first, each naming only earlier nodes:
node ID scalar|string|pointer SPELLING
node ID slice|array SPELLING CHILD
node ID record SPELLING NAME CHILD NAME CHILD ...
then one line per host capability, by LIR function index, with its result
node (`-1` for void) and parameter nodes, and one with its declaration as
written (variadic and reads-arguments flags, the declaration line, its
parameters and its return type):
host FUNCTION RESULT PARAMETER ...
abi FUNCTION VARIADIC READS SIGNATURE ARGUMENTS RETURN
then one line per module global, by LIR global index, with its type node,
and the entry's parameters and return type as written:
global GLOBAL NODE
entry ARGUMENTS RETURN
A spelling is the type as declared at that position, which a host sees as the
value's type name. Declaration text has its tabs and line ends as spaces. The
embedding API (`include/ziran_host.h`) uses these lines to translate host
values, copy a host's changes to `[]T` arguments back, export and import
module globals as state, and compare two files' capability ABIs. App bundles
may omit this section.
## Manifest (kind 1, exactly 128 bytes)
| Offset | Width | Meaning |
| ---: | ---: | --- |
| 0 | 4 | manifest schema `1` |
| 4 | 4 | LIR schema `3` |
| 8 | 4 | signed entry function ID; nonnegative |
| 12 | 4 | reachable host capability count, at most 4,096 |
| 16 | 4 | required native-variant count; currently `0` |
| 20 | 4 | asset count |
| 24 | 4 | verified proof status; currently `0` |
| 28 | 4 | reserved; zero |
| 32 | 32 | program identity |
| 64 | 32 | asset identity |
| 96 | 32 | combined executable-content identity |
The program identity is SHA-256 of `ZX28-PROGRAM\0` followed by the exact kind-2
bytes. The asset identity is SHA-256 of `ZX28-ASSETS\0`, the u32 asset count,
then each sorted asset's u32 name length/name bytes and u32 data length/data
bytes. For a bundle with required-feature mask `1`, the combined identity is
SHA-256 of `ZX28-CONTENT\0`, the entry ID as a little-endian u32, the mask as
a little-endian u64, the program identity and the asset identity.
For a bundle with required-feature mask `3`, the combined identity is SHA-256
of `ZX28-MODULE-CONTENT\0`, the entry ID as a little-endian u32, the mask as
a little-endian u64, the program identity, the asset identity, the linkage byte
length as a little-endian u64, the exact kind-5 bytes, the host-interface byte
length as a little-endian u64 and the exact kind-`0x80000003` bytes.
The owned reader checks all three identities before exposing the executable.
Module linkage and its host interface affect the module bundle's content
identity. Debug, source and unknown optional attachments are outside the
combined identity. Proof status zero means no
opaque producer law/proof claim becomes verified merely by being attached or
hashed.
## Required instruction program (kind 2)
The payload uses the internal deterministic instruction codec from
`compiler_exec_serial.zi`: header, required core section, and no debug section.
It is not a standalone executable artifact: `.lirb`, `--emit exec` and
`--input exec` have been removed. ZX is the portable program boundary.
It contains LIR version, module identities, type graph, constants and binary
constant bytes, globals and initializers, functions, parameter/value type IDs,
blocks, instructions, operands, edges, symbol IDs, effect ordering, alignments
and the entry ID. It has no host pointers or compiler/C record layouts.
The executable writer strips source names and origins, then calls the unchanged
LIR verifier and codec. The reader copies all LIR strings, blobs and tables into
`ZxExecOwner`, rejects a debug-bearing required payload, verifies it, checks that
the manifest and program entry IDs agree, and exposes a borrowed `LirProgram`
until `ZxExecReadFree`. The original container bytes can be released immediately.
Reachability starts at the entry. Direct calls, host calls and function-address
constants add their symbol IDs; an indirect call conservatively adds every
portable function, since host procedure values do not exist.
Duplicate module identities, duplicate module/name function definitions and
duplicate module/name globals reject. Each reachable bodiless `Host` function is
one capability; its module, name and scalar signature are already in the
verified program. The writer stores the recomputed count and the reader rejects
a different manifest count (`capability-count`) instead of trusting producer
metadata. Other external functions and non-portable calling conventions reject.
The existing bounded portable engine then executes the verified program once
the embedder has bound every capability.
Outer validation uses the caller's `LirLimits` as well as the inner codec and
verifier. The reader rejects a container larger than `limits.bytes` before
framing or hashing and charges `limits.work` for container bytes, program and
asset hashing, module linkage and module host-interface hashing and copying,
symbol-name bytes, hash-table initialization/probes, reachability and temporary
copies. Temporary asset, symbol and reachability allocations are
checked against the byte budget before allocation. Symbol uniqueness uses
deterministic open-addressed tables; hash collisions remain explicitly charged.
The first reachable indirect call adds every function once, and later indirect
calls do not rescan that set. A budget failure returns `limit`, carries an LIR
`Limit` diagnostic and leaves the owned reader invalid. The writer applies the
same accounting with `LirDefaultLimits`; these limits do not change which
instructions or sections the format accepts.
## Assets (kind 3)
The section is the existing asset codec: u32 count, then for each asset a u32
name length, name bytes, u32 data length and exact data bytes. Names are sorted
bytewise and unique relative paths. Empty, `.`, `..`, absolute-like, backslash,
colon and NUL-containing names reject. Data is arbitrary binary, including NUL.
The section must be consumed exactly.
The raw framing API returns asset views borrowing the file. The owned executable
API validates and hashes them during the read; the embedding API copies them
when it opens the file and exposes them through `BundleAsset*`. `zi2zx
--asset-dir` stores them.
## Module linkage (kind 5)
The section is present exactly when required feature bit 1 is set. Its flags
are `1`, alignment is `8`, and its payload consists of the compiler's canonical
module linkage bytes. The payload must be nonempty and fits within the container
and reader byte limits. The framing API treats the payload as bytes. The owned
reader verifies the combined identity and copies the payload before returning.
The linkage codec defines the interpretation of these bytes.
## APIs and failure behavior
`ExecutableEncode` measures when output is empty. A short output returns its
required size and changes no byte. `ExecutableDecode` frames sections and assets
without interpreting LIR. `ZxExecWrite` produces a stripped deterministic
container; `ZxExecRead`, `ZxExecReadProgram`, and `ZxExecReadFree` provide the
bounded owned verified program. Empty and repeated frees are safe.
`ZxExecWriteModule(program, assets, output, interface, debug, module_linkage)`
writes the module form when linkage is nonempty. Empty linkage produces the app
form. `ZxExecReadModuleLinkage(owner)` returns bytes owned by a successful read
and valid until that owner is reused or freed. It returns an empty string for
an app bundle or an invalid owner.
The format-specific tools keep generated-output replacement semantics: they write a sibling
temporary and replaces the requested path only after a complete successful
write. `-o -` streams revision 28 to a pipe. A malformed input cannot replace a
previous output. Diagnostics distinguish legacy/unknown versions, required
features or sections, flags, ordering, alignment, overlap, truncation, trailing
bytes, manifest fields, assets, content identity, LIR codec/verifier rejection,
entry mismatch, capability, variant, external and symbol failures.
## Remaining gaps
- One file is one linked program: there are no library or add-on containers,
cross-container symbol tables or partial-module composition.
- Native target/CPU/OS/ABI variant metadata and template verification are not
implemented; a required variant rejects, and no arbitrary machine blob is
accepted.
- Debug/source attachment codecs, optimization remarks, law witnesses and proof
revalidation are not implemented; optional bytes remain non-executable and
proof status remains unverified. Laws are checked from source.
The retained focused tests cover deterministic source/saved output, stripped
portable execution, owned input lifetime, legacy and feature rejection, unknown
required/optional sections, identity corruption, overlap, truncation, trailing
bytes, binary/NUL assets, pipe output and failed-output preservation.
+45
View File
@@ -0,0 +1,45 @@
# ZX checked library format, revision 1
`ziran pkg zx pack-ir` writes `.zx` libraries for use by the package compiler.
The package driver verifies the library and supplies its checked modules to
the compiler by package identity. ZX runtime modules and applications use the
[executable format](zx-executable-format.md).
All integers are unsigned little-endian. The 16-byte header has four fields.
| Offset | Width | Field |
| --- | --- | --- |
| 0 | 4 | Bytes `ZXLB` |
| 4 | 4 | Format revision, `1` |
| 8 | 4 | Section count, 3 to 4,098 |
| 12 | 4 | Exact file length, up to 268,435,456 bytes |
Sections follow the header in increasing bytewise order by path. Each record
has a four-byte path length, a four-byte payload length, a 32-byte raw SHA-256
of the payload, and then the path and payload bytes. Records are contiguous.
Paths are unique, relative, and 1 to 1,024 bytes long. Paths cannot contain
empty, `.` or `..` components, control bytes below 32, a backslash or a colon.
Payloads are nonempty. The final payload ends at the declared file length.
The required `checked-package.tsv` section is the literal `2`, package
identity, toolchain identity, and profile, separated by tabs and terminated
by one newline. Both identities have the form `p` followed by 16 lowercase
hexadecimal digits. The profile is a registry path segment of up to 128
ASCII letters, digits, hyphens, underscores, or periods, excluding `.` and
`..`. The required `ziran.toml` section contains the provider manifest. All
remaining sections hold serialized checked modules with `.zir` paths derived
from the provider's module paths. At least one module is required.
The registry descriptor repeats the metadata fields and adds the full
lowercase hexadecimal SHA-256 of the entire `.zx` file as a fifth field.
The package driver matches these pins to the package and toolchain in the
resolved dependency graph. The compiler checks module identities against
that graph when it opens their checked payloads.
Development libraries use `ZXLD` as their magic. Their metadata starts with
`dev` and adds a fifth field containing a lowercase hexadecimal source
fingerprint. It covers the provider manifest and lock, scanned module and
export source bytes, and feature defines. The writer checks the fingerprint
again before installing the completed file. Production package and runtime
readers reject this magic. A local development reader must be selected
explicitly and still checks the package and toolchain identities.
+272 -442
View File
@@ -2,471 +2,301 @@
## [Unreleased]
- A host library registered for `zx2native` may be an `ar(1)` archive of ELF64 x86-64 relocatable objects instead of a shared object. The Linux executable links the members its capabilities reach, each once, with their text, read-only data, writable data, zero fill, GOT entries and relocations, and the capability's veneer calls its member directly, so the executable stays static and has no interpreter or dynamic record. An unsupported section, relocation or symbol is the stable `assembly.gap.machine-archive` diagnostic naming the capability, member and symbol, and the old output is kept. `tests/machine_elf.sh` links and runs an archive, rejects an undefined member symbol, and keeps the shared-library case green.
- `zx2native --platform linux|windows` supplies the ZX Runner's file and clock services itself, so a program that uses `std/guest_files` or `std/guest_clock` links into the same static ELF or PE32+ as any other instead of stopping at a host-capability gap. The linker names the nine `host_api` services by function and signature, keeps them apart from library imports so the ELF stays static and the PE imports only what a veneer calls, and emits each veneer after the library ones. Linux veneers make the system calls with the path in a 4 KiB stack slot; Windows veneers widen UTF-8 paths to UTF-16 with `MultiByteToWideChar`, convert listed names back with `WideCharToMultiByte`, and import `GetFileAttributesExW`, `CreateFileW`, `ReadFile`, `WriteFile`, `DeleteFileW`, `MoveFileExW`, `CreateDirectoryW`, `FindFirstFileW`, `FindNextFileW`, `FindClose`, `QueryPerformanceCounter`, `QueryPerformanceFrequency` and `GetSystemTimeAsFileTime` as needed. A read or a listing grows a heap block through the runtime's resize entry and shrinks it to the final length; the block stays allocated. `tests/machine_elf.sh` and `tests/zx_windows_parity_cases.zi` run one program that writes, reads, renames and removes a file (with a non-ASCII name), lists a directory and reads both clocks on Linux and under Wine.
- `zx2native --platform windows` writes each line of standard output to a console once it ends, as the Linux ELF does, while a redirected or piped descriptor keeps whole buffers: the buffered runtime asks `GetConsoleMode` once, so an image with more than one console call imports it beside `GetStdHandle`, `WriteFile` and `ExitProcess`; hello, with one call, still imports the three. `tests/zx_windows_parity_cases.zi` runs a program that prints, works and prints again under a pseudo-terminal on both systems and times its first line.
- `zx2native --platform windows` writes x64 unwind data for every function with a prologue: a `.pdata` `RUNTIME_FUNCTION` and a `.xdata` `UNWIND_INFO` record that walks the pushed frame pointer and the stack allocation. The record starts where the frame does, after an early return that leaves before any frame exists, so a Windows stack walker attributes frames from the first byte.
- `zx2native --target armv7 --platform linux|android` writes a static ARMv7 ELF32 (EM_ARM, EABI5) with its own runtime, matching the AArch64 writer: the entry stub sets the stack limit, calls the initializers and the entry, and ends through the runtime's exit; the console writer is A32 machine code emitted from Ziran source. Both ARM rows run on their devices (Pixel 4a and Moto e6 play) and both report a named gap for a facility they do not carry.
- `zx2native --target aarch64 --platform linux|android` writes a static AArch64 ELF with its own runtime: the entry stub sets the stack limit, calls the initializers and the entry, and ends through the runtime's exit; the console writer is AArch64 machine code emitted from Ziran source. The image resolves every relocation at link time, so it needs no loader. A program that calls a formatter or a host capability is still a named gap.
## [0.8.0] - 2026-11-23
- Build native AArch64 and ARMv7 images with indexed relocation lookup, so each image relocation visits only its own instruction's machine relocations instead of scanning the whole program. Both devices pass the 81-program parity.
- ZX Runner: `make install-user` installs the `zx` command, the `.zx` file type (`application/x-ziran-bundle`, recognized by name and by its `ZX\0\0` header) and a desktop entry that file managers use to open `.zx` files. `zx app.zx` runs any bundle with the toolchain's runtime and hands it to no other program. It first explains a file that is not a ZX program or uses an older or newer ZX format, and names a bundle that needs platform capabilities, such as a window, that the runner does not provide. Started without a terminal, it also shows failures in a dialog.
- Removed `std/rss_scan` (feed item and tag scanning: `FeedNextItem`, `FeedTag`, `FeedCopyText`). The standard library has no replacement; a program that needs it copies `std/rss_scan.zi` from commit c3ef9fb2, the last one that has it, into its own module root.
- Removed `std/http_get_linux` (`GetHttps`, `GetHttpsCapped`). Use `std/net_http`: `SendCapped` with an `HttpRequest` whose `method` is `"GET"`. Commit 4c62f8b8 is the last one that has the old module.
- `#caller_location` names the call site's file relative to its module root, or by its package and the path inside that package, so the same sources build the same output from any folder or package cache.
- ZX embedders can request an active guest stop from another thread, including during initialization and library calls.
- Hosted ZX applications can open from a read callback with a smaller instruction store when running on the portable engine.
- Compile hot packed ZX integer instruction runs on Linux i386 with bounded executable storage and the interpreter's work, fuel and failure locations.
- Speed up large record and array loads in the ZX instruction engine.
- Check public API declarations and examples for a selected backend and platform with `ziran api`.
- Pack checked ZX libraries for explicit OS and CPU targets with `ziran pkg zx pack-ir --locked`.
- Reduce portable ZX integer execution overhead by reusing canonical operands and looking up edge metadata only at branches and jumps.
- Allow instruction-engine hosts to borrow packed read-only scalar slices for synchronous callbacks.
- Add optional bounded progress and cancellation callbacks to PNG/JPEG decoding while preserving the ordinary image readers.
- Add compact/reference instruction-budget parity coverage and retained i386 runtime comparisons; the unproven interpreter optimization candidate was withdrawn before installation.
- The portable ZX engine reuses frame storage for large record and array snapshots with disjoint lifetimes.
- Package locks preserve each dependency's own name and exports when multiple refs select the same local override.
- ZX supports indexing typed pointers. The engine and checked native backends use the backing allocation to reject invalid indices.
- The portable ZX engine can resize a heap block using adjacent free space on both sides, avoiding a replacement allocation when the combined space fits.
- The portable ZX engine reuses storage for temporary derived addresses across branches, so loops can traverse large buffers without filling the address table.
- Native ZX can run with a smaller temporary frame arena when the host cannot reserve 256 MiB of contiguous address space.
- Speed up SHA-256 verification on hosts without SHA instructions.
- Package tested native Ziran toolchains in Gitea by exact source revision and Linux host profile.
- Distribute checked packages as versioned `.zx` libraries for source-free imports in ZX and native builds.
- Publish and fetch verified `.zx` images and checked compiler companions through Gitea. Package locks can discover and pin compatible checked dependencies for source-free ZX builds.
- The engine-only ZX reader can decode directly into compact instruction storage and expand one function at a time for verification and planning.
- Compact ZX execution uses half the storage for value locations when the configured limits fit a signed 32-bit encoding. Larger plans retain 64-bit locations.
- C embedders can use `BundleOpenEngineReadAt` to reduce the engine’s verified instruction storage. A host allocator can release the unused storage through an optional shrink callback.
- C embedders can open seekable ZX app images through `BundleOpenReadAt` without keeping a full input buffer. The callback is needed only during verification, and images with assets, module linkage, or additional attachments use the byte-based API.
- Native x86-64 code copies and clears fixed-size values through 512 bytes with inline vector instructions, takes register hints from actual control-flow predecessors, creates a stackless leaf's frame only when a fuel check traps, and copies only the used members of record snapshots read through constant fields.
- `zx` hosts bundles in-process and gives them files, the clock, arguments and environment, and their own embedded assets (std/guest_files, guest_clock, guest_process, guest_assets); a capability it lacks is named in the error.
- `ziran api --json` exposes optional type-checked, runnable usage examples for public symbols.
- Native instances release temporary frame reservations while idle, so multiple bundles fit in a 32-bit address space without reducing the active frame limit or checked pointer protection.
- Embedders can route instruction-engine ZX output through a per-instance console callback, including output from global initializers.
- In-process native ZX resizes large heap blocks through the allocator instead of always allocating and copying a replacement. Growth remains zero-filled and checked aliases are invalidated even when the address stays the same. The Vectors kernel on Alpha took 38.19 µs instead of 40.04 µs in 11 matched rounds, against 34.07 µs for C.
- Wasm stores can copy a loaded record directly from its source when no intervening effect requires a snapshot. Copies through pointers preserve partially overlapping memory in either direction.
- The shared optimizer resolves calls through known function addresses, gives calls inside loops a larger inlining budget, and restores borrowed input on resource-limited specialization. Standalone ZX tools now rebuild when the specialization module changes.
- Source and saved module graphs can grow beyond 1,024 files, with bounds checked against available addressable storage.
- Platform conditions in modules with file-scope enum imports no longer force an otherwise ordinary import cycle to resolve at compile time.
- Executable ZX identities hash whole byte ranges through the runtime’s shared SHA-256 implementation, including CPU acceleration where supported, instead of feeding a separate hasher one byte at a time. Identity validation and resource limits are unchanged.
- The native disk cache reloads ARMv7 and AArch64 machine images, including the ARMv7 runtime helper relocations. Android apps reuse compiled code across launches.
- ZX lowering turns a range test with literal bounds, such as `code >= 12288 && code <= 12543`, on a stable local, record member or fixed-array element into one unsigned comparison. Kryon's TextIdeographic drops from 55 to 41 instructions, and the Text widget scenario ran faster in Wasm in 8 of 10 alternating Alpha rounds, with the paint result checked on every call.
- Wasm frames hold only the record slots a procedure still uses. A large record read in place, or a zeroed record that is never built, reserves no frame space, so Shovey, whose level replay reads single fields of a 306 KB global, compiles to Wasm instead of exceeding the 8 MB frame limit.
- On x86-64 and aarch64, native console prints read their arguments straight from the saved registers instead of decoding each by type. On Alpha, arrays.zi went from 1.018 to 0.490 µs per call, enums.zi from 0.353 to 0.177, below Wasm, and loops.zi from 1.560 to 0.720.
- Native ZX gathers standard output in the same console buffer as the engine and hands it to stdio once per run, and before standard error, a host capability call or a trap report. On Alpha, arrays.zi went from 1.150 to 1.023 µs per call, enums.zi from 0.392 to 0.360 and loops.zi from 1.780 to 1.600.
- Native host calls resolve each function's capability or platform service once per instance, keep up to eight arguments on the stack instead of allocating them, and format printed integers directly. On Alpha, arrays.zi went from 2.075 to 1.122 µs per call, enums.zi from 0.686 to 0.378 and loops.zi from 3.155 to 1.718.
- `BundleInstanceOptions.unbounded` runs an instance without step metering: native code for it is built without fuel checks, like an unbounded executable, and takes no step limit. The standard and example benchmark hosts use it, as C and Wasm run unmetered. A normal native run now leaves its output to stdio buffering, as the engine does, instead of flushing stdout and stderr on every call. On Alpha, enums.zi went from 1.213 to 0.688 µs per call, arrays.zi from 2.563 to 2.059, score.zi from 0.033 to 0.022, dijkstra by 24% and fannkuch-redux by 14%.
- In-process native ZX no longer makes a system call on every entry: each thread keeps its stack range, and a forked child looks it up again under its own limit. Records & calls (score.zi) went from 0.511 to 0.032 µs per call on Alpha and text_demo.zi from 0.512 to 0.033 µs; arrays, enums and loops took 13–30% less time.
- Fixes: native ARMv7 and AArch64 code reads and changes members of large records and globals in place, as x86-64 code does, instead of copying the whole record into the frame for every access. Shovey's `LevelReplayPump`, whose 12 MB frame stopped it at its frame limit when Play was pressed on an ARMv7 phone, now needs 1.8 MB on every target. A record or array built from zeros is zeroed in one pass instead of one store per member, so Shovey's native code shrinks from 6.4 to 1.4 MB on ARMv7 and from 2.8 to 0.9 MB on x86-64, and its AArch64 build, where one 4.7 MB function put branches out of range, now compiles.
- Native code is verified once: the encoder no longer verifies again a program register allocation just verified, which shortens a phone's on-device compile. The native disk cache now works in Android apps: a library linked without a GNU build ID, as reproducible APKs are, is identified by its code, and an app process caches in its own cache directory, so only the first launch after an install compiles a bundle.
- Fixes: generated C declares a generic procedure's copy for its caller when the copy's signature names a type through the template's own import alias and the caller has a module-scoped import of that name; GCC 14 rejected the call as an implicit declaration (Kryon's text Draw called from Terminal).
- ZX applications can load separately compiled libraries with verified typed imports, independent instances, export inspection and state-preserving replacement. The loader checks dependency graphs and accepts explicit module roots.
- Most of the compiler builds from Ziran source, bootstrapped from generated C seeds: source parsing, module discovery, declaration parsing, compile-time evaluation and condition selection, IR cleanup, the frontend IR, compiler contexts, source documents, diagnostics, paths, semantic IDs, SHA-256 and law checks, the checker (expressions, statements, values, functions, whole programs, generic linking, SIMD rules, borrow analysis), the C and Go backends with their SIMD and x86-64 assembly emitters, the checked IR codec, module loading, locked package resolution, executable ZX asset collection, entry linking for the C, Go and native backends, inline assembly checking and its C emission, and the ZX embedding API (`include/ziran_host.h`). The saved IR format and the C interfaces are unchanged.
- `ziran run app.zx` hands a bundle only to a runtime provider built by the same toolchain: a `.host` registration records `ziran version --identity` on its second line, and a provider of another build is refused with both identities.
- `ziran lock` and `ziran update` refresh checked-library entries saved under another toolchain instead of refusing; builds name the package and `ziran lock`.
- Generated C names a `#program_export` that two linked package revisions define, gives one type application one C type in every module that spells it, and keeps constants, globals and types off the runtime's and libc's names.
- Nested array literals work at file scope and in procedures: `table: [2][2]s64 = .[.[1, 2], .[3, 4]]`.
- Inside a project, `ziran api PACKAGE/MODULE` prints that package module; options may follow the input files, a module name that selects nothing is an error, and text output lists record fields and enum members.
- A syntax or import error says under it that checking stopped there, and a rejected `--bind` says which side is missing or which module already binds the capability.
- Go's `uintptr` is declared with `#type #foreign builtin "uintptr"`.
- New standard modules for Limbo ports: `std/list`, `std/pool`, `std/tuple`, `std/rune_text`, `std/zx_conc` and `std/bundle_guest`. `std/grapheme` answers ASCII text without its tables.
- Two dependencies that name one repository by different URLs share one module namespace under a local override.
## [0.7.0] - 2026-11-18
- Wasm now runs all three Kryon widget scenarios faster than Go, and two of them faster than C: Button takes 2.46 µs, Text 3.59 µs and Input 3.24 µs per two frames on Alpha, against 4.33, 3.89 and 6.59 µs in Go. Wasm code reads a record's fields where the record lies instead of copying it, builds records where their caller or parent keeps them, writes a single changed field in place, and writes zeroed records with wide stores or `memory.fill`. `zx2wasm --unbounded` makes a module with no step budget for runs that need none.
- The optimizer inlines small procedures, reads record members through the inserts that built them, drops unused calls to procedures without side effects, specializes calls that pass a literal Boolean controlling a loop, and turns recursion such as `Fib(n-1) + Fib(n-2)` into an accumulator loop. It hoists fixed member reads, such as a slice's data and count, out of loops and rotates loops whose test loads from memory, so JSON round trips run 9.7% and radix sort 6.8% faster. It also folds interval checks such as `value > 1000 || value < 0` into one unsigned comparison. A Kryon widget's theme lookups become the constants they read.
- Native x86-64 code is faster. Division and remainder by constants use multiplies and shifts, constant shifts use immediates, and floating-point values stay in XMM registers across calls that leave those registers alone. Small blocks are allocated in process, so binary-trees runs in under half the time of the C reference. Functions and loops are aligned, so an unrelated edit no longer moves a loop's speed, and `--checks` builds no longer branch around their traps. Float64 `sqrt` and `std/math.Sqrt` use the hardware square root on x86-64, AArch64 and ARMv7.
- New standard library features: `std/base64` encodes and decodes RFC 4648 base64; `std/jpeg` reads baseline and progressive JPEGs and writes JFIF on every target; `std/png_linux` inflates PNG data portably; `std/finite` has inline `Finite32` and `Finite64`; and `std/parallel` adds `ParallelProcessors` and `ParallelInitLanes`.
- Audio is part of the core standard library, independent of Kryon: mixing, PCM streams, WAV with IMA and Microsoft ADPCM, MP3, and Ogg/Vorbis with streaming and seeking, played through SDL, WebAudio, or AAudio and OpenSL ES on Android.
- Fixes: integers format correctly across the full signed 64-bit range, including the minimum value. The native runtime builds on ARMv7 again. An in-process native run of an entry without a result reports zero. Register allocation no longer copies a register from an unrelated block across a block edge.
- The Targets page on the website compares C, Go, native ZX and Wasm in microseconds, all measured on one physical host at one compiler revision. It covers a 29-workload standard suite with independent C and Go references, Kryon widgets and JSON/UTF-8 workloads, with raw samples and generated code to download.
- Known issue: on ARMv7, native ZX can stop Kryon's `LevelReplayPump` at its frame limit. The fix is not in this release.
## [0.6.0] - 2026-11-16
- Ziran is manually safe like C by default: native x86-64, AArch64 and ARMv7 code, Wasm, generated C and the checks Ziran writes into Go carry no defensive runtime checks, so pointers are addresses and indexes are raw. Build with `--checks` to get every bounds check, pointer token and trap as before, or write `#checks` at the top of a module, before a block or statement, or before one index or slice access to check exactly there. The ZX header records how a bundle was built. The portable engine stays checked.
- Native code is much faster: tail calls, functions without frames, small records held in registers one field per register, copy-free reads of large-record fields, `[base + index*scale]` addressing, hot blocks laid out to fall into each other, and register allocation that gives a loop-carried value and its copy one register. Kryon's widget scenarios run natively in 8.6 µs (Button), 9.6 µs (Text) and 13.1 µs (Input) per two frames on Alpha, 121–185× faster than 0.5.0 and within about 3× of C.
- A native ELF carries only what the program uses: fuel, traps, stack checks, the pointer runtime, the heap and console buffering appear only when referenced, and `examples/hello.zi` is a 254-byte executable whose `main` is a few instructions.
- `zx2native --target x86_64 --platform windows` writes a Windows x86-64 PE32+ console `.exe` from verified ZX, with no C runtime and only the kernel32 imports the program uses.
- On linux-armv7, Android included, `ziran run app.zx`, `zi2zx run` and the embedding API run bundles as native code by default; ARMv7 code keeps 64-bit values in register pairs, and all 72 parity programs print the engine's output on an armeabi-v7a phone.
- `zx2native` writes Linux x86-64 executables for programs that call host capabilities, linking each capability by name from a registered host library (`NAME.library` beside the `.host` players in `ZIRAN_HOST_PATH` or `~/.local/share/ziran/hosts`).
- Native compilation is faster on very large programs: the 28.7 MB Unicode conformance bundle compiles in 7.4 s instead of 81 s.
- The plain `ReadU16LE`, `ReadU32LE`, `ReadS32LE` and `ReadF32LE` read at any alignment, as C does.
- The website's target and widget tables show fresh native measurements from Alpha, with the generated C, Go, ZX, checked IR and raw samples to download.
## [0.5.0] - 2026-11-16
- ZX runs as native code by default on Linux x86-64 and AArch64, Android included: `ziran run app.zx`, `zi2zx run`, the embedding API and Kryon's players run a bundle's verified program as native code in W^X memory. Stray and freed pointers, double free, out-of-range indices, read-only stores and runaway recursion trap; a native gap is a named error and nothing falls back to the engine. `--backend engine` picks the portable instruction engine.
- Native code is fast: on Alpha's Intel Core i7-8700, warm native ZX runs a scalar and a structured workload 11× and 17× faster than the portable engine, Kryon's widget scenarios take 1.2–2.0 ms per two frames instead of the removed VM's 43–73 ms, and the Sieve, Records, Hash, Vectors and Printing kernels run within 1.3–4× of C. Shared frame slots, in-place member access, dropped checks where indices and pointers are proven, direct compare branches, buffered output and recycled vector blocks get it there.
- Native code compiled for a bundle is cached on disk (`$XDG_CACHE_HOME/ziran/native`), keyed by content, CPU features and compiler build; `ZIRAN_NATIVE_CACHE=DIR` moves the cache and `ZIRAN_NATIVE_CACHE=off` turns it off.
- Native bundles keep module state across hot reload and component replacement, return records, arrays and strings from host calls, start fresh locals as zeros and, built with `zi2zx --debug`, name the source line of a trap; `zx2native --emit map` shows the same origins, and `zx2native` executables take `--fuel N`.
- `.zx` is one format: `zi2zx` and `ziran run` write and open revision-28 executable ZX only. The semantic bundle format, its VM and the TinyCC tier are removed; rebuild older `.zx` files.
- WebAssembly has one route: `zx2wasm` lowers verified ZX with a typed host ABI and a heap. Wasm modules run faster (real loops, shared frame slots, buffered printing) and run in Asyncify runtimes such as Kryon's web player.
- The portable instruction engine runs verified ZX about 4–5 times faster.
- The embedding API runs revision-28 bundles with typed host calls: records, fixed arrays, strings, slices and handles cross the boundary, `[]T` changes copy back, globals read and write by name, and components carry state.
- ZX covers every `Simd` operation, `#parallel` loops, the bit builtins, unions, `New(T)`, `free`, pointer fields, builders, owned `Text`, the remaining `Vec` operations, and long `if`/`else if` chains and case lists.
- A closed C program carries only the code it uses: module headers declare only what other files name, runtime headers keep only the helpers it calls, and the entry is C's own `main`. Kryon's example headers shrink to a third of their size or less.
- Modules take compile-time parameters with `#module_parameters(...)` and `#import "module"(NAME = value)`, and `#insert NAME;` splices a compile-time string into the module as checked source. Saved `.zir` is version 65; regenerate saved `.zir` files.
- `std/temp` adds scoped temporary storage with mark/reset, `std/context` an explicit logger, scope tag and temporary allocator, and portable facades give one import for byte text, environment, timers, randomness, mapped files, streams, worker pools, directories and threads.
- Environment, argument, binary, file, HTTP and host-byte readers return typed outcomes that name why input was refused.
- `ziran learn on|off|status` keeps a local, size-capped corpus of native builds for a learning compiler. It is on by default and silent; `ZIRAN_LEARN=off` turns it off.
- The experimental direct pipeline lowers verified ZX to static Linux x86-64 ELF files with register allocation and no libc, and `ziran capabilities --json` lists assembly targets.
- `ziran inspect` shows each statement's source and what each expression means, and a saved ZIR file from another toolchain names both versions and how to rebuild.
- The toolchain builds and runs on macOS again, on Apple Silicon and Intel.
- The website's playground works again, and its Kryon widget table compares C, Go and native ZX with fresh measurements.
- Fixes: generated C indexes slices of pointers; Go compiles `VecSlice` with mixed-width bounds and module initializers that register host-calling procedures; calls through a module alias accept types it re-exports; `std/unicode` lowercases ASCII A–Z correctly; a string constant holding `#import` is no longer read as an import; `ziran check` matches a law's returned record by its declared type; `zi2zx` rejects `--opt` on ZX input.
## [0.4.2] - 2026-11-11
- `make zx-tools` builds the experimental scalar Linux x86-64 ELF path with verified IR, inspection dumps and source-range maps; other backends unchanged.
- Run a source file directly with `zi2zx run hello.zi`; website examples use the one-command `ziran run hello.zi` flow.
- The website's target page adds six JSON and UTF-8 workloads measured on Alpha, with downloadable output and raw samples.
- JSON readers scan long unescaped strings with SIMD, preserving borrowed text, escapes and error positions.
- SIMD byte-vector loads read immutable strings with whole-access bounds checks, and multi-module SIMD programs keep their operations in generated C.
## [0.4.1] - 2026-11-11
- Portable ZX runs unchanged desktop loop bundles about 14 times faster, with records, text and arrays also improving.
- The target page adds real Kryon widget scenarios with complete checked IR; Targets stays in shared navigation with its own IR inspector.
- The target matrix compares warm execution on desktop, Android and web with raw samples; medians exclude anomalies with 1.5×IQR fences.
- WebAssembly handles omitted slice bounds and empty slices at the end of arrays.
- Fresh native builds avoid optimizing the temporary bootstrap compiler.
- Generated C includes only the headers it uses and omits empty source files.
- `ziran inspect` inspects portable `.zx` bundles, including checked modules and bytes.
- Build WebAssembly with `ziran build --target=wasm`, including Hello World programs.
## [0.4.0] - 2026-11-10
- The website presents all four outputs in a target matrix: inspect C, Go,
portable ZX, direct WebAssembly and checked IR, download generated files,
run WebAssembly in your browser and compare measured target costs.
- The website gains a target matrix across C, Go, portable ZX, Wasm and checked IR, with downloads, in-browser Wasm and measured costs.
- `ziran run app.zx` discovers installed package runtime providers for host capabilities; console and graphical bundles share the command.
- `pkg paths PACKAGE...` returns ordered resolved paths as JSON after one graph validation.
- Reused compiler builds refresh embedded runtime headers by content, so restored timestamps cannot leave stale C helpers.
- Linked functions keep their copied capacities consistent with storage, preventing heap corruption after dead-code pruning.
- The parser, effect derivation, import linking, proof kernel, theorem checking and the `.zx` container run as Ziran code, with the same results.
- `#run` evaluates text of any length with builders, pointers, slices and folded loops, and shares one evaluator with `#if`, `#ifx` and `#assert`.
- `.Member` resolves against an enum imported from another module, and an imported constant can size an array.
- Record fields and enums take `#c "SPELLING"` so generated headers match shared C code; `const char *` fields compile and headers stop macro-defining constants.
- `#asm` takes slices, clobber ranges and one variant per line; `ziran run` runs them with TinyCC, bundles always run portable bodies.
- `-DZIRAN_NO_HEADER_INLINE` keeps generated C calls external, so link-time interposition such as `ld --wrap` sees every call.
- A `#target` procedure's SIMD-tier copies call that tier's `#inline` procedures; the AV1 decoder decodes 1080p frames 2–4% faster.
- A unary operator inside a binary one keeps its grouping in generated C and Go.
- Generated C proves away more bounds checks: pre-guard locals, fixed ranges, parameter fields, `else` branches, `ifx` picks; may-wrap checks stay and stored-before-read locals skip zeroing.
- Native SIMD vectors such as `s16xN` hold as many 128-bit blocks as the code handles, every width gives the same results, and `#target` picks the best instructions once at startup.
- Generated C includes only the SIMD helpers a program calls and compiles each tier in its own file; TinyCC compiles the AV1 decoder a third faster.
- The portable VM keeps `std/simd` vectors inline, TinyCC and unoptimized C run operations inline, and Go emits typed code per operation (352p AV1 decode 346 → 44 ms).
- `std/simd` adds `Simd.Sign` and `Simd.AbsDiff`, runs loads, stores, widening and 256-bit halves as single instructions, and its scalar fallback runs about nine times faster.
- Standard SIMD vectors such as `u8x16` and 256-bit forms give the same bits on every target.
- On 32-bit ARM, `f32` vector arithmetic keeps tiny values.
- `std/resample` kernels use `std/simd` instead of assembly, up to twice as fast with Wasm SIMD128.
- String constants over 4095 bytes build as strict C with escaped trigraphs, and generated C builds without warnings under `-Wall -Wextra`.
- Standard libc bindings use `usize`/`isize` sizes so they link and run on wasm32.
- `VecSlice` can view a global Vec or a Vec field, which cannot grow, be freed or be replaced while the view lives.
- `build --target=c --exe` links with Emscripten, keeping the `.wasm` file.
- Each `#load` file can store and index the same `Vec` or `Option`, and a public record with module-private field types builds in importing modules.
- Fresh `Text` in checker edge cases is freed with its block, and assigning a Vec or Text field frees the old value.
- Checking resolves constants through the lookup cache, `forall` laws check in half the time, and Breeze lowers 921 modules in under a second.
- `#reads` follows strings through field paths and marks read-only procedures and foreign calls, so `Text` passed through is freed too.
- A `Text` result only read in its statement or local is freed when its block closes; globals holding a `Vec` or `Text` can be assigned or moved.
- `std/vec` gains owned UTF-8 `Text`; `TextView` borrows, `TextCopy` copies, producers like `JsonWrite` return it, and files naming it import `std/vec` automatically.
- A local named like a C library function or Go builtin no longer hides it, and without a project `std/NAME` always loads the standard module.
- `make install-user` keeps a `~/.local/bin/ziran` wrapper and says so instead of failing.
- `for` loops, slicing and move-out work on Vec record fields; pushing or freeing while looping is rejected, and Go compiles `for` over a local Vec.
- Integer literals with separators, hex, binary and `u64` values above `s64` work in globals, constants, tables, array sizes and ranges.
- Shadowed locals such as `x := x + 5` in an inner block read the outer binding on every target.
- Generated C inlines small same-module and cross-module calls, copies arrays once, keeps one vectorizable loop exit, and honors `#inline` and `#cold`.
- Checked division, shifts and indexes run inline under TinyCC and unoptimized C, about 17% faster under `ziran run` and 24% faster at `-O0`.
- Constant tables bind across several loops, file-scope initializers and nesting, and constant arrays are read from one shared read-only copy.
- `ziran run` charges step budgets once per procedure and literal range, and portable programs use prepared function and global indices for calls and reads.
- Generated C accepts checked pointer casts to imported C callback types.
- `ziran run app.zx` discovers installed package runtime providers for host capabilities; console and graphical bundles use the same command.
- The website uses a simpler reading layout across the homepage, guides and API pages, with responsive navigation and the working browser playground.
- `pkg paths PACKAGE...` returns ordered resolved paths as JSON after one
graph validation, sharing `pkg path` selectors and cache checks.
- Reused compiler builds refresh embedded runtime headers by content, so
restored source timestamps cannot leave generated C using stale helpers.
- Linked functions keep their copied statement and expression capacities
consistent with their storage, preventing heap corruption when later
lowering appends nodes after dead-code pruning.
- Expression and initializer parsing build shared IR directly from Ziran,
removing the C callback parser. Compile-time quoted searches share the
Ziran source scanner.
- `#run` evaluates text of any length with builders, pointers, slices and
folded loops, and iterates array literals directly.
- `#asm` template, operand and clobber strings may name compile-time constants,
including templates generated in the same file. Local blocks retain these
strings through rechecking and saved IR; ARM NEON helpers support callers
built without NEON and with only 16 D registers.
- Effect-class derivation and `#law ... effect` evaluation run in Ziran
instead of C, preserving law results and diagnostic details.
- `.Member` resolves against an enum imported from another module, as in
`F(.Two)` for a `B.Kind` parameter, and an imported constant such as
`B.LIMIT` sizes an array.
- Import linking, file-private renaming and the `#inline` self-call check
run in Ziran instead of C, with the same diagnostics and checked names.
- The scalar proof kernel behind `#proof` is written in Ziran instead of C,
with the same proof results, diagnostics and step budget.
- Theorems and their `#proof` certificates are parsed, prepared and checked
by Ziran code instead of C, with the same results and diagnostics.
- The `.zx` container (header, capability, law and waiver tables, assets
and their limits) is written, read and checked against its program by
Ziran code instead of C; bundles keep the same bytes.
- Record fields and enums take `#c "SPELLING"` so a generated C header
matches C code that shares the records: `const char *` or `char name[N]`
fields, and enum constants with a prefix such as `ZIR_EXPR_`. Saved IR is
version 63.
- The compiler's IR records (modules, functions, statements, expressions,
types, laws and proofs) are defined once in Ziran; C includes the header
generated from them.
- A record whose array size names a constant, such as `[NAME_MAX]u8`, keeps
its fields' `#go_tag` and `#c` spellings; Go dropped the tags before.
- Ziran code reading or storing a pointer field spelled `#c "const char *"`
gets the right type in generated C, so it compiles without a const or
pointer-sign error.
- `#if`, `#ifx`, `#assert` and `#run` share one compile-time evaluator, and
enum values read integer literals as the language does (`0b10_1`, `1_000`).
- `#asm` routines take slices, clobber ranges such as `xmm0..xmm7` and
`q0..q1`, and one variant per line; the checker rejects undeclared or
reserved registers, and `-DZIRAN_ASM_CHECK` runs every variant against
the portable body. TinyCC assembles SSE2-SSE4.2 variants.
- `ziran run FILE.zi` runs `#asm` variants with TinyCC. Bundles keep them,
but a bundle file always runs the portable bodies, so a downloaded bundle
cannot run instructions of its own.
- `-DZIRAN_NO_HEADER_INLINE` keeps generated C calls on the external
definitions instead of header inline copies, so link-time interposition
such as `ld --wrap` sees every call again.
- A `#target` procedure's SSSE3, SSE4.1 and AVX2 copies call the same
tier's copy of each `#inline` procedure of the module, which ran SSE2
code or a call out of the tier's file before. The AV1 decoder decodes
1080p frames 2-4% faster.
- A unary operator inside a binary one keeps its grouping: Go read
`a ^ -b` as `(a ^ 0) - b`, and C read a float `-(-x)` as `--x`.
- A local such as `at := row * stride + column` declared before the guard
that bounds `row`, `column` and `stride` proves reads such as
`levels[at + stride]` in generated C, so they drop their bounds checks.
- Generated C skips the zero fill of a local declared without a value when
every element is provably stored before anything reads it, such as a
block filled row by row with `Simd.Store` in `for i: 0..7`.
- Generated C headers no longer define record and array constants as
macros in Ziran spelling; uses carry the value, as in Go.
- Native SIMD vectors such as `s16xN` hold as many 128-bit blocks as the
code running them handles: two in a `#target` procedure's AVX2 copy and
in AVX2 builds, one elsewhere. Loops step by `Simd.Lanes(s16xN)`, and
every width gives the same results.
- Generated C gets a copy of `ziran_simd_ops.h` holding only the SIMD
helpers the program calls, with the same object code. TinyCC compiles
the AV1 decoder's modules a third faster, which starts an uncached ZX
`ziran run` about 230 ms sooner on 32-bit Android.
- Generated C leaves out bounds checks that an `else` branch or a constant
left shift proves: `view[i - 1]` in the `else` of `if i == 0`, `t[i]`
under `if i != 8` in `for i: 0..8`, and `bytes[(row << 4) + t]`.
- `ziran run` of a ZX bundle without a native cache starts about 18% sooner
on 32-bit Android and 10% sooner on x86-64, with the same generated C.
- Generated C keeps the bounds check behind a guard on a sum or product
that may wrap: `if first + 1 + second > view.count { return }` no longer
removes the check of `view[first]`, through a local, an `ifx` choice or a
loop limit either.
- Generated C leaves out bounds checks a guard on a parameter's field
proves, such as `destination[i]` in `for i: 0..frame.count - 1` after
`if destination.count != frame.count { return }`, until a call or a store
through a pointer, slice or global could change the field.
- String constants and string globals longer than 4095 bytes build as strict
C (GCC and Clang `-pedantic -Werror`, TinyCC). Header string constants
are escaped like other C strings, so `??` text no longer forms a trigraph.
- std's libc bindings for `getcwd`, `readlink`, `read`, `write`, `poll`,
`bcopy`, `mempcpy` and `curl_ws_recv` use `usize` and `isize` for size_t
and ssize_t values, so they link and run on wasm32.
- `VecSlice` and `values[a:b]` can view a global Vec or a Vec field of a
global record. While the view lives, the Vec cannot grow, be freed or be
replaced, here or in a called procedure; the view cannot be returned or
kept outside its block.
- `build --target=c --exe` links with Emscripten's `emcc`, keeping the
`.wasm` file its launcher loads.
- Each `#load` file of a module can store and index the same `Vec` or
`Option` of a module-private record.
- A public record whose fields hold module-private types builds in modules
that import it: its C header now defines those types.
- A fresh Text from a procedure that only reads through a pointer argument,
as in `AwardsText(*awards)`, is freed with its block, and so is one read
by a local whose name another block also declares.
- A field of a local record or by-value parameter that holds a Vec or Text
can be assigned: `shelf.label = TextCopy(name)` frees the old value, and a
field moved out can be assigned again.
- Fixed a use-after-free in the checker when a record literal field
initializer was a fresh Text.
- `Simd.Load`, `Simd.Gather` and a returned constant array read the shared
table instead of copying it at every use, in C and Go, and `TABLE.count`
no longer builds the table.
- `std/simd` in the portable VM (`zi2zx run --vm`) runs about a quarter
faster: each call site works out its operation and operands once.
- Uncached `ziran run` of programs that use `std/simd` compiles in half the
time: C that only names vector types includes their small types header,
not every operation.
- The portable VM holds `std/simd` vectors of up to 128 bits inline in its
values: a 352p AV1 decode under `zi2zx run --vm` takes 4.9 s, from 6.5 s.
- Under TinyCC on x86-64 (`ziran run`), `std/simd` operations run inline
rather than as calls, and small records copy through registers: a cached
1080p AV1 decode takes 503 ms, from 697 ms.
- Under TinyCC and unoptimized C, `std/simd` multiplies, rounding shifts,
widening, narrowing and gathers run inline, and bounds checks and whole
slices (`a[:]`) cost no call: AV1's vector self-guided filter decodes
352p in 76 ms under a cached `ziran run`, from 95 ms.
- Go output computes each `std/simd` operation in its own typed code, which
Go inlines, instead of through one general lane interpreter: a 352p AV1
decode built as Go takes 44 ms, from 346 ms.
- Under TinyCC on every target, as on x86-64, `std/simd` operations run
inline, and vector loads and stores copy in place rather than through
memcpy. On 32-bit ARM, small records copy through registers and constants
build with movw and movt: a cached 352p AV1 decode under `ziran run` on a
Cortex-A53 phone takes 1.8 s, from 3.6 s.
- In C, locals, parameters and globals whose names begin with two
underscores, which C reserves, are renamed as keywords are.
- Under TinyCC and unoptimized C builds, checked division, shifts and index
reads are right when an operand is named like one of their temporaries,
such as `zi__a`.
- zi2c writes the C for large programs far faster: it works out how each
module's header includes its imports once, so Breeze's 921 modules lower in
under a second instead of over two minutes, with the same output.
- Checking resolves constants through the symbol lookup cache, as it does
types and procedures: Breeze checks about 0.25 s faster, AV1 about 15%.
`ZIRAN_VERIFY_SYMBOL_LOOKUPS=1` verifies constant lookups too.
- `tests/compiler_kernel_benchmarks.sh` no longer stops when another
commit lands during the run; it checks the tools, inputs and headers it
built and measured.
- `forall` laws check in about half the time, with the same results: each
law's condition is parsed once, a procedure's parameter list is split
once, and a call made again with the same arguments in a later case reuses
its result.
- The slice lifetime check finishes in a fraction of the time on large
programs: each pass rechecks only procedures whose callees or globals
changed, and callee summaries and recorded writes are looked up directly.
`ZIRAN_PROFILE` now reports the slice lifetime and law gate checks as
their own phases.
- `#reads` follows strings through field paths: a record parameter copied into
a local record's field is followed to its later uses, a later `=` into the
field replaces the string, and nested record fields are checked. Fresh Text
in a `:=` record local that is only read is freed with its block.
- A local override whose own manifest gained, lost or changed dependencies
since `ziran.lock` builds locally: its graph is resolved from the working
manifests in memory, and the lock is left for `ziran lock`. Packages without
an override and `--locked` builds keep the exact check.
- `ziran COMMAND --help` and `-h` print that command's usage and do nothing
else; `ziran update --help` used to rewrite the lock.
- A local override checked out past its locked commit is validated against the
graph its root dependency locks, so exact transitive pins of that package
no longer fail with a dependency-count mismatch.
- `std/simd` vectors such as `u8x16`, `s16x8` and `f32x4`, and 256-bit forms
such as `s16x16`, with operations that give the same bits in C (SSE2 to
AVX2, NEON and WebAssembly SIMD128), Go, bundles and the portable VM.
- A `#target` procedure runs the best x86-64 SIMD instructions the CPU has,
chosen once when the program runs. `ZIRAN_SIMD_TIER` lowers the choice,
and `#asm` variants needing a vector feature beyond it are passed over.
- `std/simd` works however it is imported or aliased, and short standard
imports such as `#import "simd"` also resolve through
`--module-path std=DIR`, as package tests pass it.
- SIMD loads, stores, widening and 256-bit halves compile to single
instructions instead of copies through memory.
- `std/simd` under `ziran run`, TinyCC and `ZIRAN_SIMD_SCALAR` runs about
nine times faster: each operation works on its own lane type, and TinyCC
on x86-64 uses SSE2 for the common integer operations.
- `Simd.Sign` and `Simd.AbsDiff`. 256-bit vectors run as two 128-bit halves
without AVX2, and reductions, `MulWide`, `Narrow` and `AddPairs` use
fewer instructions.
- On 32-bit ARM, `f32` vector arithmetic keeps tiny values instead of
flushing them to zero, and byte shifts of 256-bit vectors are correct.
- `std/resample`'s kernels use `std/simd` instead of assembly. They make the
same bytes and run faster: at least as fast with AVX2 and about 20% faster
on large downscales, 3 to 10% faster with NEON on a Cortex-A53, and about
twice as fast with WebAssembly SIMD128.
- On 32-bit ARM, Clang builds `Simd.LoadLow` as one load instead of copying
the bytes through the stack.
- `Text` in `std/vec` is owned UTF-8 text that frees its bytes with its
owner. `TextView(text)` borrows it, a `Text` passed where a `string` is
expected lends the same view, and `TextCopy` copies a string into one.
- A procedure can return `Text` to callers written for a `string` result:
they get a string as before, while `result: Text = Render(...)` frees it
with `result`. `BuilderFinish` gives a `Text` where one is expected.
- Standard text producers such as `TextReplace`, `Float64Repr`, `JsonWrite`
and `JoinPath` return `Text`. Existing callers still get a `string`;
`json: Text = JsonWrite(...)` frees the text when `json` goes away.
- A `Text` result only read within its statement, as in
`Count(JsonWrite(...))`, `Render(a) == Render(b)` or `.count`, is freed
when its block closes instead of kept for the program.
- A local such as `line := Render(...)` that is only read, compared,
counted or passed to a procedure that only reads it is freed when its
block closes too.
- Such a result passed through an `ifx` arm, a local, a procedure that
returns it, or a record literal field such as `Props.{.text = Render()}`
whose callee only reads that field is freed the same way.
- Such a result handed to std/format's `Append` or `BuilderPrint`, whose
first argument is the builder's address, is freed too.
- A callee that copies its string parameters into a local `[N]string` and
only reads the elements, or that points a `string` local at other views
of them with `=`, as in `v = s[1:3]`, only reads them.
- A procedure type marked `#reads` after its result, as in
`Painter :: #type (label: string) -> s32 #reads;`, only holds procedures
that read their strings, so Text passed through it is freed too. Saved IR
is format 62.
- Text read in an `else if` condition, after `&&` or `||`, or in an `ifx`
that gives a number or `bool` is freed when its block closes.
- A global holding a `Vec` or `Text`, alone or in a record, can be assigned,
which frees its old value, and moved into a local or returned, which
leaves it empty.
- A file that names `Text` or `Vec(T)` imports `std/vec` automatically, so
its C header, bundle and Go code see the same types as the code that made
them. A parameter or return type that names no visible type is an error.
- `#reads` before `#foreign` marks a foreign procedure that only reads its
string and byte arguments, so Text passed to it is freed too.
- A `-1` or a global argument before such a result no longer keeps it,
unless the producing call may change a global.
- A local named like a C library function, such as `free`, no longer hides
it in generated C, and one named like a Go builtin no longer hides it in
Go.
- `make install-user` keeps a `~/.local/bin/ziran` that launches another
tool, such as a build queue wrapper, and says so instead of failing.
- `for h.items`, `for * h.parts`, `for it.tags` and `h.items[1:]` work on a
Vec record field, and a record field holding Vecs moves out, as in
`last := popped.value`. Pushing to or freeing a Vec while a loop over it
runs is rejected, also through a field or a called procedure.
- Go output of `for v` over a local Vec compiles again.
- A constant table read in several loops of one function, or through
`.count`, no longer fails with "cannot bind aggregate constant".
- Integer literals such as `1_000`, `0xDEAD_BEEF`, `0b1010_0101` and `u64`
values above the `s64` maximum work in globals, `::` constants, constant
tables, array sizes and range bounds, and pass the portable VM's checks.
- `x := x + 5` in an inner block, and `i := ...` in a `for` body over `i`,
read the outer binding on every target; generated C no longer reads the
new local, and the VM no longer steps the shadow instead of the loop.
- Generated C leaves out bounds checks it proves always pass, such as
`t[i]` in `for i: 0..7` over a `[8]T` array, `view[i]` in
`for i: 0..view.count-1`, `table[x & 255]`, and `bytes[at]` after
`line := row * 16` and `at := line + (offset & 15)`.
- `#inline` after a procedure's result always inlines it in generated C,
and `#cold` keeps a slow path out of line, including other modules' calls.
- A procedure returning an array copies it to the caller once in generated
C, and `return Make(n)` writes the caller's array directly.
- A local array passed by value to a Ziran procedure is copied once in
generated C, not by both the caller and the callee.
- Generated Go shifts by a variable count without the general integer
helper, and copies a constant table straight from its shared `var`.
- A file-scope variable can start from a constant table of any length,
such as `table: [4096]u8 = BIG`, instead of failing past 4 KiB.
- Constant tables can be nested, as in
`GRID :: [3]s32.[s32.[1, 2, 3], s32.[4, 5, 6]]` or a `#run` procedure
that fills `g[a][b]`, and `GRID[i][j]` reads the table without a copy.
- Generated C also leaves out bounds checks an earlier guard proves, such as
`input[row * stride + column]` in loops over `row` and `column` after an
`if` that returns when `input.count` is too small.
- Those checks stay out when the loop body has an `if` that continues or
returns, such as `if flag > 3 { continue }`, or an enclosing `if i < 32`,
and for rows `stride` apart after a guard that `stride >= width`.
- They also stay out for a row or column a flip picks with `ifx`, and after
a guard written as `cast(s64)(height - 1) * stride + width`.
- A long `||` guard with comparisons no index uses still proves the reads,
and so does a filter window that starts `radius` rows and columns back.
- `ziran run` spends its step budget more cheaply: each procedure finds its
budget once instead of at every loop iteration, so an AV1 decode runs
about 7% faster.
- Code built by TinyCC (`ziran run`) or by GCC and Clang without
optimization checks indexes, shifts and divisions in place instead of
calling a helper, so an AV1 decode runs about 17% faster under `ziran run`
and 24% faster at `-O0`. Optimized builds are unchanged.
- `ziran run` charges a loop over literal bounds, such as `for i: 0..7`, its
whole step count once as it starts rather than at every iteration.
- Generated C emits a call of a small procedure of the same module as that
procedure's body, so `ziran run` (TinyCC) and unoptimized builds skip the
call: an AV1 decode runs about 7% faster under `ziran run` and 4% faster at
`-O0`. A private procedure every caller inlined is no C warning.
- Generated C builds without warnings under GCC and Clang `-Wall -Wextra`:
an `ifx` comparison gets one pair of parentheses, a local nothing reads is
cast to void, and a procedure named like `ReadSignedBits` no longer pulls
in an unused helper.
- Generated C builds the SIMD tier copies of a large `#target` procedure in
their own files, such as `inverse_transform.avx2.c`, so a parallel C build
compiles them at the same time. An AV1 decoder builds at `-O2` about 40%
faster with 8 jobs.
- A range over a computed bound, such as `for i: 0..count`, tests the bound
once as it starts and then leaves only at its last value. Generated C has
one loop exit, which GCC can vectorize, and an AV1 decode runs about 2%
faster at `-O2`.
- Generated C writes an array call result straight into the local or array
lvalue it initializes or is assigned to, without a temporary and a copy.
- Small public procedures are inlinable across modules in generated C
without LTO: their header carries a `static inline` copy for other modules.
- Generated C divides and shifts by a nonconstant operand through a checked
helper of its width, and shifts signed values right by a constant with one
arithmetic shift, keeping the zero-divisor and shift-count aborts.
- Constant number and boolean arrays of any length (`TABLE :: s32.[...]`, also
through `#run`) are read-only tables: `TABLE[i]` reads one shared copy on C,
Go and the VM instead of copying the array at every read.
- `clz`, `ctz`, `popcount` and `bswap` builtins for `u8`, `u16`, `u32` and
`u64`, with the width as the count for zero, on C, Go and the VM.
- A Vec can hold Vecs and records that own Vecs: `VecPush` moves the element
in, `groups[i].parts[j]` reads and writes in place, and dropping frees the
inner Vecs. A discarded owned record result, such as `VecPop`'s, is freed.
- A local override that no longer matches `ziran.lock` now names the package, its source and the mismatched pin instead of "cannot fetch locked packages"; `GIT_TRACE` no longer makes a clean package cache look modified.
- `std/thread_linux` links and polls on macOS, which has no `pthread_tryjoin_np`.
- Array literals have no size cap and check in linear time; saved IR is
bounded only by its 256 MiB read budget. Returning a view of a pointer
parameter's own array storage is rejected; pass that storage as a slice.
- Native C keeps an array literal of constant numbers or booleans as one
static table instead of a store per element, so large tables compile fast.
- `ziran edit` previews and applies checked source edits; `ziran compact` and
`ziran expand` give `.zi` files an optional lossless compact transport.
- JSON diagnostics keep each message within 2048 bytes and report cuts in a
`truncation` field.
- `std/unicode` adds Unicode 17 `NFCInto`, `LowerInto` and exact letter,
number and white-space properties.
- `std/json_document` owns its bytes per node, adds `JsonReset`, caller-owned
`Into` accessors and erasers that wipe private buffers.
- `std/file_tree_linux` adds `FileSnapshot` and `SameFileSnapshot` to tell
whether a file was changed or replaced.
- `std/process_channel_linux` accepts up to 32 arguments and can discard
stderr; `std/socket_linux` adds `SocketCloseWrite`.
- Curl HTTP accepts named header values up to 8191 bytes.
- `std/image` adds fallible caller-owned resampling and bicubic resize;
`std/float_text` adds `Float64ReprInto`.
- `std/resample` gives programs Pillow's resize as allocation-free row
kernels, with SSE2, AVX2, NEON (AArch64 and ARMv7) and WebAssembly SIMD128
versions that make the same bytes.
- `#asm` adds `arm+neon` for ARMv7, selected at run time, and
`wasm32+simd128` for WebAssembly builds made with `-msimd128`.
- Native C generation accepts checked pointer casts to imported C callback types;
Go and portable targets continue to reject C callbacks.
- Package overrides selecting one locked revision now share its dependency graph
across older transitive revisions, including newly added dependencies.
- Without a project, `std/NAME` always loads the standard library's module, even
when a search path or the importing package has its own module named NAME.
- Portable programs use prepared function and global indices for calls and reads, reducing repeated-call execution time.
### Added
- Owned vectors support fallible reserve, resize and capacity-bounded resize with
matching C, Go and portable execution, initialized defaults and safe owned-element cleanup.
- `std/web.WebBlobBytes` snapshots file or media bytes into a browser Blob
without first making a separate typed-array copy. The snapshot remains valid
after source changes or Wasm memory growth.
- Project commands such as `ziran bundle --project` accept `--module-path DIR`
for modules a build step generates. They join the project's own modules;
dependencies still resolve only from the lock and never see them.
- `--exe --release` builds with link-time optimization across modules.
- `#parallel_gpu for` runs on the fastest GPU in native Linux and Android builds,
falling back to CPU threads.
- Python build tools can consume verified dependency artifacts and ordered
native link metadata through the toolchain's shared artifact helper.
- Dependency-owned native artifact recipes build and reuse declared output sets
through the locked package graph, with explicit platform/ABI identities,
resolved options, input validation and atomic publication.
- `std/utf8` gained bounded `Copy`, which preserves valid bytes, repairs
malformed input with U+FFFD, never splits an output sequence, and reports
the written count and completion separately.
- `std/text_tools` gained `TextHexDecodeInto`, which appends bounded
uppercase or lowercase hexadecimal bytes and leaves its output unchanged on
every failure.
- Linux and Android hosts on x86-64, ARM and ARM64 run portable bundles as native code, compiled in memory and cached between launches.
- Natively run bundles execute `#parallel for` regions on worker threads, one per processor.
- `#parallel for` bodies can hand out results by writing their own slot of an array or slice the function owns, such as `out[it] = value`, or their own window of a slice, such as the row `pixels[it * width : it * width + width]`.
- The new `zi2wasm` tool lowers a checked program's scalar subset to one wasm32 module: the portable control flow, calls, casts and wrapped integer widths, with a step-budget import matching the native tier's counting. Programs outside the subset fail with a `zx.wasm` diagnostic, and `tests/zx_wasm.sh` compares the module's result with the native tier and the portable VM under node (and wasmtime when installed).
- The wasm execution tier and `zi2wasm` lower strings, slices and module globals: string values are i64 handles over interned data-segment literals with byte indexing, `.count` and equality through a generated compare helper; slices borrow their base's storage as (length, address) handles with bounds-checked element views; globals take fixed data-segment slots whose literal bytes reload fresh on every instantiation. Pointers cross as opaque handles. Probing Inner Breeze's real bundles now passes strings, slices and pointer signatures, leaving enums and expression-initialized globals as the remaining rejections.
- The wasm execution tier and `zi2wasm` lower records and fixed arrays: fields laid out exactly as the checker sizes them, values as arena slots with lexical region lifetimes, literals, member and index places with bounds checks, value copies through calls and returns, and parameter slots the callee owns.
- `BundleInstantiate` gained a WebAssembly execution tier behind a provider seam (`ZxWasmSetPlatform`): with a provider installed, bundles in the scalar subset run as WebAssembly lowered from their verified IR at open time, and everything else falls back to the portable VM; without a provider, behavior is unchanged. Native TinyCC hosts are untouched. `tests/zx_wasm_engine_test.c` checks the seam, handoff and fallback natively, and `tests/zx_wasm_web.sh` runs a bundle end to end through the wasm-built library and a JavaScript provider (skipped without emcc and node).
- `std/vorbis` reads an in-memory Ogg Vorbis stream's channels, rate and length from its pages, without decoding or a library, so programs can bound a stream before decoding it.
- `std/vorbis_linux` decodes whole in-memory Ogg Vorbis streams to 16-bit PCM over the platform libvorbisfile, with a frame limit and strict refusal of truncated, chained or damaged streams. Only programs that import it link the library.
- Owned vectors support fallible reserve and resize with matching C, Go and portable behavior.
- `std/web.WebBlobBytes` snapshots file or media bytes into a browser Blob without a typed-array copy.
- Project commands accept `--module-path DIR` for generated modules; dependencies still resolve only from the lock.
- `--exe --release` builds with link-time optimization.
- `#parallel_gpu for` runs on the fastest GPU in native Linux and Android builds, falling back to CPU threads.
- Python build tools consume verified dependency artifacts, and dependency-owned artifact recipes publish declared outputs atomically.
- `std/utf8` gains bounded, repairing `Copy`; `std/text_tools` gains `TextHexDecodeInto`.
- Linux and Android hosts on x86-64, ARM and ARM64 run portable bundles as native code, cached between launches, with `#parallel for` on one worker thread per processor.
- `zx2wasm` lowers a checked program's scalars, strings, slices, globals, records and fixed arrays to one wasm32 module; other programs fail with named diagnostics.
- `BundleInstantiate` gained a WebAssembly execution tier behind a provider seam; other bundles fall back to the portable VM.
- `std/vorbis` reads a stream's channels, rate and length; `std/vorbis_linux` decodes whole streams to 16-bit PCM, linking the library only on import.
### Removed
- The Python target: `zi2py`, `--target=py`, `py:` imports and the `std/*_py`
modules. Run native scripts with `ziran run --target=c`.
- The separate `zi2zx-vm` runner. `zi2zx run --vm FILE` runs a bundle on the
portable VM instead.
- The Python target: `zi2py`, `--target=py`, `py:` imports and the `std/*_py` modules. Run native scripts with `ziran run --target=c`.
- The separate `zi2zx-vm` runner; `zi2zx run --vm FILE` runs a bundle on the portable VM instead.
### Changed
- Native `--exe` builds default to `-O3`, and lowering a ZX bundle to C is
faster because read-only field walks no longer copy each field.
- Compiler commands run at low CPU and disk priority (`ZIRAN_NICE`) and use at most half of the CPUs, bounded by free memory (`ZIRAN_JOBS` lowers it). `zi2c` writes C on worker processes, and the lifetime check no longer rescans every global and function, which halves Breeze's front-end time. `--prune-stale` also cleans subdirectories.
- Native `--exe` builds default to `-O3`, and lowering a ZX bundle to C no longer copies each read-only field.
- Compiler commands run at low CPU and disk priority and use at most half the CPUs, bounded by free memory (`ZIRAN_NICE`, `ZIRAN_JOBS`).
- Native builds run `#parallel for` regions on one thread per processor instead of four; `ZIRAN_PAR_THREADS` still chooses.
- Saved IR (format 59) writes each string once and refers back to it, stores numbers in as few bytes as they need, and stores source positions relative to the previous one, so `.zir` files and `.zx` bundles carry about a third of their former code size at the same open cost. Rebuild format 58 IR and bundles from source.
- Saved IR writes each string once and stores numbers compactly, so `.zir` files and `.zx` bundles carry about a third of their former size; rebuild format 58 files.
### Fixed
- The later lines of a string that spans several lines keep their text: `int`
and `float` there became `s64` and `float32`, and assembly such as
`vmov.i32` was rejected as an old type spelling.
- The standard vector reference includes capacity operations, and their portable
regression test links correctly with an instrumented compiler library.
- Portable record globals correctly initialize fields from open-import constants,
including imports used only by initializers.
- Keep caching native script runs when the compiler binary is larger than 16 MiB.
- `ziran lock` and `ziran update` resolve a project that depends on a package and also pins the same repository commit as a source checkout, such as a game and its artwork. The source checkout gets its own lock entry instead of failing with "cannot update project lock"; existing locks still verify.
- Android applications report portable execution errors in the system log, so failures can be diagnosed when no terminal is attached.
- Artifact recipes accept up to 256 inputs, so a provider with a long source
list no longer fails with "unknown or invalid artifact recipe".
- Add-ons can use records, functions and globals that a shared library did not
retain, even when both use the same module. Only such add-ons need portable
bundle format 27; every other bundle is written as format 26, so hosts built
before 27 still open it.
- Native C builds keep globals and constants separate from foreign library symbols, so a variable such as `open` cannot replace the system file-opening function and crash the program.
- `ziran lock` and `ziran update` lock one package when manifests name the same commit by a branch and by that commit; they failed with "cannot update project lock". A full-commit ref now matches a package locked at that commit.
- Bundles accept arrays of fixed arrays as function and host capability parameters.
- `#parallel for` regions reject mutating, foreign and procedure-value calls nested inside larger expressions.
- Native parallel workers see every binding their body reads, including parameters and fixed arrays.
- `#parallel for` bodies can write into arrays they declare themselves.
- Saved IR keeps the result type of a call whose argument is another call with widened arguments, such as `!Open(board, Index(x, y))`, so builds from it no longer fail with "saved IR does not match the checked program".
- `#parallel for` regions reject handing a shared slice to a callee that writes through it, directly or by passing it on.
- Natively run bundles reach a bound Ziran provider exported under another symbol.
- Go output converts a conditional's arms to its type, such as a float32 arm of a float64 conditional.
- `StartProcess` and `RunProcess` open input, output and error files relative to the caller's working directory, before the child changes into `directory`.
- Later lines of a multiline string keep their text instead of old type spellings.
- Portable record globals initialize fields from open-import constants.
- Caching native script runs survives compiler binaries larger than 16 MiB.
- `ziran lock` and `ziran update` resolve a commit also pinned as a source checkout, and lock one package named by branch and by commit.
- Android applications report portable execution errors in the system log.
- Artifact recipes accept up to 256 inputs.
- Add-ons can use records, functions and globals a shared library did not retain; only those bundles need format 27.
- Native C builds keep globals and constants separate from foreign library symbols.
- Bundles accept arrays of fixed arrays as parameters.
- `#parallel for` regions reject mutating nested calls and shared-slice writes; native workers see every binding their body reads.
- Saved IR keeps the result type of a call whose argument is another call with widened arguments.
- Natively run bundles reach a provider exported under another symbol.
- Go output converts a conditional's arms to its type.
- `StartProcess` and `RunProcess` open redirected files relative to the caller's directory.
## [0.3.1] - 2026-10-23
### Fixed
- Source generation now preserves output errors on hosts that use file-backed text streams.
- Website release links now follow the installed compiler version.
- Source generation preserves output errors on hosts using file-backed text streams.
- Website release links follow the installed compiler version.
## [0.3.0] - 2026-10-23
### Changed
- Portable executables and libraries now use `.zx`, the `zi2zx` tool, and the `zx` target. Source stays `.zi` and checked intermediate modules stay `.zir`. Rebuild previous `.zib` programs; renaming a file does not convert it.
- Portable executables and libraries use `.zx`, the `zi2zx` tool and the `zx` target; source stays `.zi`, checked modules `.zir`. Rebuild previous `.zib` programs.
### Fixed
- Go output no longer needs temporary filesystem space and reports output write failures instead of producing incomplete source files.
- Go output no longer needs temporary filesystem space and reports output write failures.
## [0.2.0] - 2026-09-28
### Added
- `ziran version` (and `--version`) prints the compiler version.
- Release tags now follow the compiler, so `ref = "v0.2.0"` in `ziran.toml` pins a release.
- Release tags follow the compiler, so `ref = "v0.2.0"` in `ziran.toml` pins a release.
### Changed
- A clean build of the compiler is much faster and uses at most eight cores.
+860 -217
View File
File diff suppressed because it is too large. Load diff
+49 -77
View File
@@ -1,105 +1,77 @@
# Ziran
Ziran is a general-purpose language that compiles to C and Go. The toolchain checks source, saves checked modules, and builds portable
programs you can run without a native compiler.
Ziran is a general-purpose language with direct native, WebAssembly, portable
ZX, C and Go output. Master includes Unreleased work; the current version is
in [VERSION](VERSION) and [CHANGELOG.md](CHANGELOG.md).
[Website & playground](https://ziran-lang.org/) · [Compiler guide](docs/USAGE.md) · [Implementation status](docs/IMPLEMENTATION_STATUS.md)
The compiler and portable runner are under active development. Language
coverage and target limits are listed in the implementation status.
## Try it
```jai
main :: () {
print("Hello, World!\n");
}
```
Edit and run this example in the [browser playground](https://ziran-lang.org/).
[Website and playground](https://ziran-lang.org/) · [Compiler guide](docs/USAGE.md) · [Current support](docs/IMPLEMENTATION_STATUS.md)
## Quick start
You need Make, a C11 compiler, and GNU binutils. From the repository root:
Build with Make, a C11 compiler and GNU binutils:
```sh
make
build/bin/ziran bundle --root site/examples --entry hello:main \
-o build/hello.zx site/examples/hello.zi
build/bin/ziran run build/hello.zx
build/bin/ziran check examples/hello.zi
build/bin/ziran run examples/hello.zi
build/bin/ziran build examples/hello.zi
```
This prints `Hello, World!`. To install the `ziran` command for your user, run
`make install-user` and add `~/.local/bin` to your `PATH`. Then start a
project from a template and run it:
`run` checks and executes `main`; `build` defaults to a direct native binary.
`make install-user` installs the tools in `~/.local/bin`.
```sh
ziran new hello # or --template lib, or a package's template
cd hello
ziran run -- Ada # Hello, Ada!
```zi
main :: () { print("Hello, World!\n") }
```
See [packages and projects](docs/PACKAGES.md) for templates, dependencies,
and `ziran build`/`install`.
## Tools
## Tools and formats
Use `build/bin/ziran` from the checkout, or `ziran` after installation.
Source → ZIR → LIR → optimized LIR → ZX → native (ELF/PE, x86-64/AArch64/ARMv7).
WebAssembly lowers from verified ZX through `zx2wasm`; C and Go export from ZIR
through `zi2c` and `zi2go`.
| Command | Purpose |
| --- | --- |
| `check` | Validate source and imports. |
| `build` | Generate C or Go output. |
| `ir` / `inspect` | Save checked modules and read their contents. |
| `bundle` / `run` | Build and run portable programs; `run --target=c FILE.zi -- ARGS` runs native scripts. |
| `fmt` | Format source files. |
| `guide` / `features` / `capabilities` | Explore syntax, support, and target limits. |
| `api` | Query public declarations as JSON. |
| `build` | Build native output, or select `--target=c`, `go`, `wasm` or `zx`. |
| `ir` / `inspect` | Save checked `.zir` modules and inspect artifacts. |
| `bundle` / `run` | Link `.zx` executables and run source or ZX. |
| `learn` | Control native-build corpus recording and offline C-teacher verification/training. |
| `fmt` | Format source. |
| `guide` / `features` / `capabilities` | Query syntax and target limits. |
| `api` | Query checked public declarations. |
Source files use `.zi`, checked modules use [`.zir`](docs/ZIR.md), and portable
programs use [`.zx`](docs/ZX.md). Native targets and the portable runner have
different limits.
## Standard library
The library includes text and UTF-8 helpers, generic values, sorting, queues,
JSON scanning, ZIP archives, and explicit HTTP and process capabilities.
Native Linux adapters provide file, socket, timer, and other system operations.
See the [standard library reference](https://ziran-lang.org/stdlib.html) and
[compiler guide](docs/USAGE.md#standard-library) for imports and platform limits.
Safety is manual by default, as in C. `--checks` opts a build into runtime
checks; `#checks` keeps bounds checks in selected source regions. See
[checks](docs/USAGE.md#checks) for target-specific behavior.
## Documentation
| Start here | What it covers |
| Read | When you need |
| --- | --- |
| [Compiler guide](docs/USAGE.md) | Commands, imports, foreign functions, and standard modules. |
| [Examples](https://ziran-lang.org/examples.html) | Small programs with source and output. |
| [Implementation status](docs/IMPLEMENTATION_STATUS.md) | Supported features and remaining work. |
| [Architecture](docs/ARCHITECTURE.md) | Compiler, runtime, and library boundaries. |
| [Language direction](docs/LANGUAGE_DIRECTION.md) | Language design and tooling goals. |
| [Jai parity roadmap](docs/JAI_PARITY_ROADMAP.md) | Planned language work. |
| [Benchmarks](bench/README.md) | Compiler and runtime measurements. |
| [Migration](docs/MIGRATION.md) | Repository migration details. |
| [docs/USAGE.md](docs/USAGE.md) | The compiler and standard library guide |
| [docs/IMPLEMENTATION_STATUS.md](docs/IMPLEMENTATION_STATUS.md) | Supported targets and limits |
| [docs/PACKAGES.md](docs/PACKAGES.md) | Packages, projects, and lock files |
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | The compiler pipeline |
| [docs/LANGUAGE_DIRECTION.md](docs/LANGUAGE_DIRECTION.md) | Language syntax and directives |
| [docs/OWNED_VALUES.md](docs/OWNED_VALUES.md) | Owned values and recoverable failures |
| [docs/DIAGNOSTICS.md](docs/DIAGNOSTICS.md) | Diagnostic codes and JSON output |
| [docs/AUTHORING.md](docs/AUTHORING.md) | Tool-driven editing workflows |
| [docs/LAWS.md](docs/LAWS.md) | Laws and proof certificates |
| [docs/ZX.md](docs/ZX.md) | The portable ZX format |
| [bench/README.md](bench/README.md) | Running benchmarks |
| [plans/open-work.md](plans/open-work.md) | What is still open |
Kryon is a separate UI library that applications import explicitly.
Standard library and package APIs: [ziran-lang.org/modules.html](https://ziran-lang.org/modules.html).
Kryon is a separate UI library imported by applications; console programs have
no graphics dependency. Repository rules for agents live in
[AGENTS.md](AGENTS.md).
## Development
Run `make check` for the language, backend, and portable runtime checks.
Tests use four workers by default; set `CHECK_JOBS=1` to run them serially.
The native command and formatter are written in Ziran. Compiler scanners,
declaration, foreign binding, and `using` modifier syntax, enum validation and
evaluation, type spelling and field parsing, expression and nested initializer
grammar, statement expression extraction, loop headers, optional `then`, and
compile-time branch syntax are also written in Ziran. Ziran also parses multiple
results and bindings, normalizes procedure-type parameters, expands formatted
builder statements, and rewrites
symmetric operators, procedure-name expressions, and local procedure names.
The rest of the compiler is still being migrated from C.
A fresh build uses the generated modules in `bootstrap/` to build a bootstrap
compiler, then compiles their maintained `cmd/compiler_*.zi` sources for the
ordinary tools. Run
`make check-bootstrap` to verify that the generated seed matches the source.
After changing a compiler module, use `make update-bootstrap` to refresh its seed.
Run `make check` for the retained local suite and `make check-bootstrap` for
bootstrap reproducibility. `CHECK_FILTER=text` selects matching tests. The
compiler uses maintained Ziran and C sources; bootstrap seeds live in
`bootstrap/`. Refresh affected seeds with `make update-bootstrap` after
compiler changes.
+1 -1
View File
@@ -1 +1 @@
0.4.0
0.8.0
+99
View File
@@ -0,0 +1,99 @@
ASSEMBLY_C := $(BUILD_DIR)/compiler-assembly
ASSEMBLY_MACHINE_SOURCES := cmd/compiler_vector_form.zi cmd/compiler_vectorize.zi cmd/compiler_vector_x86.zi \
cmd/compiler_target.zi cmd/compiler_machine_image.zi cmd/compiler_abi.zi cmd/compiler_machine_ir.zi \
cmd/compiler_machine_verify.zi cmd/compiler_machine_aggregate.zi cmd/compiler_machine_fields.zi cmd/compiler_machine_select.zi cmd/compiler_machine_lower.zi \
cmd/compiler_machine_verify_allocated.zi cmd/compiler_regalloc.zi cmd/compiler_x86_bytes.zi cmd/compiler_x86_64.zi cmd/compiler_x86_runtime.zi \
cmd/compiler_x86_win64.zi cmd/compiler_x86_host.zi cmd/compiler_x86_image.zi \
cmd/compiler_encode.zi cmd/compiler_aarch64.zi cmd/compiler_aarch64_runtime.zi cmd/compiler_aarch64_elf.zi cmd/compiler_armv7.zi cmd/compiler_armv7_runtime.zi cmd/compiler_armv7_elf.zi \
cmd/compiler_arm_bytes.zi \
cmd/compiler_machine_elf.zi cmd/compiler_machine_pe.zi cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi
ASSEMBLY_SOURCES := std/math.zi cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_zir_lower.zi cmd/compiler_zx_run.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_debug.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_ssa.zi cmd/compiler_opt_rotate.zi cmd/compiler_opt_loop.zi cmd/compiler_opt_licm.zi cmd/compiler_opt_induction.zi cmd/compiler_opt_layout.zi cmd/compiler_opt_inline.zi cmd/compiler_opt_specialize.zi cmd/compiler_opt_thread.zi cmd/compiler_opt_accumulate.zi cmd/compiler_opt_dom.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi $(ASSEMBLY_MACHINE_SOURCES)
ASSEMBLY_SOURCES += std/finite.zi
ifneq ($(BOOTSTRAP),1)
ifeq ($(NATIVE_HOST_ENABLED),1)
# Only these objects read the generated assembly headers. A target-specific
# CFLAGS would also reach the prerequisites make builds for it, zi2c among
# them, where the set's own math.h and vec.h would shadow the real ones;
# `private` prevents that but needs GNU Make 3.82, and macOS ships 3.81.
$(foreach source,bootstrap/runtime/zir_host_native.c bootstrap/runtime/zir_host_native_armv7.c,\
$(eval $(call obj,$(source))_CFLAGS += -I$(ASSEMBLY_C)))
$(call obj,bootstrap/runtime/zir_host_native.c bootstrap/runtime/zir_host_native_armv7.c): $(ASSEMBLY_C)/.generated
endif
endif
.PHONY: zx-tools
zx-tools: $(BIN_DIR)/zi2zx $(BIN_DIR)/zx2wasm $(BIN_DIR)/zx2native
check: zx-tools
# The generator runs whenever its sources or zi2c change, but only files
# whose text changed are replaced, and .generated moves only then: a zi2c
# relinked for a new checkout path (a prebuilt tree) recompiles nothing.
$(ASSEMBLY_C)/.ran: assembly.mk $(ASSEMBLY_SOURCES) $(GEN_ZI2C)
rm -rf $(BUILD_DIR)/compiler-assembly.next
env -u DISPLAY -u WAYLAND_DISPLAY $(GEN_ZI2C) --no-main --root cmd -o $(BUILD_DIR)/compiler-assembly.next \
cmd/compiler_lowered_verify.zi cmd/compiler_zir_lower.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi \
cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi cmd/compiler_zx_run.zi
@mkdir -p $(ASSEMBLY_C); changed=; \
for f in $(BUILD_DIR)/compiler-assembly.next/*; do \
cmp -s "$$f" "$(ASSEMBLY_C)/$${f##*/}" || { cp "$$f" $(ASSEMBLY_C)/; changed=1; }; done; \
for f in $(ASSEMBLY_C)/*; do \
[ -e "$(BUILD_DIR)/compiler-assembly.next/$${f##*/}" ] || { rm -f "$$f"; changed=1; }; done; \
if [ -n "$$changed" ] || [ ! -e $(ASSEMBLY_C)/.generated ]; then touch $(ASSEMBLY_C)/.generated; fi
rm -rf $(BUILD_DIR)/compiler-assembly.next
touch $@
$(ASSEMBLY_C)/.generated: $(ASSEMBLY_C)/.ran
@test -f $@ || touch $@
$(BUILD_DIR)/obj/assembly-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(BUILD_DIR)/.compiler-flags
@mkdir -p $(BUILD_DIR)/obj/assembly
@set -eu; objects=; for source in $(ASSEMBLY_C)/*.c; do \
object=$(BUILD_DIR)/obj/assembly/$$(basename "$$source" .c).o; \
$(CC) $(CFLAGS) $(FRAMEFLAGS) -I$(ASSEMBLY_C) -c -o "$$object" "$$source"; \
objects="$$objects $$object"; \
done; $(CC) -r -nostdlib -o $@ $$objects
# The embedding library already carries the source compiler and the verified-ZX
# engine, including its own compiler_bundle symbols. Keep the native machine
# pipeline in a separate relocatable object so linking libziran cannot pull in a
# second copy of those public symbols from assembly-core.o.
ASSEMBLY_NATIVE_MODULES := compiler_vector_form compiler_vectorize compiler_vector_x86 compiler_opt_ssa \
compiler_abi compiler_machine_image \
compiler_machine_ir compiler_machine_verify \
compiler_machine_aggregate compiler_machine_fields compiler_machine_select compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
compiler_target compiler_learning compiler_learning_policy compiler_x86_bytes compiler_x86_64 compiler_x86_runtime compiler_encode compiler_aarch64 compiler_aarch64_runtime compiler_aarch64_elf compiler_armv7 compiler_armv7_runtime compiler_armv7_elf \
compiler_x86_win64 compiler_x86_host compiler_x86_image \
compiler_x86_archive \
compiler_arm_bytes \
compiler_machine_elf compiler_machine_pe \
compiler_machine_pipeline \
compiler_native_cache
$(BUILD_DIR)/obj/native-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(ENGINE_NAMES) $(BUILD_DIR)/.compiler-flags
@mkdir -p $(BUILD_DIR)/obj/native-assembly
@set -eu; objects=; for module in $(ASSEMBLY_NATIVE_MODULES); do \
source=$(ASSEMBLY_C)/$$module.c; \
object=$(BUILD_DIR)/obj/native-assembly/$$module.o; \
test -f "$$source"; \
$(CC) $(CFLAGS) $(FRAMEFLAGS) -fvisibility=hidden -I$(ASSEMBLY_C) \
-include $(ENGINE_NAMES) -c -o "$$object" "$$source"; \
objects="$$objects $$object"; \
done; $(CC) -r -nostdlib -o $@ $$objects
# zx2native's driver is Ziran (cmd/zx2native.zi); the generated copy uses the
# assembly set's own headers and links its unprefixed entry points.
ZX2NATIVE_C := $(BUILD_DIR)/zx2native-c
$(ZX2NATIVE_C)/.generated: cmd/zx2native.zi cmd/compiler_cli.zi cmd/compiler_ir.zi \
$(BUILD_DIR)/compiler-assembly/.generated $(BIN_DIR)/zi2c
$(BIN_DIR)/zi2c --entry zx2native:main --root cmd --module-path std -o $(ZX2NATIVE_C) cmd/zx2native.zi
touch $@
$(ZX2NATIVE_C)/%.c: $(ZX2NATIVE_C)/.generated
@test -f $@
$(BIN_DIR)/zx2native: $(ZX2NATIVE_C)/zx2native.c \
$(BUILD_DIR)/obj/assembly-core.o $(BUILD_DIR)/libziran.a | $(BIN_DIR)
$(NICE) $(CC) $(CFLAGS) -I$(ZX2NATIVE_C) -I$(BUILD_DIR)/compiler-assembly -o $@ \
$(ZX2NATIVE_C)/zx2native.c $(BUILD_DIR)/obj/assembly-core.o $(BUILD_DIR)/libziran.a $(RUNTIME_LIBS)
chmod 755 $@
+177 -32
View File
@@ -1,9 +1,162 @@
# Runtime and compiler benchmarks
Every benchmark runs through one entry point, from the repository root:
```sh
build/bin/ziran run --target=c bench/bench.zi -- list
build/bin/ziran run --target=c bench/bench.zi -- NAME [DRIVER ARGUMENTS]
build/bin/ziran run --target=c bench/bench.zi -- --local NAME --validate ...
```
`bench/bench.zi` names every driver, gives each the same environment (no
display or desktop-session variables, no `ZIRAN_PROFILE`, and `ZIRAN_LEARN=off`
so the learning corpus never records during a benchmark) and refuses to measure
a host benchmark anywhere but the physical host named by `ZIRAN_BENCH_HOST`,
`alpha` by default. `--local` is for measurement-free modes. A new driver is
registered in `bench/bench.zi`; `tests/bench_entry.sh` fails while one is not.
The per-benchmark commands below are the driver arguments; prefix each with
the entry point instead of running the driver directly.
Run benchmark builds and measurements on Alpha's physical host, as requested
by the owner on 2026-11-11, from the canonical Ziran repository there.
Reject virtualized execution. If Alpha is unavailable, wait rather than running the
benchmark on the current desktop. Record the host in every report and collect
both sides of a comparison on the same host; retained desktop results keep
their original provenance.
## Standard benchmarks and the host gate
`bench/standard/README.md` describes the standard language benchmarks
(`wasm-tier --standard`, `--standard-full` for the Benchmarks Game sizes) and
`standard-compile`. Anything the site's kernel or standard tables publish is
measured with `--host-gate`: each measured job runs on one logical CPU of the
quietest core, inherited by the child so no wrapper process adds time, with Go
at `GOMAXPROCS=1`. A poller on the other cores reads that CPU's
`scaling_cur_freq` every 10 ms and the sibling's busy time. A job is kept only
if its 10th to 90th percentile clock is within 3% of its median, the median
reaches 95% of the clock calibrated at start, and the hyperthread sibling is
busy at most 15% of the job; otherwise it runs again (up to eight attempts),
and rejected attempts stay in the receipt with their observations. The site
generators refuse receipts without it. Alpha's powersave/HWP clock otherwise
moves between 0.8 and 4.3 GHz and run time follows it
(`results/records-native-frequency-alpha-2026-11-16.json`). Compile-time builds
are not pinned.
Timed compiler/codec kernels are an explicit benchmark command, outside
`make check`: `build/bin/ziran run --target=c bench/bench.zi -- compiler-kernels` on Alpha.
Routine tests still validate benchmark statistics and command interfaces.
## JSON and UTF-8 workloads
On Alpha, run `build/bin/ziran run --target=c bench/bench.zi -- json-text --samples 11` to build and measure
the six Ziran programs in `bench/json_text/`. Each timed batch verifies its
result. The website retains generated artifacts, raw samples and compiler
diagnostics for unsupported targets in `site/generated/json-text/`.
The qualified Alpha snapshot is retained in `bench/results/json-text/alpha-matrix.json`.
Use `build/bin/ziran run --target=c bench/bench.zi -- --local json-text --check` to validate that snapshot without timing it.
## Portable ZX execution
```sh
build/bin/ziran run --target=c bench/bench.zi -- zx-execution
```
This Ziran script measures every unchanged portable bundle in the published
target matrix, verifies output and checksums, and records three repetitions of
nine warm batches. Symmetric 1.5×IQR filtering excludes anomalies from each median while retaining the raw samples and excluded indices. Source, library and bundle hashes detect drift. Retained
before/after measurements and the bottleneck analysis are in
[`results/zx-loops/README.md`](results/zx-loops/README.md).
Library workloads live upstream. The website's generic library harness accepts
Kryon's manifest without adding widget behavior to Ziran:
```sh
build/bin/ziran run --target=c bench/bench.zi -- library-targets \
--project ../../kryonlabs/kryon \
--manifest ../../kryonlabs/kryon/tests/widget_benchmarks.json --samples 9
```
Use the actual Kryon checkout path. The published archive contains all checked modules;
the source fixtures, generated C/Go/ZX and raw samples are downloadable.
These desktop cases measure public widget behavior and recorded paint commands,
excluding pixel rasterization and OS I/O.
## ZX assembly comparison receipts
`assembly_collect.zi` validates an exact campaign plan and, only after fresh
Alpha physical-host attestation, executes explicitly selected modes into the
strict raw schema consumed by `assembly_compare.zi`. Local plan validation is
measurement-free:
```sh
build/bin/ziran run --target=c bench/bench.zi -- --local assembly-collect --validate PLAN.json
```
Run `PLAN.json OUTPUT.json` instead only in the canonical checkout on Alpha's
physical host. The collector hashes the workload and complete declared runtime
closure before and after collection, enforces private cache/process boundaries,
checks every sample's stdout oracle, and atomically emits raw samples. It
supports explicit old VM, lowered portable, direct-AOT and control selectors.
The current default ZX runtime is not native-only proof, so
`old-c-tinycc-native` remains missing; no `new-native` ZX selector exists.
Direct AOT is never relabeled as that engine. The exact plan schema, phase
units, invocation, and remaining gates are in
[`../ASSEMBLY/performance-report.md`](../ASSEMBLY/performance-report.md).
## ZX runtime comparison 2 driver
`zx_compare.zi` measures the portable engine, cold native ZX, warm native ZX,
the `zx2native` AOT ELF control and the C control over identical workloads in
one receipt. Every trial verifies the oracle checksum, the reported backend
and, for native cohorts, the native evidence flag. The receipt records the
machine, virtualization and load averages before and after the run, hashes of
the driver, helper, control and library sources, the fixture artifact hashes,
and the copied M0 TinyCC summary:
```sh
build/bin/ziran run --target=c bench/bench.zi -- zx-compare --engine --native-cold --native-warm --aot \
--c-control --m0-receipts bench/results --samples 9
```
Every prepare step (fixture `zi2zx`, the `zx-host` helper build, the C control
build, the per-kind AOT source generation and builds) runs through the queue
and is recorded with its command line, exit code and wall time. The receipt is
written atomically after every trial, and the integrity block re-hashes every
input before the driver reports success. Without `--out`, the receipt is
`bench/results/zx-compare-<host>-<date>.json`. `--alpha` additionally enforces
the Alpha physical-host attestation gate for receipts that claim it.
## Fresh compiler rebuild
```sh
build/bin/ziran run --target=c bench/bench.zi -- compiler-build
```
This times `make -B -jN all` at the normal `build/` paths: all native Ziran
compiler tools and `libziran.a` rebuild, including generated compiler modules.
`--jobs N` selects concurrency; the default uses the queue's allocation when
available, otherwise the Makefile's usual half-CPU limit of 2–16 jobs.
Results, raw build output and sample history are retained under the tracked
`bench/results/compiler-build/` path. The wall time excludes queue waiting,
tests, installation and website builds. The report records CPU time, source
diff fingerprint, revision, dirty state and compilation count. Filesystem caches
remain warm; `make -B` forces all build targets to rebuild without deleting
other build outputs.
Add `--profile` to record every make shell recipe's monotonic start, finish
and elapsed time in `recipes.json`, with the 20 slowest in
`slowest-recipes.json`. Profiling keeps compiler optimization flags
unchanged, but adds process instrumentation; use ordinary runs for timing claims.
The temporary bootstrap seed defaults to `-O0`: it only emits the compiler
modules' C before the final tools are built with the normal `CFLAGS=-O2`.
`BOOTSTRAP_CFLAGS=-O2` restores the former seed settings for a comparison.
## Complete native builds
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/native_builds.py \
build/bin/ziran run --target=c bench/bench.zi -- native-builds \
--out build/benchmarks/native-builds
```
@@ -66,7 +219,7 @@ while retaining separate translation units and the existing worker limit.
For a complete build of the formatter application itself:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/formatter_builds.py \
build/bin/ziran run --target=c bench/bench.zi -- formatter-builds \
--before-bin-dir PATH/TO/PRESERVED/bin \
--out build/benchmarks/native-programs/formatter
```
@@ -91,14 +244,6 @@ Dependency metadata must contain at least 512 inputs per consumer. Fresh and
unchanged samples share warm machine caches and identical source inputs.
This compares two compiler versions, without a Go or C language baseline.
`bench/native_cache_names.py --before-ref REVISION
--out build/benchmarks/native-cache-names` isolates ordered-name collection at
16, 256, 2,048 and 8,192 names. It compiles the earlier cache source from Git
through compiler standard input and compares it with the current source.
Each sample inserts unique names, repeats duplicates, checks order and an
independent checksum, then frees the collection. Input preparation and process
startup are outside the internal timer. Report this container timing
separately from whole builds; process RSS also includes benchmark inputs.
Both harnesses save raw samples, tool/source hashes and actual CPU affinity.
For a before/after comparison that reaches late record types within the former
512-module limit, add `--groups 4 --read-last` to the header-graph benchmark.
@@ -155,7 +300,7 @@ Preserve `ziran`, `zi2zir`, `zi2c` and `zi2zx` together before changing the
compiler, then run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/body_eligibility.py \
build/bin/ziran run --target=c bench/bench.zi -- body-eligibility \
--before-bin-dir build/body-eligibility/before \
--out build/benchmarks/body-eligibility
```
@@ -183,7 +328,7 @@ Before changing the runtime, preserve `zi2zir`, `zi2zx` and `libziran.a` togethe
in a stable baseline directory. Then run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vm_execution.py \
build/bin/ziran run --target=c bench/bench.zi -- vm-execution \
--before-dir build/vm-execution/before --out build/benchmarks/vm-execution
```
@@ -212,7 +357,7 @@ hashes and expected results alongside the existing raw timing receipts.
To calibrate these same workloads against generated native C and Go:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vm_native.py \
build/bin/ziran run --target=c bench/bench.zi -- vm-native \
--vm-results build/benchmarks/vm-execution \
--out build/benchmarks/vm-native
```
@@ -237,10 +382,10 @@ the measured workloads; they do not establish whole-application C/Go parity.
## Android device execution
Prepare matched Ziran source/saved-IR C and Go programs, handwritten C/Go
controls, and a portable VM fixture for one Android ABI:
controls, and a portable engine fixture for one Android ABI:
```sh
python3 bench/android_execution.py prepare \
build/bin/ziran run --target=c bench/bench.zi -- android-execution prepare \
--out build/benchmarks/android-device/execution \
--ndk "$ANDROID_NDK_HOME" --abi armeabi-v7a
```
@@ -249,7 +394,7 @@ Run the measurement stage on the host that owns the device's ADB connection,
passing its exact serial:
```sh
python3 bench/android_execution.py run \
build/bin/ziran run --target=c bench/bench.zi -- android-execution run \
--out build/benchmarks/android-device/execution --serial DEVICE_SERIAL
```
@@ -270,13 +415,13 @@ not establish Go-like compilation speed on Android.
To compare the same seven portable workloads across saved VM libraries:
```sh
python3 bench/vm_android.py prepare \
build/bin/ziran run --target=c bench/bench.zi -- vm-android prepare \
--vm-results build/benchmarks/vm-execution \
--out build/benchmarks/vm-json/android \
--ndk "$ANDROID_NDK_HOME" --abi armeabi-v7a \
--library before PATH/TO/BASELINE/libziran.a \
--library after build/bundle-runtime/android-armeabi-v7a/libziran.a
python3 bench/vm_android.py run \
build/bin/ziran run --target=c bench/bench.zi -- vm-android run \
--out build/benchmarks/vm-json/android --serial DEVICE_SERIAL --cpu 0
```
@@ -297,7 +442,7 @@ establish gains on another.
## CPU-selected assembly
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/cpu_features.py \
build/bin/ziran run --target=c bench/bench.zi -- cpu-features \
--out build/benchmarks/cpu-features
```
@@ -330,7 +475,7 @@ and removing inactive outputs.
## Native Go assembly bridges
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/go_assembly.py \
build/bin/ziran run --target=c bench/bench.zi -- go-assembly \
--before-bin-dir build/go-assembly/before/bin \
--out build/go-assembly/benchmark
```
@@ -360,7 +505,7 @@ that its binaries and build outputs are inactive.
Host embedding has a separate capability-scaling benchmark:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/host_capabilities.py \
build/bin/ziran run --target=c bench/bench.zi -- host-capabilities \
--before-dir build/host-capabilities/before --out build/benchmarks/host-capabilities
```
@@ -378,7 +523,7 @@ For the public embedding API, compare one checked `BundleOpen` followed by
independent `BundleInstantiate`/run/close operations:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/bundle_instances.py \
build/bin/ziran run --target=c bench/bench.zi -- bundle-instances \
--before-dir build/bundle-runtime/before --out build/benchmarks/bundle-instances
```
@@ -397,7 +542,7 @@ sum oracles, verifies source/saved bundle identity, and runs the comparison
below. For example:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/enum_values.py \
build/bin/ziran run --target=c bench/bench.zi -- enum-values \
--before-dir build/compiler-check/before --out build/benchmarks/enum-values
```
@@ -419,7 +564,7 @@ For example, using fixtures generated by `compiler_scaling.py` with its default
16 fields:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vm_startup.py \
build/bin/ziran run --target=c bench/bench.zi -- vm-startup \
--before-dir build/vm-performance/before \
--out build/vm-performance/comparison \
--case modules128 \
@@ -456,7 +601,7 @@ receipts and remove inactive outputs before reusing the stable output path.
## Assembly and portable fallback
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/assembly.py \
build/bin/ziran run --target=c bench/bench.zi -- assembly \
--out build/benchmarks/assembly
```
@@ -481,7 +626,7 @@ For compiler scaling, module graphs, generic specialization, and source/saved
IR validation, run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/compiler_scaling.py \
build/bin/ziran run --target=c bench/bench.zi -- compiler-scaling \
--out build/benchmarks/compiler-scaling --sizes 8 32 128
```
@@ -527,7 +672,7 @@ From the repository root, build the current toolchain and run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY make -j4 all
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/smoke.py
build/bin/ziran run --target=c bench/bench.zi -- smoke
```
The script creates a new directory under `build/benchmarks/` with `metadata.json`,
@@ -542,7 +687,7 @@ portable `.zx`. The harness checks that generated source and bundles match,
and validates every runtime result against an independent modular-series
oracle before reporting times. It separately measures Ziran check/emission,
downstream native compilation, and whole-process execution. Runtime cases are
shuffled with a fixed seed between sample rounds. The portable VM runs only
shuffled with a fixed seed between sample rounds. The portable engine runs only
the small input because its instruction budget excludes the large one.
These numbers are a smoke baseline, not a language ranking. They include
@@ -557,7 +702,7 @@ real applications.
For a second workload that grows a `Vec(s32)` and then scans it, run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/vector_growth.py
build/bin/ziran run --target=c bench/bench.zi -- vector-growth
```
This measures source and saved-IR checks and emissions to C, Go, and
@@ -565,7 +710,7 @@ portable `.zx`, downstream native builds, and whole-process execution.
Handwritten C, C++, Go, Rust, Java, JavaScript, and Python versions provide
algorithm-level comparisons when their toolchains are installed; unavailable
tools are recorded explicitly. The checksum uses a closed-form arithmetic
oracle, and every runtime sample must match it. The portable VM runs the small
oracle, and every runtime sample must match it. The portable engine runs the small
input only. Raw commands, samples,
source and tool hashes, and caveats are written alongside the report. These
workloads remain a smoke and collection baseline; they do not cover text,
@@ -574,7 +719,7 @@ records, generics, larger module graphs, or real applications.
For a record-value and call workload over a fixed `[32]Point` table, run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/record_calls.py
build/bin/ziran run --target=c bench/bench.zi -- record-calls
```
Each round updates all records through a checked `Mix(Point, Point, s32, s32)`
@@ -594,7 +739,7 @@ binary hashes.
For a UTF-8 scanning workload over `aé中🙂`, run:
```sh
env -u DISPLAY -u WAYLAND_DISPLAY python3 bench/text_scan.py
build/bin/ziran run --target=c bench/bench.zi -- text-scan
```
The text has 10 bytes and 4 Unicode scalar values; every runtime sample must
+1 -1
View File
@@ -140,7 +140,7 @@ func benchKernel(n int64, seed uint64) uint64 {
'Go uses GOMAXPROCS=1 for the single-threaded kernel; no device settings are changed.',
'C/Go use the same SWAR population-count formula; Python bit_count supplies the independent oracle.'])
(out/'manifest.json').write_text(json.dumps(data,indent=2)+'\n')
print('Prepared Android native/Go controls and portable VM fixture')
print('Prepared Android native/Go controls and portable engine fixture')
def run(args):
+1 -1
View File
@@ -155,7 +155,7 @@ Answer :: () -> s64 { return cast(s64)(Kernel(SMALL, SEED) & 9223372036854775807
for form, root, entry in [('source', output, source), ('saved', output/'ir', output/'ir/swap.zir')]:
directory = output / form
repeated([binaries/'zi2c', '--root', root, '-o', directory, entry], 'compile', f'Ziran {form} emit C')
repeated([binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'swap:Answer', '-o', output/f'{form}.zx', entry],
repeated([binaries/'zi2zx', '--root', root, '--entry', 'swap:Answer', '-o', output/f'{form}.zx', entry],
'compile', f'Ziran {form} bundle')
host = directory/'host.c'
host.write_text('#include "swap.h"\n#include <stdio.h>\n#include <stdlib.h>\n'
+757
View File
@@ -0,0 +1,757 @@
#!/usr/bin/env ziran
// Collect strict assembly comparison receipts on Alpha's physical host.
// Validation is measurement-free; collection never substitutes the unavailable
// new-native ZX engine.
#import "benchmark_statistics"
#import "std/byte_text_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/float_text"
#import "std/json_document"
#import "std/math"
#import "std/number_text"
#import "std/process_run_linux"
#import "std/text_tools"
#import "std/timer_linux"
using Vectors :: #import "std/vec"
#scope_file
MAX_PLAN_BYTES :: 4194304;
MAX_JOBS :: 2048;
MAX_REQUIRED_CELLS :: 512;
MAX_REPEATS :: 4096;
MAX_TOTAL_SAMPLES :: 65536;
MAX_TEXT :: 1024;
RequiredCell :: struct {
case_id: string
phase: string
metric: string
unit: string
}
ClosureItem :: struct {
path: string
digest: string
}
CollectJob :: struct {
receipt_id: string
case_id: string
engine: string
selector: string
phase: string
metric: string
unit: string
command: Vec(string)
verification: Vec(string)
closure: Vec(ClosureItem)
workload: string
input_path: string
input_checksum: string
semantic_settings: string
correctness_expected: string
iterations: s64
repeats: s64
warmups: s64
timeout_ms: s64
cache_policy: string
cache_directory: string
environment: Vec(string)
artifact: string
rss_tool: string
}
CollectPlan :: struct {
campaign: string
physical_host: string
hostname: string
cpu: string
os: string
working_directory: string
collector_work: string
required: Vec(RequiredCell)
jobs: Vec(CollectJob)
}
Observation :: struct {
sample: float64
correctness: string
valid: bool
}
Cat :: (left: string, right: string) -> string {
parts: [2]string = .[left, right]
return TextDetach(TextJoin(parts[:], ""))
}
SafeText :: (value: string, limit: s64 = MAX_TEXT) -> bool {
if value.count == 0 || value.count > limit { return false }
for byte: value { if byte < 32 || byte == 127 { return false } }
return true
}
SafeName :: (value: string) -> bool {
if !SafeText(value, 256) { return false }
for byte: value {
if !(byte >= #char "a" && byte <= #char "z") &&
!(byte >= #char "A" && byte <= #char "Z") &&
!(byte >= #char "0" && byte <= #char "9") &&
byte != #char "-" && byte != #char "_" && byte != #char "." { return false }
}
return value != "." && value != ".."
}
CleanAbsolutePath :: (value: string) -> bool {
if value.count < 2 || value[0] != #char "/" || value[value.count - 1] == #char "/" ||
TextContains(value, "//") || TextContains(value, "/../") ||
TextContains(value, "/./") || TextHasSuffix(value, "/..") ||
TextHasSuffix(value, "/.") { return false }
return true
}
FieldInto :: (document: *JsonDocument, object: s32, name: string,
output: *string, limit: s64 = MAX_TEXT) -> bool {
node := JsonMember(document, object, name)
if JsonKindOf(document, node) != .String { return false }
value := TextDetach(JsonString(document, node))
if !SafeText(value, limit) { return false }
<<output = value
return true
}
IntegerField :: (document: *JsonDocument, object: s32, name: string,
minimum: s64, maximum: s64, output: *s64) -> bool {
value, valid := JsonInteger(document, JsonMember(document, object, name))
if !valid || value < minimum || value > maximum { return false }
<<output = value
return true
}
StringArray :: (document: *JsonDocument, object: s32, name: string,
output: *Vec(string), maximum: s32, empty_ok: bool = true) -> bool {
node := JsonMember(document, object, name)
if JsonKindOf(document, node) != .Array || JsonCount(document, node) > maximum ||
(!empty_ok && JsonCount(document, node) == 0) { return false }
for index: cast(s32)0..JsonCount(document, node) - 1 {
item := JsonElement(document, node, index)
if JsonKindOf(document, item) != .String { return false }
value := TextDetach(JsonString(document, item))
if !SafeText(value, 4095) { return false }
VecPush(<<output, value)
}
return true
}
ValidDigest :: (value: string) -> bool {
if value.count != 71 || value[0:7] != "sha256:" { return false }
for byte: value[7:] {
if !(byte >= #char "0" && byte <= #char "9") &&
!(byte >= #char "a" && byte <= #char "f") { return false }
}
return true
}
ParseRequired :: (document: *JsonDocument, node: s32, output: *RequiredCell) -> bool {
return JsonKindOf(document, node) == .Object && JsonCount(document, node) == 4 &&
FieldInto(document, node, "case", *output.case_id, 256) &&
FieldInto(document, node, "phase", *output.phase, 128) &&
FieldInto(document, node, "metric", *output.metric, 128) &&
FieldInto(document, node, "unit", *output.unit, 128)
}
ParseClosure :: (document: *JsonDocument, object: s32, output: *Vec(ClosureItem)) -> bool {
node := JsonMember(document, object, "runtime_closure")
if JsonKindOf(document, node) != .Array || JsonCount(document, node) == 0 ||
JsonCount(document, node) > 32 { return false }
for index: cast(s32)0..JsonCount(document, node) - 1 {
item_node := JsonElement(document, node, index)
item: ClosureItem
if JsonKindOf(document, item_node) != .Object || JsonCount(document, item_node) != 2 ||
!FieldInto(document, item_node, "path", *item.path, 4095) ||
!FieldInto(document, item_node, "sha256", *item.digest, 71) ||
!ValidDigest(item.digest) || !CleanAbsolutePath(item.path) { return false }
for other_index: cast(s64)0..(<<output).count - 1 {
if (<<output)[other_index].path == item.path { return false }
}
VecPush(<<output, item)
}
return true
}
Contains :: (values: []string, wanted: string) -> bool {
for value: values { if value == wanted { return true } }
return false
}
ContainsPair :: (values: []string, first: string, second: string) -> bool {
for index: cast(s64)0..values.count - 2 {
if values[index] == first && values[index + 1] == second { return true }
}
return false
}
EnvironmentValue :: (values: []string, name: string) -> string {
prefix := Cat(name, "=")
for value: values {
if TextHasPrefix(value, prefix) { return value[prefix.count:] }
}
return ""
}
ClosureContains :: (job: *CollectJob, path: string) -> bool {
for item: job.closure { if item.path == path { return true } }
return false
}
ValidCellShape :: (phase: string, metric: string, unit: string) -> bool {
if phase == "coldcompile" || phase == "coldstartup" || phase == "warmstartup" {
return metric == "duration" && unit == "ns"
}
if phase == "warmthroughput" { return metric == "throughput" && unit == "ops/s" }
if phase == "memory" { return metric == "memory" && unit == "KiB" }
if phase == "code-size" { return metric == "code-size" && unit == "bytes" }
if phase == "bundle-size" { return metric == "bundle-size" && unit == "bytes" }
return false
}
ValidSelector :: (job: *CollectJob) -> bool {
if job.engine == "new-native" {
print("assembly collector: new-native ZX is unavailable; keep that required cell missing\n")
return false
}
expected := ""
if job.engine == "old-portable-vm" { expected = "zx-vm" }
else if job.engine == "new-portable" { expected = "lowered-portable" }
else if job.engine == "old-c-tinycc-native" {
print("assembly collector: old C/TinyCC native has no native-only CLI proof; keep that cell missing\n")
return false
}
else if job.engine == "direct-aot" { expected = "direct-aot" }
else if job.engine == "control-c" || job.engine == "control-go" ||
job.engine == "control-wasm" { expected = job.engine }
else {
print("assembly collector: unsupported engine %\n", job.engine)
return false
}
if job.selector != expected {
print("assembly collector: engine % requires selector %, not %\n",
job.engine, expected, job.selector)
return false
}
if job.command.count == 0 || job.command[0].count == 0 ||
job.command[0][0] != #char "/" || !ClosureContains(job, job.command[0]) { return false }
if job.verification.count > 0 &&
(job.verification[0][0] != #char "/" || !ClosureContains(job, job.verification[0])) {
return false
}
if job.rss_tool != "-" &&
(job.rss_tool[0] != #char "/" || !ClosureContains(job, job.rss_tool)) { return false }
selection := job.command[:]
if (job.phase == "coldcompile" || job.phase == "code-size" ||
job.phase == "bundle-size") && job.verification.count > 0 {
selection = job.verification[:]
}
flags := selection[1:]
if job.selector == "zx-vm" {
return flags.count == 3 && flags[0] == "run" && flags[1] == "--vm" &&
flags[2] == job.input_path
}
if job.selector == "lowered-portable" {
expected_input := ifx job.phase == "coldcompile" ||
job.phase == "bundle-size" then job.artifact else job.input_path
return PathName(selection[0]) == "zi2zx" && flags.count == 2 && flags[0] == "run" &&
flags[1] == expected_input
}
if job.selector == "direct-aot" {
return job.artifact != "-" && selection[0] == job.artifact
}
if job.selector == "control-c" || job.selector == "control-go" {
return job.artifact != "-" && selection[0] == job.artifact
}
if job.selector == "control-wasm" {
return job.artifact != "-" && Contains(flags, job.artifact)
}
return true
}
PathInside :: (parent: string, child: string) -> bool {
if !CleanAbsolutePath(parent) || !CleanAbsolutePath(child) { return false }
prefix := Cat(parent, "/")
return child != parent && TextHasPrefix(child, prefix)
}
ValidateJob :: (plan: *CollectPlan, job: *CollectJob) -> bool {
if !SafeName(job.receipt_id) || !ValidCellShape(job.phase, job.metric, job.unit) ||
!ValidDigest(job.input_checksum) || !ValidDigest(job.correctness_expected) ||
!TextContains(job.semantic_settings, "process=fresh-child-per-sample") ||
job.command.count == 0 || job.repeats < 3 || job.repeats > MAX_REPEATS ||
job.iterations < 1 || job.timeout_ms < 1 ||
!CleanAbsolutePath(job.input_path) { return false }
if job.phase == "warmstartup" || job.phase == "warmthroughput" {
if job.warmups < 1 { return false }
} else if job.warmups != 0 { return false }
if job.phase == "warmthroughput" &&
(job.verification.count == 0 ||
!TextContains(job.semantic_settings, "timing=internal-kernel-ns")) { return false }
private_cache := job.cache_policy == "private-cold-each-sample" ||
job.cache_policy == "private-warm-across-samples"
if private_cache {
if job.cache_directory == "-" || !PathInside(plan.collector_work, job.cache_directory) {
return false
}
} else if job.cache_policy != "immutable-artifact-no-engine-cache" ||
job.cache_directory != "-" { return false }
if job.phase == "coldcompile" || job.phase == "code-size" ||
job.phase == "bundle-size" {
if job.verification.count == 0 || job.artifact == "-" ||
!PathInside(plan.collector_work, job.artifact) { return false }
}
if job.phase == "memory" && job.rss_tool == "-" { return false }
if job.phase != "memory" && job.rss_tool != "-" { return false }
return ValidSelector(job) && ToolchainIdentity(job) != ""
}
ParseJob :: (document: *JsonDocument, node: s32, output: *CollectJob) -> bool {
if JsonKindOf(document, node) != .Object || JsonCount(document, node) != 24 ||
!FieldInto(document, node, "receipt_id", *output.receipt_id, 256) ||
!FieldInto(document, node, "case", *output.case_id, 256) ||
!FieldInto(document, node, "engine", *output.engine, 128) ||
!FieldInto(document, node, "selector", *output.selector, 128) ||
!FieldInto(document, node, "phase", *output.phase, 128) ||
!FieldInto(document, node, "metric", *output.metric, 128) ||
!FieldInto(document, node, "unit", *output.unit, 128) ||
!StringArray(document, node, "command", *output.command, 64, false) ||
!StringArray(document, node, "verification", *output.verification, 64) ||
!ParseClosure(document, node, *output.closure) ||
!FieldInto(document, node, "workload", *output.workload) ||
!FieldInto(document, node, "input_path", *output.input_path, 4095) ||
!FieldInto(document, node, "input_checksum", *output.input_checksum, 71) ||
!FieldInto(document, node, "semantic_settings", *output.semantic_settings) ||
!FieldInto(document, node, "correctness_expected", *output.correctness_expected, 71) ||
!IntegerField(document, node, "iterations", 1, 9223372036854775807, *output.iterations) ||
!IntegerField(document, node, "repeats", 3, MAX_REPEATS, *output.repeats) ||
!IntegerField(document, node, "warmups", 0, MAX_REPEATS, *output.warmups) ||
!IntegerField(document, node, "timeout_ms", 1, 86400000, *output.timeout_ms) ||
!FieldInto(document, node, "cache_policy", *output.cache_policy, 128) ||
!FieldInto(document, node, "cache_directory", *output.cache_directory, 4095) ||
!StringArray(document, node, "environment", *output.environment, 64) ||
!FieldInto(document, node, "artifact", *output.artifact, 4095) ||
!FieldInto(document, node, "rss_tool", *output.rss_tool, 4095) { return false }
return true
}
ParsePlan :: (text: string, plan: *CollectPlan) -> bool {
document: JsonDocument
if !JsonRead(*document, text) || JsonKindOf(*document, document.root) != .Object ||
JsonCount(*document, document.root) != 10 { return false }
schema, schema_valid := JsonInteger(*document,
JsonMember(*document, document.root, "schema_version"))
if !schema_valid || schema != 1 ||
!FieldInto(*document, document.root, "campaign", *plan.campaign, 256) ||
!FieldInto(*document, document.root, "physical_host", *plan.physical_host, 256) ||
!FieldInto(*document, document.root, "hostname", *plan.hostname, 256) ||
!FieldInto(*document, document.root, "cpu", *plan.cpu) ||
!FieldInto(*document, document.root, "os", *plan.os) ||
!FieldInto(*document, document.root, "working_directory", *plan.working_directory, 4095) ||
!FieldInto(*document, document.root, "collector_work", *plan.collector_work, 4095) {
return false
}
required := JsonMember(*document, document.root, "required_cells")
jobs := JsonMember(*document, document.root, "jobs")
if JsonKindOf(*document, required) != .Array || JsonCount(*document, required) == 0 ||
JsonCount(*document, required) > MAX_REQUIRED_CELLS ||
JsonKindOf(*document, jobs) != .Array || JsonCount(*document, jobs) == 0 ||
JsonCount(*document, jobs) > MAX_JOBS { return false }
for index: cast(s32)0..JsonCount(*document, required) - 1 {
cell: RequiredCell
if !ParseRequired(*document, JsonElement(*document, required, index), *cell) {
return false
}
VecPush(plan.required, cell)
}
total_samples: s64
for index: cast(s32)0..JsonCount(*document, jobs) - 1 {
job: CollectJob
if !ParseJob(*document, JsonElement(*document, jobs, index), *job) { return false }
total_samples += job.repeats
if total_samples > MAX_TOTAL_SAMPLES { return false }
VecPush(plan.jobs, job)
}
return true
}
ValidatePlan :: (plan: *CollectPlan) -> bool {
if plan.physical_host != "alpha" || !TextHasPrefix(plan.hostname, "alpha") ||
!CleanAbsolutePath(plan.working_directory) ||
!CleanAbsolutePath(plan.collector_work) ||
!PathInside(plan.working_directory, plan.collector_work) { return false }
for index: cast(s64)0..plan.required.count - 1 {
if !ValidCellShape(plan.required[index].phase, plan.required[index].metric,
plan.required[index].unit) { return false }
for other: index + 1..plan.required.count - 1 {
if plan.required[index].case_id == plan.required[other].case_id &&
plan.required[index].phase == plan.required[other].phase &&
plan.required[index].metric == plan.required[other].metric &&
plan.required[index].unit == plan.required[other].unit { return false }
}
}
for index: cast(s64)0..plan.jobs.count - 1 {
if !ValidateJob(plan, *plan.jobs[index]) { return false }
for other: index + 1..plan.jobs.count - 1 {
if plan.jobs[index].receipt_id == plan.jobs[other].receipt_id { return false }
if plan.jobs[index].case_id == plan.jobs[other].case_id &&
plan.jobs[index].phase == plan.jobs[other].phase &&
plan.jobs[index].metric == plan.jobs[other].metric &&
plan.jobs[index].engine == plan.jobs[other].engine { return false }
if plan.jobs[index].case_id == plan.jobs[other].case_id &&
plan.jobs[index].phase == plan.jobs[other].phase &&
plan.jobs[index].metric == plan.jobs[other].metric &&
(plan.jobs[index].workload != plan.jobs[other].workload ||
plan.jobs[index].input_checksum != plan.jobs[other].input_checksum ||
plan.jobs[index].iterations != plan.jobs[other].iterations ||
plan.jobs[index].unit != plan.jobs[other].unit ||
plan.jobs[index].semantic_settings != plan.jobs[other].semantic_settings ||
plan.jobs[index].correctness_expected != plan.jobs[other].correctness_expected) {
return false
}
}
}
return true
}
#scope_export
ValidatePlanText :: (text: string) -> bool {
plan: CollectPlan
return ParsePlan(text, *plan) && ValidatePlan(*plan)
}
#scope_file
Capture :: (arguments: []string) -> (text: string, code: s32) {
options: ProcessOptions = .{.arguments = arguments, .capture_output = true}
run: ProcessRun
if !RunProcess(options, *run) { return "", 127 }
return TextDetach(BuilderFinish(run.output)), run.code
}
HashFile :: (path: string) -> string {
arguments := string.["sha256sum", "--", path]
output, code := Capture(arguments[:])
if code != 0 || output.count < 64 { return "" }
result := Cat("sha256:", output[0:64])
return ifx ValidDigest(result) then result else ""
}
CpuIdentity :: () -> string {
arguments := string.["/usr/bin/lscpu"]
output, code := Capture(arguments[:])
if code != 0 { return "" }
lines := TextLines(output)
for line: lines {
if TextHasPrefix(line, "Model name:") {
return TextDetach(TextCopy(TextTrim(line[11:])))
}
}
return ""
}
VerifyPhysicalHost :: (plan: *CollectPlan) -> bool {
host_command := string.["/usr/bin/hostname"]
os_command := string.["/usr/bin/uname", "-srmo"]
virt_command := string.["/usr/bin/systemd-detect-virt"]
hostname, host_code := Capture(host_command[:])
os, os_code := Capture(os_command[:])
virtualization, virt_code := Capture(virt_command[:])
actual_host := TextTrim(hostname)
actual_os := TextTrim(os)
actual_virt := TextTrim(virtualization)
actual_cpu := CpuIdentity()
if host_code != 0 || os_code != 0 || virt_code != 1 || actual_virt != "none" ||
actual_host != plan.hostname || actual_cpu != plan.cpu || actual_os != plan.os {
print("assembly collector: Alpha physical-host attestation failed; no commands were run\n")
return false
}
return true
}
VerifyInputs :: (job: *CollectJob) -> bool {
if HashFile(job.input_path) != job.input_checksum { return false }
for item: job.closure {
if HashFile(item.path) != item.digest { return false }
}
return true
}
ResetPrivateCache :: (plan: *CollectPlan, job: *CollectJob) -> bool {
if job.cache_directory == "-" { return true }
if !PathInside(plan.collector_work, job.cache_directory) { return false }
if PathStatus(job.cache_directory, false).kind != .Missing &&
!RemoveTree(job.cache_directory) { return false }
return CreateDirectories(job.cache_directory)
}
CommandOutputPath :: (plan: *CollectPlan, job: *CollectJob, label: string) -> string {
prefix := Cat(plan.collector_work, Cat("/", Cat(job.receipt_id, Cat("-", label))))
return Cat(prefix, ".stdout")
}
RunCommand :: (plan: *CollectPlan, job: *CollectJob, arguments: []string,
label: string, measured: bool) -> (elapsed: s64, output_digest: string, valid: bool) {
stdout_path := CommandOutputPath(plan, job, label)
prefix := stdout_path[0:stdout_path.count - 7]
stderr_path := Cat(prefix, ".stderr")
environment: Vec(string)
for value: job.environment { VecPush(environment, value) }
removals := string.["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
"DBUS_SESSION_BUS_ADDRESS", "GDK_DISPLAY"]
for value: removals { VecPush(environment, value) }
VecPush(environment, "HARMONY_DESKTOP_RECOVERY=0")
options: ProcessOptions = .{.arguments = arguments, .directory = plan.working_directory,
.environment = environment[:], .output_path = stdout_path,
.error_path = stderr_path, .new_session = true}
run: ProcessRun
started := MonotonicNanoseconds()
if started < 0 || !StartProcess(options, *run) { return 0, "", false }
deadline := MonotonicMilliseconds() + job.timeout_ms
while !PollProcess(*run) {
if MonotonicMilliseconds() >= deadline {
unused SignalProcess(*run, 15, true)
unused SleepMilliseconds(100)
if !PollProcess(*run) { unused SignalProcess(*run, 9, true) }
unused WaitProcess(*run)
print("assembly collector: command timed out for %\n", job.receipt_id)
return 0, "", false
}
unused SleepMilliseconds(2)
}
finished := MonotonicNanoseconds()
if run.code != 0 || finished <= started { return 0, "", false }
digest := HashFile(stdout_path)
return ifx measured then finished - started else cast(s64)1, digest, digest != ""
}
RunVerification :: (plan: *CollectPlan, job: *CollectJob, fallback: string,
label: string) -> (identity: string, valid: bool) {
if job.verification.count == 0 { return fallback, fallback == job.correctness_expected }
unused_elapsed, identity, ok := RunCommand(plan, job, job.verification[:], label, false)
return identity, ok && identity == job.correctness_expected
}
MeasureOnce :: (plan: *CollectPlan, job: *CollectJob, index: s64,
warmup: bool = false) -> Observation {
result: Observation
suffix_buffer: [32]u8
suffix := TextDetach(TextCopy(FormatInteger(index, suffix_buffer[:])))
label := Cat(ifx warmup then "warmup-" else "sample-", suffix)
if !warmup && (job.phase == "coldcompile" || job.phase == "code-size" ||
job.phase == "bundle-size") {
info := PathStatus(job.artifact, false)
if info.kind != .Missing && (info.kind != .File || !RemoveFile(job.artifact)) {
return result
}
}
command: Vec(string)
rss_path := ""
if job.phase == "memory" {
rss_path = Cat(plan.collector_work, Cat("/", Cat(job.receipt_id, Cat("-rss-", suffix))))
VecPush(command, job.rss_tool)
VecPush(command, "-f")
VecPush(command, "%M")
VecPush(command, "-o")
VecPush(command, rss_path)
VecPush(command, "--")
for value: job.command { VecPush(command, value) }
} else {
for value: job.command { VecPush(command, value) }
}
elapsed, command_identity, ok := RunCommand(plan, job, command[:], label, true)
if !ok { return result }
identity, correct := RunVerification(plan, job, command_identity, Cat(label, "-verify"))
if !correct { return result }
result.correctness = identity
if warmup { result.sample = 1.0; result.valid = true; return result }
if job.metric == "duration" { result.sample = cast(float64)elapsed }
else if job.metric == "throughput" {
text, readable := ReadEntireFile(CommandOutputPath(plan, job, label))
timing := ifx readable then TextTrim(text) else ""
kernel_ns, count := IntegerPrefix(timing)
if count != timing.count || kernel_ns <= 0 { return .{} }
result.sample = cast(float64)job.iterations * 1000000000.0 /
cast(float64)kernel_ns
} else if job.metric == "memory" {
text, readable := ReadEntireFile(rss_path)
value, count := IntegerPrefix(ifx readable then TextTrim(text) else "")
if count == 0 || value <= 0 { return .{} }
result.sample = cast(float64)value
} else {
info := PathStatus(job.artifact)
if info.kind != .File || info.size <= 0 { return .{} }
result.sample = cast(float64)info.size
}
result.valid = result.sample > 0.0 && Finite64(result.sample)
return result
}
ToolchainIdentity :: (job: *CollectJob) -> string {
output: Vec(u8)
unused BuilderAppend(output, "selector=")
unused BuilderAppend(output, job.selector)
unused BuilderAppend(output, ";command=")
unused BuilderAppend(output, job.command[0])
unused BuilderAppend(output, ";cache=")
unused BuilderAppend(output, job.cache_policy)
unused BuilderAppend(output, "@")
unused BuilderAppend(output, job.cache_directory)
unused BuilderAppend(output, ";process=fresh-child-per-sample")
if job.verification.count > 0 {
unused BuilderAppend(output, ";verify=")
for index: cast(s64)0..job.verification.count - 1 {
if index > 0 { unused BuilderAppend(output, ",") }
unused BuilderAppend(output, job.verification[index])
}
}
if job.environment.count > 0 {
unused BuilderAppend(output, ";environment=")
for index: cast(s64)0..job.environment.count - 1 {
if index > 0 { unused BuilderAppend(output, ",") }
unused BuilderAppend(output, job.environment[index])
}
}
unused BuilderAppend(output,
";collector-environment=DISPLAY-,WAYLAND_DISPLAY-,XAUTHORITY-,DBUS_SESSION_BUS_ADDRESS-,GDK_DISPLAY-,HARMONY_DESKTOP_RECOVERY=0")
unused BuilderAppend(output, ";closure=")
for index: cast(s64)0..job.closure.count - 1 {
if index > 0 { unused BuilderAppend(output, ",") }
unused BuilderAppend(output, job.closure[index].path)
unused BuilderAppend(output, "@")
unused BuilderAppend(output, job.closure[index].digest)
}
result := TextDetach(BuilderFinish(output))
return ifx SafeText(result) then result else ""
}
PutText :: (document: *JsonDocument, object: s32, name: string, value: string) {
JsonSet(document, object, name, JsonNewStringCopy(document, value))
}
AppendRequired :: (document: *JsonDocument, array: s32, cell: *RequiredCell) {
object := JsonNewObject(document)
PutText(document, object, "case", cell.case_id)
PutText(document, object, "phase", cell.phase)
PutText(document, object, "metric", cell.metric)
PutText(document, object, "unit", cell.unit)
JsonAppend(document, array, object)
}
AppendReceipt :: (document: *JsonDocument, array: s32, plan: *CollectPlan,
job: *CollectJob, samples: []float64, correctness: string) -> bool {
toolchain := ToolchainIdentity(job)
if toolchain == "" { return false }
object := JsonNewObject(document)
PutText(document, object, "receipt_id", job.receipt_id)
PutText(document, object, "case", job.case_id)
PutText(document, object, "physical_host", plan.physical_host)
PutText(document, object, "host_mode", "physical")
PutText(document, object, "vm", "none")
PutText(document, object, "cpu", plan.cpu)
PutText(document, object, "os", plan.os)
PutText(document, object, "toolchain", toolchain)
flags := JsonNewArray(document)
for index: cast(s64)1..job.command.count - 1 {
JsonAppend(document, flags, JsonNewStringCopy(document, job.command[index]))
}
JsonSet(document, object, "flags", flags)
PutText(document, object, "workload", job.workload)
PutText(document, object, "input_checksum", job.input_checksum)
PutText(document, object, "engine", job.engine)
PutText(document, object, "phase", job.phase)
PutText(document, object, "metric", job.metric)
PutText(document, object, "unit", job.unit)
PutText(document, object, "semantic_settings", job.semantic_settings)
PutText(document, object, "correctness_expected", job.correctness_expected)
PutText(document, object, "correctness_actual", correctness)
JsonSet(document, object, "iterations", JsonNewInteger(document, job.iterations))
JsonSet(document, object, "repeats", JsonNewInteger(document, job.repeats))
values := JsonNewArray(document)
for sample: samples {
JsonAppend(document, values, JsonNewNumber(document, Float64Repr(sample)))
}
JsonSet(document, object, "samples", values)
JsonAppend(document, array, object)
return true
}
#scope_export
ProcessCollection :: (input: string, output: string) -> bool {
if input == output { return false }
query := PathQuery(input)
if !query.valid || query.info.kind != .File || query.info.size < 2 ||
query.info.size > MAX_PLAN_BYTES { return false }
text, readable := ReadEntireFile(input)
if !readable || text.count != query.info.size { return false }
plan: CollectPlan
if !ParsePlan(text, *plan) || !ValidatePlan(*plan) {
print("assembly collector: invalid collection plan\n")
return false
}
// This guard precedes filesystem verification, cache reset, and every job.
if !VerifyPhysicalHost(*plan) { return false }
if !CreateDirectories(plan.collector_work) { return false }
document: JsonDocument
root := JsonNewObject(*document)
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
PutText(*document, root, "campaign", plan.campaign)
required := JsonNewArray(*document)
for * cell: plan.required { AppendRequired(*document, required, cell) }
JsonSet(*document, root, "required_cells", required)
receipts := JsonNewArray(*document)
for * job: plan.jobs {
if !VerifyInputs(job) { return false }
if job.cache_policy == "private-warm-across-samples" &&
!ResetPrivateCache(*plan, job) { return false }
for warmup: cast(s64)0..job.warmups - 1 {
observation := MeasureOnce(*plan, job, warmup, true)
if !observation.valid { return false }
}
samples: Vec(float64)
correctness := ""
for index: cast(s64)0..job.repeats - 1 {
if job.cache_policy == "private-cold-each-sample" &&
!ResetPrivateCache(*plan, job) { return false }
observation := MeasureOnce(*plan, job, index)
if !observation.valid || observation.correctness != job.correctness_expected {
return false
}
correctness = observation.correctness
VecPush(samples, observation.sample)
}
statistics := BenchmarkAnalyze(samples[:])
if !statistics.valid || !VerifyInputs(job) ||
!AppendReceipt(*document, receipts, *plan, job,
samples[:], correctness) { return false }
}
JsonSet(*document, root, "receipts", receipts)
result := JsonWrite(*document, root, JsonPythonStyle(2))
return CreateDirectories(PathParent(output)) && ReplaceFile(output, result)
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc == 3 && TextFromCString(argv[1]) == "--validate" {
input := TextDetach(TextCopy(TextFromCString(argv[2])))
query := PathQuery(input)
text, readable := ReadEntireFile(input)
if !query.valid || query.info.kind != .File || query.info.size < 2 ||
query.info.size > MAX_PLAN_BYTES || !readable || text.count != query.info.size ||
!ValidatePlanText(text) { return 1 }
print("assembly collector: plan is valid; no commands were run\n")
return 0
}
if argc != 3 {
print("usage: assembly_collect.zi [--validate] PLAN.json [OUTPUT.json]\n")
return 2
}
input := TextDetach(TextCopy(TextFromCString(argv[1])))
output := TextDetach(TextCopy(TextFromCString(argv[2])))
return ifx ProcessCollection(input, output) then 0 else 1
}
+590
View File
@@ -0,0 +1,590 @@
#!/usr/bin/env ziran
#import "benchmark_statistics"
#import "std/byte_text_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/float_text"
#import "std/json_document"
#import "std/math"
#import "std/number_text"
#import "std/text_tools"
using Vectors :: #import "std/vec"
#scope_file
MAX_INPUT_BYTES :: 4194304;
MAX_REQUIRED_CELLS :: 512;
MAX_RECEIPTS :: 2048;
MAX_SAMPLES_PER_RECEIPT :: 4096;
MAX_TOTAL_SAMPLES :: 65536;
MAX_TEXT :: 1024;
core_engines: [5]string = .[
"old-portable-vm",
"new-portable",
"old-c-tinycc-native",
"new-native",
"direct-aot",
];
RequiredCell :: struct {
case_id: string
phase: string
metric: string
unit: string
}
Receipt :: struct {
receipt_id: string
case_id: string
physical_host: string
host_mode: string
vm: string
cpu: string
os: string
toolchain: string
flags: Vec(string)
workload: string
input_checksum: string
engine: string
phase: string
metric: string
unit: string
semantic_settings: string
correctness_expected: string
correctness_actual: string
iterations: s64
repeats: s64
samples: Vec(float64)
statistics: BenchmarkSampleStatistics
}
Markdown :: struct {
bytes: Vec(u8)
valid: bool
}
Cat :: (left: string, right: string) -> string {
parts: [2]string = .[left, right]
return TextDetach(TextJoin(parts[:], ""))
}
Put :: (output: *Markdown, text: string) {
if output.valid { output.valid = BuilderAppend(output.bytes, text) }
}
SafeText :: (text: string, limit: s64 = MAX_TEXT) -> bool {
if text.count == 0 || text.count > limit { return false }
for byte: text { if byte < 32 || byte == 127 { return false } }
return true
}
FieldInto :: (document: *JsonDocument, object: s32, name: string,
output: *string, limit: s64 = MAX_TEXT) -> bool {
node := JsonMember(document, object, name)
if JsonKindOf(document, node) != .String { return false }
value := TextDetach(JsonString(document, node))
if !SafeText(value, limit) { return false }
<<output = value
return true
}
IntegerField :: (document: *JsonDocument, object: s32, name: string,
minimum: s64, maximum: s64, output: *s64) -> bool {
value, valid := JsonInteger(document, JsonMember(document, object, name))
if !valid || value < minimum || value > maximum { return false }
<<output = value
return true
}
ParseRequiredCell :: (document: *JsonDocument, node: s32,
result: *RequiredCell) -> bool {
return JsonKindOf(document, node) == .Object && JsonCount(document, node) == 4 &&
FieldInto(document, node, "case", *result.case_id, 256) &&
FieldInto(document, node, "phase", *result.phase, 128) &&
FieldInto(document, node, "metric", *result.metric, 128) &&
FieldInto(document, node, "unit", *result.unit, 128)
}
ParseReceipt :: (document: *JsonDocument, node: s32, result: *Receipt) -> bool {
if JsonKindOf(document, node) != .Object || JsonCount(document, node) != 21 {
return false
}
if !FieldInto(document, node, "receipt_id", *result.receipt_id, 256) ||
!FieldInto(document, node, "case", *result.case_id, 256) ||
!FieldInto(document, node, "physical_host", *result.physical_host, 256) ||
!FieldInto(document, node, "host_mode", *result.host_mode, 64) ||
!FieldInto(document, node, "vm", *result.vm, 256) ||
!FieldInto(document, node, "cpu", *result.cpu) ||
!FieldInto(document, node, "os", *result.os) ||
!FieldInto(document, node, "toolchain", *result.toolchain) ||
!FieldInto(document, node, "workload", *result.workload) ||
!FieldInto(document, node, "input_checksum", *result.input_checksum, 256) ||
!FieldInto(document, node, "engine", *result.engine, 128) ||
!FieldInto(document, node, "phase", *result.phase, 128) ||
!FieldInto(document, node, "metric", *result.metric, 128) ||
!FieldInto(document, node, "unit", *result.unit, 128) ||
!FieldInto(document, node, "semantic_settings", *result.semantic_settings) ||
!FieldInto(document, node, "correctness_expected", *result.correctness_expected) ||
!FieldInto(document, node, "correctness_actual", *result.correctness_actual) ||
!IntegerField(document, node, "iterations", 1, 9223372036854775807, *result.iterations) ||
!IntegerField(document, node, "repeats", 3, MAX_SAMPLES_PER_RECEIPT, *result.repeats) {
return false
}
flags := JsonMember(document, node, "flags")
if JsonKindOf(document, flags) != .Array || JsonCount(document, flags) > 64 {
return false
}
for index: cast(s32)0..JsonCount(document, flags) - 1 {
flag_node := JsonElement(document, flags, index)
if JsonKindOf(document, flag_node) != .String { return false }
flag := TextDetach(JsonString(document, flag_node))
if !SafeText(flag, 256) { return false }
VecPush(result.flags, flag)
}
samples := JsonMember(document, node, "samples")
if JsonKindOf(document, samples) != .Array ||
JsonCount(document, samples) != result.repeats { return false }
for index: cast(s32)0..JsonCount(document, samples) - 1 {
sample_node := JsonElement(document, samples, index)
if JsonKindOf(document, sample_node) != .Number { return false }
value, valid := ParseFloat64(JsonNumberText(document, sample_node))
if !valid || value <= 0.0 || !Finite64(value) { return false }
VecPush(result.samples, value)
}
statistics := BenchmarkAnalyze(result.samples[:])
result.statistics.valid = statistics.valid
result.statistics.lower = statistics.lower
result.statistics.upper = statistics.upper
result.statistics.median = statistics.median
VecSwap(result.statistics.excluded, statistics.excluded)
VecSwap(result.statistics.included, statistics.included)
return result.statistics.valid
}
SameCell :: (left: *Receipt, right: *Receipt) -> bool {
return left.case_id == right.case_id && left.phase == right.phase &&
left.metric == right.metric
}
CompatibilityProblem :: (left: *Receipt, right: *Receipt) -> string {
if left.physical_host != right.physical_host { return "physical_host changed" }
if left.host_mode != right.host_mode { return "host_mode changed" }
if left.vm != right.vm { return "VM identity changed" }
if left.cpu != right.cpu { return "CPU identity changed" }
if left.os != right.os { return "OS identity changed" }
if left.workload != right.workload { return "workload changed" }
if left.input_checksum != right.input_checksum { return "workload input checksum changed" }
if left.iterations != right.iterations { return "iteration count changed" }
if left.unit != right.unit { return "measurement unit changed" }
if left.semantic_settings != right.semantic_settings { return "semantic settings changed" }
if left.correctness_expected != right.correctness_expected {
return "expected correctness identity changed"
}
return ""
}
ValidateCampaign :: (required: []RequiredCell, receipts: []Receipt) -> bool {
for index: cast(s64)0..required.count - 1 {
for other: index + 1..required.count - 1 {
if required[index].case_id == required[other].case_id &&
required[index].phase == required[other].phase &&
required[index].metric == required[other].metric &&
required[index].unit == required[other].unit {
print("assembly comparison: duplicate required cell %/%/%\n",
required[index].case_id, required[index].phase, required[index].metric)
return false
}
}
}
if receipts.count == 0 {
print("assembly comparison: receipts must not be empty\n")
return false
}
first := *receipts[0]
for index: cast(s64)0..receipts.count - 1 {
receipt := *receipts[index]
if receipt.host_mode != "physical" || receipt.vm != "none" {
print("assembly comparison: receipt % is not a direct physical-host measurement\n",
receipt.receipt_id)
return false
}
if receipt.correctness_expected != receipt.correctness_actual {
print("assembly comparison: receipt % failed its correctness identity\n",
receipt.receipt_id)
return false
}
global_problem := CompatibilityProblem(first, receipt)
if global_problem == "physical_host changed" || global_problem == "host_mode changed" ||
global_problem == "VM identity changed" || global_problem == "CPU identity changed" ||
global_problem == "OS identity changed" {
print("assembly comparison: incompatible campaign receipt %: %\n",
receipt.receipt_id, global_problem)
return false
}
for other: index + 1..receipts.count - 1 {
candidate := *receipts[other]
if receipt.receipt_id == candidate.receipt_id {
print("assembly comparison: duplicate receipt_id %\n", receipt.receipt_id)
return false
}
if SameCell(receipt, candidate) && receipt.engine == candidate.engine {
print("assembly comparison: duplicate engine cell %/%/%/%\n",
receipt.case_id, receipt.phase, receipt.metric, receipt.engine)
return false
}
if SameCell(receipt, candidate) {
problem := CompatibilityProblem(receipt, candidate)
if problem != "" {
print("assembly comparison: incompatible receipts % and %: %\n",
receipt.receipt_id, candidate.receipt_id, problem)
return false
}
}
}
}
return true
}
MetricDirection :: (metric: string) -> s32 {
if metric == "throughput" { return 1 }
if metric == "duration" || metric == "memory" ||
metric == "code-size" || metric == "bundle-size" { return -1 }
return 0
}
FindReceipt :: (receipts: []Receipt, cell: *RequiredCell, engine: string) -> s64 {
for index: cast(s64)0..receipts.count - 1 {
receipt := *receipts[index]
if receipt.case_id == cell.case_id && receipt.phase == cell.phase &&
receipt.metric == cell.metric && receipt.unit == cell.unit &&
receipt.engine == engine { return index }
}
return -1
}
ContainsCell :: (cells: []RequiredCell, candidate: *RequiredCell) -> bool {
for cell: cells {
if cell.case_id == candidate.case_id && cell.phase == candidate.phase &&
cell.metric == candidate.metric && cell.unit == candidate.unit { return true }
}
return false
}
AllCells :: (required: []RequiredCell, receipts: []Receipt) -> Vec(RequiredCell) {
cells: Vec(RequiredCell)
for cell: required { VecPush(cells, cell) }
for index: cast(s64)0..receipts.count - 1 {
receipt := *receipts[index]
cell: RequiredCell = .{.case_id = receipt.case_id, .phase = receipt.phase,
.metric = receipt.metric, .unit = receipt.unit}
if !ContainsCell(cells[:], *cell) { VecPush(cells, cell) }
}
return cells
}
EscapeMarkdown :: (value: string) -> string {
escaped: Vec(u8)
for byte: value {
entity := ""
if byte == #char "&" { entity = "&amp;" }
else if byte == #char "<" { entity = "&lt;" }
else if byte == #char ">" { entity = "&gt;" }
else if byte == #char "|" { entity = "&#124;" }
else if byte == #char "`" { entity = "&#96;" }
else if byte == #char "\\" { entity = "&#92;" }
else if byte == #char "*" { entity = "&#42;" }
else if byte == #char "_" { entity = "&#95;" }
else if byte == #char "[" { entity = "&#91;" }
else if byte == #char "]" { entity = "&#93;" }
else if byte == #char "#" { entity = "&#35;" }
if entity != "" {
if !BuilderAppend(escaped, entity) { return "" }
} else if !VecPush(escaped, byte) { return "" }
}
return TextDetach(BuilderFinish(escaped))
}
Decimal :: (value: float64, places: s32) -> string {
buffer: [64]u8
return TextDetach(TextCopy(FormatDecimal(value, places, buffer[:])))
}
MedianText :: (receipt: *Receipt) -> string {
return Cat(TextDetach(Float64Repr(receipt.statistics.median)),
Cat(" ", EscapeMarkdown(receipt.unit)))
}
IndicesText :: (indices: []s64) -> string {
output: Vec(u8)
unused BuilderAppend(output, "[")
for index: cast(s64)0..indices.count - 1 {
if index > 0 { unused BuilderAppend(output, ", ") }
buffer: [32]u8
unused BuilderAppend(output, FormatInteger(indices[index], buffer[:]))
}
unused BuilderAppend(output, "]")
return TextDetach(BuilderFinish(output))
}
SamplesText :: (samples: []float64) -> string {
output: Vec(u8)
unused BuilderAppend(output, "[")
for index: cast(s64)0..samples.count - 1 {
if index > 0 { unused BuilderAppend(output, ", ") }
unused BuilderAppend(output, Float64Repr(samples[index]))
}
unused BuilderAppend(output, "]")
return TextDetach(BuilderFinish(output))
}
CellValue :: (receipts: []Receipt, cell: *RequiredCell, engine: string) -> string {
index := FindReceipt(receipts, cell, engine)
if index < 0 { return "missing" }
return MedianText(*receipts[index])
}
CountMissing :: (required: []RequiredCell, receipts: []Receipt) -> s64 {
count: s64
for cell: required {
for engine: core_engines {
if FindReceipt(receipts, *cell, engine) < 0 { count += 1 }
}
}
return count
}
PairRow :: (output: *Markdown, receipts: []Receipt, cell: *RequiredCell,
baseline: string, candidate: string, optional: bool = false) {
base := FindReceipt(receipts, cell, baseline)
next := FindReceipt(receipts, cell, candidate)
if optional && next < 0 { return }
Put(output, "| "); Put(output, EscapeMarkdown(cell.case_id)); Put(output, " | ")
Put(output, EscapeMarkdown(cell.phase)); Put(output, " / ")
Put(output, EscapeMarkdown(cell.metric)); Put(output, " | ")
Put(output, baseline); Put(output, " → "); Put(output, candidate); Put(output, " | ")
Put(output, ifx base >= 0 then MedianText(*receipts[base]) else "missing")
Put(output, " | ")
Put(output, ifx next >= 0 then MedianText(*receipts[next]) else "missing")
Put(output, " | ")
if base < 0 || next < 0 {
Put(output, "not compared: missing receipt")
} else {
direction := MetricDirection(cell.metric)
if direction == 0 {
Put(output, "noncomparable: unknown metric direction")
} else {
baseline_value := receipts[base].statistics.median
candidate_value := receipts[next].statistics.median
ratio := ifx direction > 0 then candidate_value / baseline_value else baseline_value / candidate_value
metric_ratio := candidate_value / baseline_value
metric_change := (metric_ratio - 1.0) * 100.0
if ratio <= 0.0 || metric_ratio <= 0.0 || !Finite64(ratio) ||
!Finite64(metric_ratio) || !Finite64(metric_change) {
Put(output, "noncomparable: derived ratio outside finite range")
} else {
Put(output, Decimal(ratio, 3)); Put(output, "x favorable factor; ")
if ratio > 1.0 { Put(output, "improvement") }
else if ratio < 1.0 { Put(output, "regression") }
else { Put(output, "unchanged") }
Put(output, "; candidate metric change ")
if metric_change > 0.0 { Put(output, "+") }
Put(output, Decimal(metric_change, 2)); Put(output, "%")
}
}
}
Put(output, " |\n")
}
BuildReport :: (campaign: string, required: []RequiredCell,
receipts: []Receipt) -> (text: string, valid: bool) {
output: Markdown
output.valid = true
missing := CountMissing(required, receipts)
Put(*output, "# ZX Assembly Performance Comparison\n\n")
Put(*output, "Campaign: `"); Put(*output, EscapeMarkdown(campaign)); Put(*output, "`\n\n")
Put(*output, "Status: ")
if missing == 0 { Put(*output, "complete required comparison matrix") }
else {
Put(*output, "incomplete — ")
buffer: [32]u8
Put(*output, FormatInteger(missing, buffer[:]))
Put(*output, " required engine/phase cells missing")
}
Put(*output, ".\n\n")
Put(*output, "This report contains no aggregate or geometric mean. Each row keeps its absolute median, normalized favorable factor, candidate metric change, raw samples, and audited outlier indices. Favorable factors are candidate/baseline for throughput and baseline/candidate for duration, memory, code size, and bundle size; candidate metric change is always (candidate - baseline) / baseline.\n\n")
Put(*output, "## Environment\n\n")
first := *receipts[0]
Put(*output, "- Physical host: `"); Put(*output, EscapeMarkdown(first.physical_host)); Put(*output, "` (`")
Put(*output, EscapeMarkdown(first.host_mode)); Put(*output, "`, VM `")
Put(*output, EscapeMarkdown(first.vm)); Put(*output, "`)\n")
Put(*output, "- CPU: `"); Put(*output, EscapeMarkdown(first.cpu)); Put(*output, "`\n")
Put(*output, "- OS: `"); Put(*output, EscapeMarkdown(first.os)); Put(*output, "`\n\n")
cells := AllCells(required, receipts)
Put(*output, "## Absolute medians and required matrix\n\n")
Put(*output, "| Case | Phase / metric | Unit | old portable VM | new portable | old C/TinyCC native | new native | direct AOT | C control | Go control | Wasm control |\n")
Put(*output, "| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |\n")
for cell: cells {
Put(*output, "| "); Put(*output, EscapeMarkdown(cell.case_id)); Put(*output, " | ")
Put(*output, EscapeMarkdown(cell.phase)); Put(*output, " / ")
Put(*output, EscapeMarkdown(cell.metric)); Put(*output, " | ")
Put(*output, EscapeMarkdown(cell.unit)); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "old-portable-vm")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "new-portable")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "old-c-tinycc-native")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "new-native")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "direct-aot")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "control-c")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "control-go")); Put(*output, " | ")
Put(*output, CellValue(receipts, *cell, "control-wasm")); Put(*output, " |\n")
}
Put(*output, "\n## Per-case comparisons\n\n")
Put(*output, "| Case | Phase / metric | Comparison | Baseline median | Candidate median | Result |\n")
Put(*output, "| --- | --- | --- | ---: | ---: | --- |\n")
for cell: cells {
PairRow(*output, receipts, *cell, "old-portable-vm", "new-portable")
PairRow(*output, receipts, *cell, "old-c-tinycc-native", "new-native")
PairRow(*output, receipts, *cell, "old-c-tinycc-native", "direct-aot")
PairRow(*output, receipts, *cell, "old-portable-vm", "control-c", true)
PairRow(*output, receipts, *cell, "old-portable-vm", "control-go", true)
PairRow(*output, receipts, *cell, "old-portable-vm", "control-wasm", true)
}
Put(*output, "\n## Missing required cells\n\n")
if missing == 0 { Put(*output, "None.\n") }
else {
for cell: required {
for engine: core_engines {
if FindReceipt(receipts, *cell, engine) < 0 {
Put(*output, "- `"); Put(*output, EscapeMarkdown(cell.case_id)); Put(*output, "` / `")
Put(*output, EscapeMarkdown(cell.phase)); Put(*output, "` / `")
Put(*output, EscapeMarkdown(cell.metric)); Put(*output, "` / `")
Put(*output, EscapeMarkdown(cell.unit)); Put(*output, "`: missing `")
Put(*output, engine); Put(*output, "`\n")
}
}
}
}
Put(*output, "\n## Raw receipt audit\n\n")
Put(*output, "Outliers use the canonical symmetric 1.5×IQR fences with linearly interpolated inclusive quartiles. Indices below are zero-based positions in the unchanged raw sample array.\n\n")
for receipt_index: cast(s64)0..receipts.count - 1 {
receipt := *receipts[receipt_index]
Put(*output, "### "); Put(*output, EscapeMarkdown(receipt.receipt_id)); Put(*output, "\n\n")
Put(*output, "- Cell: `"); Put(*output, EscapeMarkdown(receipt.case_id)); Put(*output, "` / `")
Put(*output, EscapeMarkdown(receipt.phase)); Put(*output, "` / `")
Put(*output, EscapeMarkdown(receipt.metric)); Put(*output, "`; engine `")
Put(*output, EscapeMarkdown(receipt.engine)); Put(*output, "`\n")
Put(*output, "- Workload: `"); Put(*output, EscapeMarkdown(receipt.workload)); Put(*output, "`; input checksum `")
Put(*output, EscapeMarkdown(receipt.input_checksum)); Put(*output, "`; iterations `")
buffer: [32]u8
Put(*output, FormatInteger(receipt.iterations, buffer[:]))
Put(*output, "`; semantics `"); Put(*output, EscapeMarkdown(receipt.semantic_settings)); Put(*output, "`\n")
Put(*output, "- Toolchain: `"); Put(*output, EscapeMarkdown(receipt.toolchain)); Put(*output, "`; flags: ")
if receipt.flags.count == 0 { Put(*output, "(none)") }
else {
for index: cast(s64)0..receipt.flags.count - 1 {
if index > 0 { Put(*output, ", ") }
Put(*output, "`"); Put(*output, EscapeMarkdown(receipt.flags[index])); Put(*output, "`")
}
}
Put(*output, "\n- Correctness identity: `"); Put(*output, EscapeMarkdown(receipt.correctness_expected))
Put(*output, "` = `"); Put(*output, EscapeMarkdown(receipt.correctness_actual)); Put(*output, "`\n")
Put(*output, "- Sample count: `"); Put(*output, FormatInteger(receipt.repeats, buffer[:]))
Put(*output, "`; raw samples ("); Put(*output, EscapeMarkdown(receipt.unit)); Put(*output, "): `")
Put(*output, SamplesText(receipt.samples[:])); Put(*output, "`\n")
Put(*output, "- Excluded indices: `"); Put(*output, IndicesText(receipt.statistics.excluded[:]))
Put(*output, "`; retained median: `"); Put(*output, MedianText(receipt)); Put(*output, "`\n\n")
}
if !output.valid { return "", false }
return TextDetach(BuilderFinish(output.bytes)), true
}
#scope_export
ProcessComparison :: (input: string, output: string) -> bool {
if input == output {
print("assembly comparison: input and output paths must differ\n")
return false
}
query := PathQuery(input)
if !query.valid || query.info.kind != .File || query.info.size < 2 ||
query.info.size > MAX_INPUT_BYTES {
print("assembly comparison: input must be a 2-byte..4-MiB regular file\n")
return false
}
text, readable := ReadEntireFile(input)
if !readable || text.count != query.info.size {
print("assembly comparison: input could not be read completely\n")
return false
}
document: JsonDocument
if !JsonRead(*document, text) || JsonKindOf(*document, document.root) != .Object ||
JsonCount(*document, document.root) != 4 {
print("assembly comparison: malformed root receipt document\n")
return false
}
schema, schema_valid := JsonInteger(*document, JsonMember(*document, document.root, "schema_version"))
campaign := ""
if !schema_valid || schema != 1 ||
!FieldInto(*document, document.root, "campaign", *campaign, 256) {
print("assembly comparison: unsupported schema or invalid campaign\n")
return false
}
required_node := JsonMember(*document, document.root, "required_cells")
receipts_node := JsonMember(*document, document.root, "receipts")
if JsonKindOf(*document, required_node) != .Array ||
JsonCount(*document, required_node) == 0 ||
JsonCount(*document, required_node) > MAX_REQUIRED_CELLS ||
JsonKindOf(*document, receipts_node) != .Array ||
JsonCount(*document, receipts_node) > MAX_RECEIPTS {
print("assembly comparison: required_cells or receipts exceeds its bound\n")
return false
}
required: Vec(RequiredCell)
for index: cast(s32)0..JsonCount(*document, required_node) - 1 {
cell: RequiredCell
if !ParseRequiredCell(*document, JsonElement(*document, required_node, index), *cell) {
print("assembly comparison: malformed required cell at index %\n", index)
return false
}
VecPush(required, cell)
}
receipts: Vec(Receipt)
total_samples: s64
for index: cast(s32)0..JsonCount(*document, receipts_node) - 1 {
receipt: Receipt
if !ParseReceipt(*document, JsonElement(*document, receipts_node, index), *receipt) {
print("assembly comparison: malformed receipt or invalid samples at index %\n", index)
return false
}
total_samples += receipt.samples.count
if total_samples > MAX_TOTAL_SAMPLES {
print("assembly comparison: total raw sample bound exceeded\n")
return false
}
VecPush(receipts, receipt)
}
if !ValidateCampaign(required[:], receipts[:]) { return false }
report, valid := BuildReport(campaign, required[:], receipts[:])
if !valid {
print("assembly comparison: report construction failed\n")
return false
}
if !CreateDirectories(PathParent(output)) || !ReplaceFile(output, report) {
print("assembly comparison: atomic report replacement failed\n")
return false
}
return true
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 3 {
print("usage: assembly_compare.zi INPUT.json OUTPUT.md\n")
return 2
}
input := TextDetach(TextCopy(TextFromCString(argv[1])))
output := TextDetach(TextCopy(TextFromCString(argv[2])))
return ifx ProcessComparison(input, output) then 0 else 1
}
+88
View File
@@ -0,0 +1,88 @@
// Read a valid executable with a synthetic binary asset, at the small and
// 75 MB package sizes. Compile and run only on Alpha's physical host:
// LDLIBS="$PWD/build/libziran.a" build-queue -- ziran build --target=c --exe --entry asset_digest:main --root bench --module-path cmd \
// -o build/asset-digest bench/asset_digest.zi
// build-queue -- build/asset-digest/asset_digest
// Each JSON line retains all 11 read samples, with one untimed warmup.
#import "std/timer_linux"
using Bundle :: #import "compiler_bundle"
using Link :: #import "compiler_exec_link"
using Lir :: #import "compiler_lowered_ir"
using Vectors :: #import "std/vec"
Measure :: (program: Lir.LirProgram, count: s64) -> bool {
payload: Vec(u8)
if !VecResize(payload, count) { return false }
defer VecFree(payload)
for index: 0..count - 1 { payload[index] = cast(u8)(index * 37 + 11) }
assets: [1]Bundle.Asset = .{.{name = "data/payload.bin", data = TextView(payload[:])}}
empty: []u8
measured := Link.ZxExecWrite(program, assets[:], empty)
encoded: Vec(u8)
if measured.problem != .None || !VecResize(encoded, measured.size) ||
Link.ZxExecWrite(program, assets[:], encoded[:]).problem != .None { return false }
defer VecFree(encoded)
decoded_assets: [1]Bundle.Asset
layout := Bundle.ExecutableDecode(TextView(encoded[:]), decoded_assets[:])
if layout.problem != .None { return false }
identity: [32]u8
samples: [11]s64
for round: 0..11 {
owner: Link.ZxExecOwner
began := MonotonicNanoseconds()
read := Link.ZxExecRead(*owner, TextView(encoded[:]), Lir.LirDefaultLimits())
elapsed := MonotonicNanoseconds() - began
if read.problem != .None || !owner.valid || owner.assets != 1 {
Link.ZxExecReadFree(*owner)
return false
}
if round == 0 { identity = owner.identity }
else {
for index: 0..31 {
if identity[index] != owner.identity[index] { Link.ZxExecReadFree(*owner); return false }
}
samples[round - 1] = elapsed
}
Link.ZxExecReadFree(*owner)
}
print("{\"asset_bytes\":%,\"bundle_bytes\":%,\"identity\":[", count, measured.size)
for index: 0..31 {
if index > 0 { print(",") }
print("%", identity[index])
}
print("],\"assets_identity\":[")
for index: 0..31 {
if index > 0 { print(",") }
print("%", layout.assets_identity[index])
}
print("],\"content_identity\":[")
for index: 0..31 {
if index > 0 { print(",") }
print("%", layout.content_identity[index])
}
print("],\"samples_ns\":[")
for index: 0..10 {
if index > 0 { print(",") }
print("%", samples[index])
}
print("]}\n")
return true
}
main :: () -> s32 {
types: [2]Lir.LirType = .{.{kind = .Void}, .{kind = .Integer, bits = 32, is_signed = true}}
modules: [1]string = .{"asset-digest"}
constants: [1]Lir.LirConstant = .{.{type = 1, bits = 42}}
values: [1]s32 = .{1}
returned: [1]s32 = .{0}
instructions: [2]Lir.LirInstruction
instructions[0] = .{op = .Constant, result = 0, symbol = 0, origin = -1}
instructions[1] = .{op = .Return, result = -1, operands = returned[:], symbol = -1, origin = -1}
blocks: [1]Lir.LirBlock = .{.{instructions = instructions[:]}}
functions: [1]Lir.LirFunction = .{.{module = 0, name = "main", result = 1,
values = values[:], blocks = blocks[:], entry = 0, origin = -1}}
program := Lir.LirProgram.{version = Lir.LirVersion, modules = modules[:],
types = types[:], constants = constants[:], functions = functions[:], entry = 0}
if !Measure(program, 1000000) || !Measure(program, 75000000) { return 1 }
return 0
}
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env -S ziran run --target=c
// The one entry point for Ziran's benchmarks. From the repository root:
//
// build/bin/ziran run --target=c bench/bench.zi -- list
// build/bin/ziran run --target=c bench/bench.zi -- NAME [DRIVER ARGUMENTS]
// build/bin/ziran run --target=c bench/bench.zi -- --local NAME [DRIVER ARGUMENTS]
// build/bin/ziran run --target=c bench/bench.zi -- check
//
// Every benchmark gets the same environment: no display or desktop-session
// variables, no ZIRAN_PROFILE, and ZIRAN_LEARN=off, so the learning corpus
// never records while something is measured. A host benchmark measures only
// on a physical host named by ZIRAN_BENCH_HOST (`alpha` by default); `--local`
// skips that check for measurement-free modes such as `--validate` or
// `--check`. A device benchmark measures on a phone, and a report reads saved
// receipts, so neither checks the host. `check` verifies that every driver in
// bench/ is registered here and that the shared environment applies.
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/process_run_linux"
#import "std/text_tools"
using Vectors :: #import "std/vec"
#scope_file
libc_bench :: #system_library "libc";
FlushAll :: (stream: *void) -> s32 #foreign libc_bench "fflush";
Runner :: enum u8 { Ziran :: 0; Python :: 1; Shell :: 2; }
Place :: enum u8 { Host :: 0; Device :: 1; Report :: 2; }
Benchmark :: struct {
name: string
file: string
runner: Runner
place: Place
summary: string
module_path: string
compiler_library: bool
}
// A bare name removes the variable from the driver's environment.
BENCH_ENVIRONMENT: [9]string = .["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS",
"SESSION_MANAGER", "XDG_SESSION_ID", "XDG_SESSION_TYPE", "ZIRAN_PROFILE", "ZIRAN_LEARN=off"];
// Files in bench/ that a registered benchmark builds or imports.
SUPPORT_FILES: [15]string = .["bench.zi", "benchmark_statistics.zi", "standard_compile_entry.zi", "standard_cases.zi", "codec_kernels.py", "json_document.zi",
"math_sqrt.zi", "native_cache_fixture.zi", "wasm_tier.zi", "c_teacher_assembly.zi", "c_teacher_profile.zi", "c_teacher_rules.zi", "rill_row.zi", "zx_i386_blocks.zi", "zx_aggregate_load.zi"];
Add :: (list: *Vec(Benchmark), name: string, file: string, runner: Runner, place: Place, summary: string,
module_path: string = "", compiler_library: bool = false) {
unused VecPush(list.*, Benchmark.{.name = name, .file = file, .runner = runner, .place = place, .summary = summary,
.module_path = module_path, .compiler_library = compiler_library})
}
Registry :: () -> Vec(Benchmark) {
list: Vec(Benchmark)
Add(*list, "android-execution", "bench/android_execution.py", .Python, .Device, "cross-built kernels on one Android device")
Add(*list, "asset-digest", "bench/asset_digest.zi", .Ziran, .Host, "checked executable asset digest throughput", "cmd", true)
Add(*list, "assembly", "bench/assembly.py", .Python, .Host, "assembly, portable fallback, C, Go and the ZX engine")
Add(*list, "assembly-collect", "bench/assembly_collect.zi", .Ziran, .Host, "strict assembly comparison receipts")
Add(*list, "assembly-compare", "bench/assembly_compare.zi", .Ziran, .Report, "compare collected assembly receipts")
Add(*list, "body-eligibility", "bench/body_eligibility.py", .Python, .Host, "paired checking with output identity")
Add(*list, "bundle-assets", "bench/bundle_assets.py", .Python, .Host, "checked resource loading with real bundles")
Add(*list, "bundle-instances", "bench/bundle_instances.py", .Python, .Host, "bundle loading and fresh-instance costs")
Add(*list, "compiler-build", "bench/compiler_build.zi", .Ziran, .Host, "full native compiler rebuild")
Add(*list, "standard-compile", "bench/standard_compile.zi", .Ziran, .Host, "complete standard suite builds in C, Go, generated C, native ZX and Wasm")
Add(*list, "standard-ab", "bench/standard_ab.zi", .Ziran, .Host, "shuffled C and in-process ZX native runners on the standard suite")
Add(*list, "standard-profile", "bench/standard_profile.zi", .Ziran, .Host, "SIGPROF samples of an in-process standard runner by function")
Add(*list, "c-teacher", "bench/c_teacher.zi", .Ziran, .Host, "generated C versus native assembly and SIGPROF")
Add(*list, "c-teacher-tune", "bench/c_teacher_tuning.zi", .Ziran, .Host, "offline leaf policies against generated C")
Add(*list, "compiler-kernels", "bench/compiler_kernel_benchmarks.sh", .Shell, .Host, "timed compiler and codec kernels")
Add(*list, "compiler-scaling", "bench/compiler_scaling.py", .Python, .Host, "module graphs and generic specialization")
Add(*list, "cpu-features", "bench/cpu_features.py", .Python, .Host, "CPU-selected assembly against fallbacks")
Add(*list, "enum-values", "bench/enum_values.py", .Python, .Host, "enum-heavy checks and portable loading")
Add(*list, "formatter-builds", "bench/formatter_builds.py", .Python, .Host, "complete builds of the formatter")
Add(*list, "go-assembly", "bench/go_assembly.py", .Python, .Host, "Go assembly bridges against pure Go and C")
Add(*list, "host-capabilities", "bench/host_capabilities.py", .Python, .Host, "host-capability enumeration and calls")
Add(*list, "json-document", "bench/json_document.sh", .Shell, .Host, "direct JSON parser")
Add(*list, "json-string-scan", "bench/json_string_scan.zi", .Ziran, .Host, "JSON string scanning")
Add(*list, "json-text", "bench/json_text.py", .Python, .Host, "JSON and UTF-8 workloads on every target")
Add(*list, "library-targets", "scripts/site_library_targets.py", .Python, .Host, "a library's workloads on the site targets")
Add(*list, "math-sqrt", "bench/math_sqrt.sh", .Shell, .Host, "std/math square root")
Add(*list, "native-builds", "bench/native_builds.py", .Python, .Host, "complete native builds against C and Go")
Add(*list, "native-header-graphs", "bench/native_header_graphs.py", .Python, .Host, "native builds with a dense record ABI")
Add(*list, "native-probe", "bench/native_probe.py", .Python, .Host, "native builds with interleaved probes")
Add(*list, "native-resize-ab", "bench/native_resize_ab.py", .Python, .Host, "matched frozen native runtimes on scalar and vector kernels")
Add(*list, "reachable-types", "bench/reachable_types.py", .Python, .Host, "qualified type-graph lookup")
Add(*list, "rill-compact", "bench/rill_compact.zi", .Ziran, .Host, "checked row memory operations in compact and full-plan engines", "cmd")
Add(*list, "record-calls", "bench/record_calls.py", .Python, .Host, "record values and calls across backends")
Add(*list, "smoke", "bench/smoke.py", .Python, .Host, "cross-target smoke, startup included")
Add(*list, "text-scan", "bench/text_scan.py", .Python, .Host, "UTF-8 scanning across backends")
Add(*list, "type-exports", "bench/type_exports.py", .Python, .Host, "local and re-exported types")
Add(*list, "vector-growth", "bench/vector_growth.py", .Python, .Host, "vector growth across backends")
Add(*list, "vector-growth-ab", "bench/vector_growth_ab.py", .Python, .Host, "two vector-growth binaries, shuffled")
Add(*list, "vm-android", "bench/vm_android.py", .Python, .Device, "saved engine libraries on one Android device")
Add(*list, "vm-execution", "bench/vm_execution.py", .Python, .Host, "verified engine execution")
Add(*list, "vm-native", "bench/vm_native.py", .Python, .Host, "engine workloads against generated C and Go")
Add(*list, "vm-startup", "bench/vm_startup.py", .Python, .Host, "checked loading and engine preparation")
Add(*list, "wasm-tier", "bench/wasm_tier.py", .Python, .Host, "native/Wasm kernels; --standard adds independent C/Go references")
Add(*list, "widget-native", "bench/widget_native.py", .Python, .Host, "matched frozen public Kryon Text, Input and Button scenarios")
Add(*list, "widget-profile", "bench/widget_profile.zi", .Ziran, .Host, "SIGPROF of warmed public widget scenarios")
Add(*list, "zx-compare", "bench/zx_compare.zi", .Ziran, .Host, "ZX runtime comparison cohorts")
Add(*list, "zx-compare-devices", "bench/zx_compare.py", .Python, .Device, "ZX comparison on Alpha or a USB phone")
Add(*list, "zx-engine", "bench/zx_engine.zi", .Ziran, .Host, "instruction engine against the C target")
Add(*list, "zx-execution", "bench/zx_execution.zi", .Ziran, .Host, "warm execution of the matrix's bundles")
Add(*list, "zx-host-slice", "bench/benchmark_zx_host_slice.py", .Python, .Host, "matched i386 host slices, integer blocks and aggregate loads")
return list
}
Concat :: (left: string, right: string) -> string {
parts: [2]string = .[left, right]
return TextDetach(TextJoin(parts[:], ""))
}
Pad :: (text: string, width: s64) -> string {
spaces := " "
if text.count >= width || width > spaces.count { return text }
return Concat(text, spaces[0:width - text.count])
}
PlaceName :: (place: Place) -> string {
if place == .Device { return "device" }
if place == .Report { return "report" }
return "host"
}
Find :: (list: []Benchmark, name: string) -> s64 {
for index: cast(s64)0..list.count - 1 { if list[index].name == name { return index } }
return -1
}
Capture :: (arguments: []string, directory: string) -> (output: string, code: s32) {
options: ProcessOptions = .{arguments = arguments, directory = directory, environment = BENCH_ENVIRONMENT[:],
capture_output = true, merge_error = true}
run: ProcessRun
if !RunProcess(options, *run) { return "", 127 }
return TextDetach(TextCopy(TextTrim(BuilderFinish(run.output)))), run.code
}
HostName :: () -> string {
text, found := ReadEntireFile("/proc/sys/kernel/hostname")
return ifx found then TextDetach(TextCopy(TextTrim(text))) else "unknown"
}
Virtualization :: () -> string {
command: [1]string = .["systemd-detect-virt"]
output, code := Capture(command[:], "")
if code == 127 { return "unavailable" }
return ifx output != "" then output else "none"
}
List :: (list: []Benchmark) -> s32 {
print("benchmarks (run with: build/bin/ziran run --target=c bench/bench.zi -- NAME [ARGS])\n")
for item: list { print(" % % %\n", Pad(item.name, 21), Pad(PlaceName(item.place), 6), item.summary) }
return 0
}
Registered :: (list: []Benchmark, file: string) -> bool {
for item: list { if item.file == file { return true } }
for support: SUPPORT_FILES { if Concat("bench/", support) == file { return true } }
return false
}
IsDriver :: (repo: string, name: string) -> bool {
if TextHasSuffix(name, ".py") || TextHasSuffix(name, ".sh") { return true }
if !TextHasSuffix(name, ".zi") { return false }
text, found := ReadEntireFile(TextDetach(JoinPath(JoinPath(repo, "bench"), name)))
return found && (TextHasPrefix(text, "main ::") || TextContains(text, "\nmain ::"))
}
Check :: (repo: string, list: []Benchmark) -> s32 {
failures: s64 = 0
for item: list {
if !IsFile(TextDetach(JoinPath(repo, item.file))) { print("missing driver for %: %\n", item.name, item.file); failures += 1 }
}
names: Vec(string)
if !ListDirectory(TextDetach(JoinPath(repo, "bench")), *names) { print("cannot list bench/\n"); return 1 }
for name: names {
if IsDriver(repo, name) && !Registered(list, Concat("bench/", name)) {
print("bench/% is a driver that bench/bench.zi does not register\n", name)
failures += 1
}
}
probe: [3]string = .["sh", "-c",
"test \"$ZIRAN_LEARN\" = off && test -z \"${DISPLAY+set}${WAYLAND_DISPLAY+set}${ZIRAN_PROFILE+set}\""]
probe_output, code := Capture(probe[:], repo)
if code != 0 { print("the shared benchmark environment did not apply: %\n", probe_output); failures += 1 }
if failures > 0 { return 1 }
print("bench entry: % benchmarks registered, every driver covered, shared environment applied\n", list.count)
return 0
}
Run :: (repo: string, item: Benchmark, extra: []string, local: bool) -> s32 {
host := HostName()
virtualization := Virtualization()
required := EnvironmentText("ZIRAN_BENCH_HOST")
if required == "" { required = "alpha" }
if item.place == .Host && !local {
physical := virtualization == "none" || virtualization == "container-other"
if host != required || !physical {
print("% measures only on the physical host %; this is % (virtualization %).\n", item.name, required, host, virtualization)
print("Run it there, or pass --local before the name for a measurement-free mode.\n")
return 2
}
}
command: Vec(string)
if item.runner == .Ziran {
ziran := TextDetach(JoinPath(repo, "build/bin/ziran"))
if !IsFile(ziran) { print("build the toolchain first: make\n"); return 2 }
modules := ifx item.module_path == "" then repo else TextDetach(JoinPath(repo, item.module_path))
prefix := string.[ziran, "run", "--target=c", "--root", TextDetach(JoinPath(repo, "bench")), "--module-path", modules,
TextDetach(JoinPath(repo, item.file)), "--"]
for part: prefix { unused VecPush(command, part) }
} else {
interpreter := ifx item.runner == .Python then "python3" else "sh"
unused VecPush(command, interpreter)
unused VecPush(command, TextDetach(JoinPath(repo, item.file)))
}
for part: extra { unused VecPush(command, part) }
mode := ifx local then "local, not a measurement" else PlaceName(item.place)
print("benchmark % on % (virtualization %, %)\n", item.name, host, virtualization, mode)
environment: Vec(string)
for variable: BENCH_ENVIRONMENT { unused VecPush(environment, variable) }
if item.compiler_library {
libraries := Concat(Concat(EnvironmentText("LDLIBS"), " "), TextDetach(JoinPath(repo, "build/libziran.a")))
unused VecPush(environment, Concat("LDLIBS=", libraries))
}
options: ProcessOptions = .{arguments = VecSlice(command, 0, command.count), directory = repo,
environment = environment[:]}
// The header reaches the terminal before anything the driver prints.
unused FlushAll(null)
run: ProcessRun
if !RunProcess(options, *run) { print("cannot start %\n", item.file); return 2 }
return run.code
}
#scope_export
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
repo := PathParent(PathParent(EnvironmentText("ZIRAN_SCRIPT_FILE")))
if repo == "" || !IsFile(TextDetach(JoinPath(repo, "bench/bench.zi"))) { repo = ResolvePath(".") }
if !IsFile(TextDetach(JoinPath(repo, "bench/bench.zi"))) { print("run from the Ziran repository\n"); return 2 }
registry := Registry()
list := VecSlice(registry, 0, registry.count)
index: s32 = 1
local := false
if index < argc && TextFromCString(argv[index]) == "--local" { local = true; index += 1 }
if index >= argc { return List(list) }
name := TextFromCString(argv[index])
if name == "list" || name == "--help" || name == "-h" { return List(list) }
if name == "check" { return Check(repo, list) }
found := Find(list, name)
if found < 0 {
print("unknown benchmark: % (bench/bench.zi -- list shows them)\n", name)
return 2
}
extra: Vec(string)
index += 1
while index < argc { unused VecPush(extra, TextFromCString(argv[index])); index += 1 }
return Run(repo, list[found], VecSlice(extra, 0, extra.count), local)
}
+48
View File
@@ -0,0 +1,48 @@
// Shared native benchmark statistics. Keep raw samples in their original order;
// symmetric inclusive-quartile Tukey fences determine the displayed median.
#import "std/math"
#import "std/sort"
using Vectors :: #import "std/vec"
BenchmarkSampleStatistics :: struct {
valid: bool
lower: float64
upper: float64
median: float64
excluded: Vec(s64)
included: Vec(float64)
}
BenchmarkQuantile :: (sorted: []float64, fraction: float64) -> float64 {
if sorted.count == 0 { return 0.0 }
position := cast(float64)(sorted.count - 1) * fraction
lower := cast(s64)position
upper := ifx lower + 1 < sorted.count then lower + 1 else lower
return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - cast(float64)lower)
}
BenchmarkAnalyze :: (samples: []float64) -> BenchmarkSampleStatistics {
if samples.count < 3 { return .{} }
sorted: Vec(float64)
for sample: samples {
if sample <= 0.0 || !Finite64(sample) { return .{} }
VecPush(sorted, sample)
}
Sort(sorted[:])
q1 := BenchmarkQuantile(sorted[:], 0.25)
q3 := BenchmarkQuantile(sorted[:], 0.75)
result: BenchmarkSampleStatistics
result.lower = q1 - 1.5 * (q3 - q1)
result.upper = q3 + 1.5 * (q3 - q1)
for index: cast(s64)0..samples.count - 1 {
if samples[index] < result.lower || samples[index] > result.upper { VecPush(result.excluded, index) }
else { VecPush(result.included, samples[index]) }
}
if result.included.count < 3 { return .{} }
kept: Vec(float64)
for value: result.included { VecPush(kept, value) }
Sort(kept[:])
result.median = BenchmarkQuantile(kept[:], 0.5)
result.valid = true
return result
}
+88
View File
@@ -0,0 +1,88 @@
"""Measure ZX execution with matched Linux/i386 archives on physical Alpha."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import socket
import subprocess
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
from benchmark_samples import HostGate, summarize_samples
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('loader', type=Path)
parser.add_argument('libraries', type=Path)
parser.add_argument('inputs', type=Path)
parser.add_argument('output', type=Path)
parser.add_argument('--hot-blocks', action='store_true', help='Use the integer fixture in place of host slices')
parser.add_argument('--aggregate-loads', action='store_true', help='Also measure 32 KiB aggregate snapshots')
args = parser.parse_args()
host = socket.gethostname()
virtualization = subprocess.run(['systemd-detect-virt'], text=True, capture_output=True).stdout.strip()
if host.split('.')[0] != 'alpha' or virtualization != 'none':
parser.error('A physical Alpha host is required')
inputs = args.inputs.resolve()
gate = HostGate()
workloads = [('integer-blocks', 113475636, 'engine', False)] if args.hot_blocks else [
('small', 0x235689BC, 'slice', True), ('large', 0x235689BC, 'slice', True),
]
if args.aggregate_loads:
workloads.append(('aggregate-load', 499008, 'engine', False))
workloads.extend([
('rill-row', 1622073797, 'engine', False),
('sieve', 2262, 'engine', False),
('records', 68788, 'engine', False),
])
order = ('baseline', 'candidate', 'candidate', 'baseline',
'candidate', 'baseline', 'baseline', 'candidate')
receipt = {'host': host, 'virtualization': virtualization, 'kernel': platform.release(),
'gate': gate.describe(), 'order': order, 'sha256': {}, 'workloads': {}}
for artifact in sorted(inputs.iterdir()):
if artifact.is_file():
with artifact.open('rb') as stream:
receipt['sha256'][artifact.name] = hashlib.file_digest(stream, 'sha256').hexdigest()
def save():
temp = args.output.with_suffix('.tmp')
temp.write_text(json.dumps(receipt, indent=2) + '\n')
temp.replace(args.output)
for workload, expected, driver, borrow in workloads:
attempts = []
samples = {'baseline': [], 'candidate': []}
receipt['workloads'][workload] = {'attempts': attempts, 'summaries': {}}
for variant in order:
env = dict(os.environ)
env.pop('MATRIX_BORROW_SLICE', None)
if borrow and variant == 'candidate':
env['MATRIX_BORROW_SLICE'] = '1'
command = [args.loader, '--library-path', args.libraries,
inputs / f'{variant}-{driver}', inputs / f'{workload}.zx', str(expected), '15']
for _ in range(gate.ATTEMPTS):
measurement, observation = gate.observe(lambda: json.loads(
subprocess.check_output(command, env=env, text=True)))
rejection = gate.rejection(observation)
attempts.append(dict(variant=variant, borrowed=borrow and variant == 'candidate',
measurement=measurement, host_gate=observation, rejection=rejection))
save()
print(f'{workload} {variant} cpu{gate.cpu}: {rejection or "accepted"}', flush=True)
if rejection is None:
samples[variant].extend(ms / measurement['batches'] for ms in measurement['batch_samples_ms'])
break
gate.choose_core()
else:
raise SystemExit('Host gate rejected every attempt')
result = receipt['workloads'][workload]
result['summaries'] = {variant: summarize_samples(values) for variant, values in samples.items()}
result['speedup'] = result['summaries']['baseline']['median_ms'] / result['summaries']['candidate']['median_ms']
save()
if __name__ == '__main__':
main()
+1 -1
View File
@@ -94,7 +94,7 @@ def main():
emitted = output/'c'; bundle = output/'program.zx'
check = [binaries/'zi2zir', '--check-only', '--root', root, input_path]
emit = [binaries/'zi2c', '--root', root, '-o', emitted, input_path]
pack = [binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'program:Answer', '-o', bundle, input_path]
pack = [binaries/'zi2zx', '--root', root, '--entry', 'program:Answer', '-o', bundle, input_path]
for phase, command in [('check', check), ('emit:c', emit), ('bundle', pack)]:
invoke(command); register(case, form, version, phase, command)
invoke([binaries/'zi2zx', 'run', bundle], expected=expected)
+407
View File
@@ -0,0 +1,407 @@
// Compare generated C with the native pipeline using identical checked input.
// Run only through bench/bench.zi; all compilation and sampling shares its
// learning-off environment and the caller's build-queue reservation.
#import "c_teacher_assembly"
#import "c_teacher_profile"
#import "c_teacher_rules"
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/json_document"
#import "std/number_text"
#import "std/process_run_linux"
#import "std/text_tools"
using Vectors :: #import "std/vec"
#scope_file
Case :: struct { name: string; bundle: string; cdir: string; symbol: string; header: string; expected: s32; printing: bool; checksum: string }
Finding :: struct { workload: string; compiler: string; name: string; native: TeacherMetrics; teacher: TeacherMetrics; samples: s64; total: s64; score: s64 }
Join :: (a: string, b: string) -> string { parts := string.[a, b]; return TextDetach(TextJoin(parts[:], "")) }
Number :: (n: s64) -> string { bytes: [32]u8; return Join("", FormatInteger(n, bytes[:])) }
Field :: (d: *JsonDocument, node: s32, key: string) -> string { return TextDetach(JsonString(d, JsonMember(d, node, key))) }
Integer :: (d: *JsonDocument, node: s32, key: string) -> s64 { n, ok := JsonInteger(d, JsonMember(d, node, key)); return ifx ok then n else -1 }
Capture :: (args: []string) -> (text: string, code: s32) {
run: ProcessRun
options: ProcessOptions = .{arguments = args, capture_output = true, merge_error = true}
if !RunProcess(options, *run) { return "could not start child", 127 }
return TextDetach(BuilderFinish(run.output)), run.code
}
Require :: (args: []string) -> bool {
text, code := Capture(args)
if code != 0 { print("command failed (%): %\n%\n", code, TextJoin(args, " "), text); return false }
return true
}
Sources :: (directory: string, suffix: string, files: *Vec(string)) {
names: Vec(string)
if !ListDirectory(directory, *names) { return }
for name: names {
path := TextDetach(JoinPath(directory, name))
if IsDirectory(path) { Sources(path, suffix, files) }
else if TextHasSuffix(path, suffix) { unused VecPush(files.*, path) }
}
}
Hash :: (path: string) -> string {
command := string.["sha256sum", path]
text, code := Capture(command[:])
return ifx code == 0 && text.count >= 64 then text[:64] else "unavailable"
}
Clang :: () -> string {
candidates := string.["clang", "clang-22", "clang-21", "clang-20", "clang-19", "clang-18", "clang-17"]
for candidate: candidates {
command := string.[candidate, "--version"]
version, code := Capture(command[:])
if code == 0 { return candidate }
}
return ""
}
Metrics :: (m: TeacherMetrics) -> string {
values := s64.[m.instructions, m.loop_instructions, m.back_edges, m.stack_reads, m.stack_writes,
m.memory, m.indexed, m.branches, m.forward_branches, m.calls, m.vectors, m.multiplies, m.divides, m.shifts, m.loop_constants]
parts: Vec(string)
for value: values { unused VecPush(parts, Number(value)) }
return TextDetach(TextJoin(VecSlice(parts, 0, parts.count), "/"))
}
Patterns :: (n: TeacherMetrics, c: TeacherMetrics) -> string {
patterns: Vec(string)
if n.stack_reads + n.stack_writes > c.stack_reads + c.stack_writes { unused VecPush(patterns, "stack traffic (regalloc/aggregate lane)") }
if n.branches > c.branches { unused VecPush(patterns, "branch layout/loop rotation (SSA lane)") }
if n.calls > c.calls { unused VecPush(patterns, "calls/inlining candidates") }
if n.multiplies + n.divides > c.multiplies + c.divides { unused VecPush(patterns, "strength reduction candidates") }
if n.loop_constants > c.loop_constants { unused VecPush(patterns, "loop constants/LICM candidates") }
if c.vectors > n.vectors { unused VecPush(patterns, "vector idioms (inspect scalar SSE uses)") }
if n.memory > c.memory { unused VecPush(patterns, "memory/address folding candidates") }
return TextDetach(TextJoin(VecSlice(patterns, 0, patterns.count), "; "))
}
SaveProfile :: (path: string, profile: *TeacherProfile, digest: string) -> bool {
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
JsonSet(*document, root, "artifact_sha256", JsonNewStringCopy(*document, digest))
JsonSet(*document, root, "samples", JsonNewInteger(*document, profile.total))
JsonSet(*document, root, "runs", JsonNewInteger(*document, profile.runs))
ips := JsonNewArray(*document)
JsonSet(*document, root, "ips", ips)
for sample: profile.samples {
ip := JsonNewObject(*document)
JsonSet(*document, ip, "address", JsonNewInteger(*document, cast(s64)sample.address))
JsonSet(*document, ip, "count", JsonNewInteger(*document, sample.count))
unused JsonAppend(*document, ips, ip)
}
return WriteEntireFile(path, TextDetach(JsonWrite(*document, root, JsonPythonStyle(2))))
}
Append :: (text: *Vec(u8), value: string) { BuilderAppend(text.*, value) }
Line :: (text: *Vec(u8), value: string) { Append(text, value); Append(text, "\n") }
Row :: (text: *Vec(u8), cells: []string) {
Append(text, "| "); Append(text, TextDetach(TextJoin(cells, " | "))); Line(text, " |")
}
LoopSummary :: (code: []TeacherInstruction, begin: s64, end: s64, base: s64, profile: *TeacherProfile) -> string {
loops := TeacherLoops(code, begin, end)
best: TeacherLoop
best_samples: s64 = -1
for loop: loops {
samples: s64
for sample: profile.samples {
if sample.address >= cast(u64)(base + loop.begin) && sample.address <= cast(u64)(base + loop.end) { samples += sample.count }
}
if samples > best_samples || samples == best_samples && loop.instructions > best.instructions {
best = loop; best_samples = samples
}
}
if best_samples < 0 { return "none" }
parts := string.[Number(best.begin), "..", Number(best.end), ": ", Number(best.instructions), " instructions, ", Number(best_samples), " samples"]
return TextDetach(TextJoin(parts[:], ""))
}
Bindings :: (arguments: *Vec(string)) -> bool {
text, found := ReadEntireFile("build/site-library-targets/sources/widget_benchmarks.json")
document: JsonDocument
defer JsonReset(*document)
if !found || !JsonRead(*document, text) { return false }
bindings := JsonMember(*document, document.root, "bindings")
if JsonKindOf(*document, bindings) != .Array { return false }
for index: cast(s32)0..JsonCount(*document, bindings) - 1 {
binding := TeacherIRBinding(JsonString(*document, JsonElement(*document, bindings, index)))
if binding == "" { return false }
unused VecPush(arguments.*, "--bind")
unused VecPush(arguments.*, binding)
}
return true
}
// Reuse the scenario harness's checked IR, including its ordinary library
// bindings, rather than teaching this tool anything about widget internals.
GenerateC :: (item: Case, directory: string) -> bool {
if item.name == "Hello" { return true }
arguments: Vec(string)
root := ifx item.header == "wasm_tier.h" then "bench" else "build/site-library-targets/ir"
module := ifx item.header == "wasm_tier.h" then "wasm_tier" else "widget_benchmarks"
entry := ifx item.header == "wasm_tier.h" then item.name else Join(item.name, "Case")
flags := string.["build/bin/zi2c", "--no-main", "--root", root, "--module-path", "std", "--entry",
Join(module, Join(":", entry)), "-o", directory]
for flag: flags { unused VecPush(arguments, flag) }
if root == "bench" { unused VecPush(arguments, "bench/wasm_tier.zi") }
else {
if !Bindings(*arguments) { return false }
Sources(root, ".zir", *arguments)
}
return Require(VecSlice(arguments, 0, arguments.count))
}
Compare :: (item: Case, compiler: string, work: string, report: *Vec(u8), findings: *Vec(Finding)) -> bool {
directory := TextDetach(JoinPath(work, item.name))
if !CreateDirectories(directory) { return false }
generated := TextDetach(JoinPath(directory, "c"))
if !GenerateC(item, generated) { return false }
cdir := ifx item.name == "Hello" then item.cdir else generated
native := TextDetach(JoinPath(directory, "native"))
mapfile := TextDetach(JoinPath(directory, "native.map.json"))
native_command := string.["build/bin/zx2native", "-o", native, item.bundle]
map_command := string.["build/bin/zx2native", "--emit", "map", "-o", mapfile, item.bundle]
if !Require(native_command[:]) || !Require(map_command[:]) { return false }
maptext, read := ReadEntireFile(mapfile)
map: JsonDocument
defer JsonReset(*map)
if !read || !JsonRead(*map, maptext) { return false }
identity := JsonMember(*map, map.root, "identity")
if Field(*map, identity, "digest") != Hash(native) { print("native map identity mismatch for %\n", item.name); return false }
image := JsonMember(*map, map.root, "image")
offset := Integer(*map, image, "text_file_offset")
size := Integer(*map, image, "text_size")
base := Integer(*map, image, "text_virtual_address")
raw := TextDetach(JoinPath(directory, "text.bin"))
extract_command := string.["dd", Join("if=", native), Join("of=", raw), "bs=65536", "iflag=skip_bytes,count_bytes",
Join("skip=", Number(offset)), Join("count=", Number(size)), "status=none"]
if offset < 0 || size <= 0 || !Require(extract_command[:]) { return false }
native_dump := string.["objdump", "-D", "-b", "binary", "-m", "i386:x86-64", "-M", "intel", "--no-show-raw-insn", raw]
ntext, ncode := Capture(native_dump[:])
if ncode != 0 { return false }
unused WriteEntireFile(JoinPath(directory, "native.asm"), ntext)
executable := TextDetach(JoinPath(directory, compiler))
arguments: Vec(string)
flags := string.[compiler, "-O2", "-std=c11"]
for flag: flags { unused VecPush(arguments, flag) }
matrix_flags := string.["-DMATRIX_NATIVE", Join("-I", cdir),
Join("-DMATRIX_HEADER=\"", Join(item.header, "\"")), Join("-DMATRIX_ENTRY=", item.symbol)]
if item.header != "" { for flag: matrix_flags { unused VecPush(arguments, flag) } }
if item.header != "" { unused VecPush(arguments, "bench/site_target_host.c") }
if item.printing { unused VecPush(arguments, "-DMATRIX_VOID") }
Sources(cdir, ".c", *arguments)
link_flags := string.["-lm", "-o", executable]
for flag: link_flags { unused VecPush(arguments, flag) }
if !Require(VecSlice(arguments, 0, arguments.count)) { return false }
parity_command := string.[executable, "-", item.checksum, "3"]
parity, parity_code := Capture(parity_command[:])
if parity_code != 0 { print("C checksum parity failed for %/%: %\n", item.name, compiler, parity); return false }
unused WriteEntireFile(JoinPath(directory, Join(compiler, ".parity.json")), parity)
c_dump := string.["objdump", "-d", "-M", "intel", "--no-show-raw-insn", executable]
ctext, ccode := Capture(c_dump[:])
if ccode != 0 { return false }
unused WriteEntireFile(JoinPath(directory, Join(compiler, ".asm")), ctext)
// Sampling is diagnostic, never a benchmark timing. Short programs may
// yield no ticks; report unknown instead of inventing a time share.
profile := TeacherSampleProgram(native, item.expected)
if !profile.valid { print("sampling failed for %\n", item.name); return false }
if !SaveProfile(JoinPath(directory, Join(compiler, ".profile.json")), *profile, Hash(native)) { return false }
Line(report, Join("\n## ", Join(item.name, Join(" / ", compiler))))
Line(report, Join("Native SHA-256: ", Hash(native)))
Line(report, Join("C SHA-256: ", Hash(executable)))
Line(report, Join("ZX SHA-256: ", Hash(item.bundle)))
version_command := string.[compiler, "--version"]
compiler_version, version_code := Capture(version_command[:])
version_end := TextFind(compiler_version, "\n")
if version_end >= 0 { compiler_version = compiler_version[:version_end] }
Line(report, Join("Compiler: ", compiler_version))
Line(report, Join("SIGPROF samples/runs: ", Join(Number(profile.total), Join("/", Number(profile.runs)))))
Line(report, "\n| Function | Native metrics | C metrics | Samples | Native loop with most samples (text offsets) |\n| --- | --- | --- | ---: | --- |")
ninst := TeacherInstructions(ntext)
cinst := TeacherInstructions(ctext)
symbol_command := string.["nm", "-S", "-n", "--defined-only", executable]
symbol_text, symbol_code := Capture(symbol_command[:])
if symbol_code != 0 { return false }
symbols := TeacherSizedSymbols(symbol_text)
proposals: JsonDocument
defer JsonReset(*proposals)
proposal_root := JsonNewObject(*proposals)
JsonSet(*proposals, proposal_root, "schema_version", JsonNewInteger(*proposals, 1))
JsonSet(*proposals, proposal_root, "native_sha256", JsonNewStringCopy(*proposals, Hash(native)))
JsonSet(*proposals, proposal_root, "zx_sha256", JsonNewStringCopy(*proposals, Hash(item.bundle)))
JsonSet(*proposals, proposal_root, "c_sha256", JsonNewStringCopy(*proposals, Hash(executable)))
JsonSet(*proposals, proposal_root, "compiler", JsonNewStringCopy(*proposals, compiler_version))
proposal_rules := JsonNewArray(*proposals)
JsonSet(*proposals, proposal_root, "candidates", proposal_rules)
functions := JsonMember(*map, map.root, "functions")
for index: cast(s32)0..JsonCount(*map, functions) - 1 {
function := JsonElement(*map, functions, index)
begin := Integer(*map, function, "begin")
end := Integer(*map, function, "end")
if begin < 0 || end <= begin { continue }
name := Field(*map, function, "name")
module := Field(*map, function, "module")
mangled := Join(module, Join("_", name))
found := false
cbegin: s64
cend: s64
cmetrics: TeacherMetrics
for symbol: symbols {
if symbol.name == mangled || name != "main" && symbol.name == name {
cmetrics = TeacherMeasure(VecSlice(cinst, 0, cinst.count), symbol.begin, symbol.end)
cbegin = symbol.begin; cend = symbol.end
found = true; break
}
}
native_metrics := TeacherMeasure(VecSlice(ninst, 0, ninst.count), begin, end)
samples: s64
for sample: profile.samples {
if sample.address >= cast(u64)(base + begin) && sample.address < cast(u64)(base + end) { samples += sample.count }
}
cname := ifx found then Metrics(cmetrics) else "absent (inline/dead/renamed unknown)"
cells := string.[mangled, Metrics(native_metrics), cname, Number(samples),
LoopSummary(VecSlice(ninst, 0, ninst.count), begin, end, base, *profile)]
Row(report, cells[:])
if found {
rules := TeacherMineRewrites(VecSlice(ninst, 0, ninst.count), begin, end,
VecSlice(cinst, 0, cinst.count), cbegin, cend)
for rule: rules {
proposal := JsonNewObject(*proposals)
JsonSet(*proposals, proposal, "rule", JsonNewStringCopy(*proposals, "x86-multiply-constant"))
JsonSet(*proposals, proposal, "function", JsonNewStringCopy(*proposals, mangled))
JsonSet(*proposals, proposal, "factor", JsonNewInteger(*proposals, rule.factor))
JsonSet(*proposals, proposal, "native", JsonNewStringCopy(*proposals, rule.native))
JsonSet(*proposals, proposal, "teacher", JsonNewStringCopy(*proposals, rule.teacher))
JsonSet(*proposals, proposal, "precondition", JsonNewStringCopy(*proposals, "integer-modulo-width; flags-dead; no-memory"))
JsonSet(*proposals, proposal, "verified", JsonNewBool(*proposals, false))
unused JsonAppend(*proposals, proposal_rules, proposal)
}
}
if found && native_metrics.instructions > cmetrics.instructions {
delta := native_metrics.instructions - cmetrics.instructions
// Ranking is a proxy, not estimated cycles. Weight excess code by
// observed function samples; unsampled functions rank last.
score := ifx profile.total > 0 then samples * 100000 * delta / (native_metrics.instructions * profile.total) else 0
unused VecPush(findings.*, Finding.{workload = item.name, compiler = compiler, name = mangled,
native = native_metrics, teacher = cmetrics, samples = samples, total = profile.total, score = score})
}
}
return WriteEntireFile(JoinPath(directory, Join(compiler, ".candidates.json")),
TextDetach(JsonWrite(*proposals, proposal_root, JsonPythonStyle(2))))
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
output := "bench/results/c-teacher-omega.md"
if argc == 3 && TextFromCString(argv[1]) == "--output" { output = TextFromCString(argv[2]) }
else if argc != 1 { print("c_teacher.zi [--output REPORT.md]\nPrepare wasm-tier and library-targets through bench/bench.zi first.\n"); return 2 }
work := "build/c-teacher"
if !CreateDirectories(work) { return 1 }
cases: Vec(Case)
kernel_names := string.["Sieve", "Records", "Hash", "Vectors", "Calls", "Printing"]
for name: kernel_names {
wrapper_path := Join("build/wasm-tier/native_", Join(name, ".zi"))
wrapper, found := ReadEntireFile(wrapper_path)
if !found { print("prepare wasm-tier first: missing %\n", wrapper_path); return 1 }
wrapper = TextDetach(TextReplace(wrapper, "0..31", "0..1023"))
checksum_at := TextFind(wrapper, "checksum != ")
result := "0"
if checksum_at >= 0 {
at := checksum_at + 12
end := TextFind(wrapper, " {", at)
checksum, ok := TextInteger(wrapper[at:end])
if !ok { return 1 }
result = Number(checksum / 32)
wrapper = TextDetach(TextReplace(wrapper, Join("checksum != ", Number(checksum)), Join("checksum != ", Number(checksum * 32))))
}
teacher_source := TextDetach(JoinPath(work, Join("teacher_", Join(name, ".zi"))))
bundle := TextDetach(JoinPath(work, Join(name, ".zx")))
if !WriteEntireFile(teacher_source, wrapper) { return 1 }
build_command := string.["build/bin/zi2zx", "--root", work, "--module-path", "bench", "--module-path", "std",
"--entry", Join("teacher_", Join(name, ":main")), "-o", bundle, teacher_source]
if !Require(build_command[:]) { return 1 }
unused VecPush(cases, Case.{name = name, bundle = bundle,
cdir = "build/wasm-tier/c", symbol = Join("wasm_tier_", name), header = "wasm_tier.h", expected = 42, printing = name == "Printing", checksum = result})
}
widget_cases := string.["Button", "Text", "Input"]
widget_ids := string.["button", "text", "input"]
for index: 0..2 {
folder := Join("build/site-library-targets/", widget_ids[index])
module := Join("teacher_", widget_cases[index])
source := TextDetach(JoinPath(work, Join(module, ".zi")))
bundle := TextDetach(JoinPath(work, Join(module, ".zx")))
body := string.["Widget :: #import \"widget_benchmarks\";\n#program_export\nmain :: () -> s32 {\n",
" for iteration: 0..2047 { if Widget.", widget_cases[index], "Case() != 0 { return 1 } }\n return 0\n}\n"]
if !WriteEntireFile(source, TextDetach(TextJoin(body[:], ""))) { return 1 }
command: Vec(string)
flags := string.["build/bin/zi2zx", "--root", work, "--module-path", "build/site-library-targets/ir", "--module-path", "std",
"--entry", Join(module, ":main"), "-o", bundle]
for flag: flags { unused VecPush(command, flag) }
if !Bindings(*command) { return 1 }
unused VecPush(command, source)
Sources("build/site-library-targets/ir", ".zir", *command)
if !Require(VecSlice(command, 0, command.count)) { return 1 }
unused VecPush(cases, Case.{name = widget_cases[index], bundle = bundle,
cdir = Join(folder, "/c"), symbol = Join(widget_cases[index], "Case"), header = "widget_benchmarks.h", checksum = "0"})
}
hello_bundle := string.["build/bin/zi2zx", "--root", "examples", "--module-path", "std", "--entry", "hello:main", "-o", "build/c-teacher/hello.zx", "examples/hello.zi"]
hello_c := string.["build/bin/zi2c", "--root", "examples", "--module-path", "std", "-o", "build/c-teacher/hello-c", "examples/hello.zi"]
if !Require(hello_bundle[:]) || !Require(hello_c[:]) { return 1 }
unused VecPush(cases, Case.{name = "Hello", bundle = "build/c-teacher/hello.zx", cdir = "build/c-teacher/hello-c",
symbol = "hello_main", header = "hello.h", printing = true, checksum = "0"})
report: Vec(u8)
revision_command := string.["git", "rev-parse", "HEAD"]
revision, code := Capture(revision_command[:])
Line(*report, "# C teacher: native assembly comparison")
Line(*report, Join("\nBase revision: ", TextTrim(revision)))
host_command := string.["hostname"]
host, host_code := Capture(host_command[:])
if host_code != 0 { return 1 }
Line(*report, Join("Host: ", TextTrim(host)))
tool_names := string.["build/bin/zi2c", "build/bin/zi2zx", "build/bin/zx2native"]
tool_hashes: Vec(string)
for tool: tool_names {
digest := Hash(tool)
unused VecPush(tool_hashes, digest)
Line(*report, Join(tool, Join(" SHA-256: ", digest)))
}
Line(*report, "Learning off. Generated C compiled with -O2; native compiled from verified ZX. Function extents come from the native map; C symbols match module_name or exported name exactly. Absent symbols are not evidence of inlining. Metrics: instructions/loop-union/back-edges/stack-reads/stack-writes/memory/indexed/branches/forward-branches/calls/vector-register-uses/mul/div/shifts/loop-immediate-or-PC-relative candidates. Stack traffic includes locals and saves. Vector-register uses include scalar floating point. Loop constants are LICM candidates, not proven invariants. Back edges describe loop bodies, not execution frequency. SIGPROF uses a 1ms CPU timer, at most 30 runs; zero samples means unknown time share. Sampling includes process startup and runtime. Ranking weights relative instruction excess by observed function samples; it predicts neither cycles nor speedup.")
findings: Vec(Finding)
clang := Clang()
failures: s64
for item: cases {
if !Compare(item, "cc", work, *report, *findings) {
Line(*report, Join("\nINCOMPLETE: comparison failed for ", item.name))
failures += 1
continue
}
if clang != "" && !Compare(item, clang, work, *report, *findings) {
Line(*report, Join("\nINCOMPLETE: clang comparison failed for ", item.name))
failures += 1
}
}
ranked: Vec(u8)
Line(*ranked, "\n## Ranked C wins\n\n| Workload/compiler/function | Weighted excess | Function samples/total (estimated CPU share) | Patterns to inspect | Native | C |\n| --- | ---: | ---: | --- | --- | --- |")
for index: 1..findings.count - 1 {
at := index
while at > 0 && findings[at].score > findings[at - 1].score {
swap := findings[at]; findings[at] = findings[at - 1]; findings[at - 1] = swap; at -= 1
}
}
for finding: findings {
identity := string.[finding.workload, finding.compiler, finding.name]
share := ifx finding.total > 0 then Join(Number(finding.samples * 100 / finding.total), "%") else "unknown"
cells := string.[TextDetach(TextJoin(identity[:], "/")), Number(finding.score),
Join(Number(finding.samples), Join("/", Join(Number(finding.total), Join(" ", share)))),
Patterns(finding.native, finding.teacher), Metrics(finding.native), Metrics(finding.teacher)]
Row(*ranked, cells[:])
}
Append(*report, TextDetach(BuilderFinish(ranked)))
for index: 0..tool_names.count - 1 {
if Hash(tool_names[index]) != tool_hashes[index] {
Line(*report, Join("INCOMPLETE: compiler changed during comparison: ", tool_names[index]))
failures += 1
}
}
if !WriteEntireFile(output, TextDetach(BuilderFinish(report))) { return 1 }
print("C teacher: % workloads, % ranked function comparisons, % failed; %\n", cases.count, findings.count, failures, output)
return ifx failures == 0 then 0 else 1
}
+194
View File
@@ -0,0 +1,194 @@
// Structural observations, never equivalence proofs. Addresses are normalized
// by the caller: ELF virtual addresses for C, text-relative addresses for ZX.
#import "std/text_tools"
#import "std/byte_text_linux"
using Vectors :: #import "std/vec"
TeacherInstruction :: struct {
address: s64
mnemonic: string
operands: string
}
TeacherFunction :: struct {
name: string
begin: s64
end: s64
}
TeacherLoop :: struct { begin: s64; end: s64; instructions: s64 }
// Checked IR export uses the leaf module name. Apply the same mapping to
// each qualified side of a manifest binding; retain the function spelling.
TeacherIRBinding :: (binding: string) -> string {
sides := TextSplit(binding, "=")
flattened: Vec(string)
for side: sides {
colon := TextFind(side, ":")
if colon < 0 { return "" }
slash := TextFindLast(side[:colon], "/")
unused VecPush(flattened, side[slash + 1:])
}
if flattened.count != 2 { return "" }
return TextDetach(TextJoin(VecSlice(flattened, 0, flattened.count), "="))
}
TeacherMetrics :: struct {
instructions: s64
loop_instructions: s64
back_edges: s64
stack_reads: s64
stack_writes: s64
memory: s64
indexed: s64
branches: s64
forward_branches: s64
calls: s64
vectors: s64
multiplies: s64
divides: s64
shifts: s64
loop_constants: s64
}
TeacherHex :: (text: string) -> (value: s64, valid: bool) {
if TextHasPrefix(text, "0x") { text = text[2:] }
value: s64
digits: s64
for byte: text {
digit: s64 = -1
if byte >= 48 && byte <= 57 { digit = cast(s64)byte - 48 }
if byte >= 97 && byte <= 102 { digit = cast(s64)byte - 87 }
if byte >= 65 && byte <= 70 { digit = cast(s64)byte - 55 }
if digit < 0 || value > 576460752303423487 { return 0, false }
value = value * 16 + digit
digits += 1
}
return value, digits > 0
}
// objdump --no-show-raw-insn -M intel. Ignore symbol headings, data and
// diagnostic lines; never count a wrapped instruction byte line as code.
TeacherInstructions :: (text: string) -> Vec(TeacherInstruction) {
result: Vec(TeacherInstruction)
lines := TextLines(text)
for raw: lines {
line := TextTrim(raw)
colon := TextFind(line, ":")
if colon <= 0 { continue }
address, valid := TeacherHex(line[:colon])
if !valid { continue }
body := TextTrim(line[colon + 1:])
at: s64
while at < body.count && !TextIsSpace(body[at]) { at += 1 }
if at == 0 { continue }
mnemonic := body[:at]
if mnemonic == "(bad)" || mnemonic[0] == 46 { continue }
unused VecPush(result, TeacherInstruction.{address = address, mnemonic = mnemonic,
operands = TextTrim(body[at:])})
}
return result
}
TeacherSymbols :: (text: string) -> Vec(TeacherFunction) {
result: Vec(TeacherFunction)
lines := TextLines(text)
for raw: lines {
line := TextTrim(raw)
left := TextFind(line, " <")
right := TextFind(line, ">:")
if left <= 0 || right <= left { continue }
address, valid := TeacherHex(line[:left])
if !valid { continue }
if result.count > 0 { result[result.count - 1].end = address }
unused VecPush(result, TeacherFunction.{name = line[left + 2:right], begin = address, end = 9223372036854775807})
}
return result
}
// nm -S -n --defined-only gives real symbol sizes, excluding alignment
// padding and adjacent functions. Zero-sized/untyped symbols stay unmatched.
TeacherSizedSymbols :: (text: string) -> Vec(TeacherFunction) {
result: Vec(TeacherFunction)
lines := TextLines(text)
for line: lines {
pieces := TextSplit(TextTrim(line), " ")
fields: Vec(string)
for piece: pieces { if piece != "" { unused VecPush(fields, piece) } }
if fields.count != 4 || fields[2] != "T" && fields[2] != "t" { continue }
address, address_ok := TeacherHex(fields[0])
size, size_ok := TeacherHex(fields[1])
if !address_ok || !size_ok || size <= 0 || size > 9223372036854775807 - address { continue }
unused VecPush(result, TeacherFunction.{name = fields[3], begin = address, end = address + size})
}
return result
}
TeacherBranch :: (instruction: TeacherInstruction) -> bool {
return TextHasPrefix(instruction.mnemonic, "j") || instruction.mnemonic == "loop"
}
TeacherTarget :: (instruction: TeacherInstruction) -> (address: s64, valid: bool) {
at: s64
while at < instruction.operands.count && !TextIsSpace(instruction.operands[at]) { at += 1 }
return TeacherHex(instruction.operands[:at])
}
TeacherLoops :: (code: []TeacherInstruction, begin: s64, end: s64) -> Vec(TeacherLoop) {
result: Vec(TeacherLoop)
for instruction: code {
if instruction.address < begin || instruction.address >= end || !TeacherBranch(instruction) { continue }
target, valid := TeacherTarget(instruction)
if !valid || target < begin || target > instruction.address { continue }
count: s64
for member: code { if member.address >= target && member.address <= instruction.address { count += 1 } }
unused VecPush(result, TeacherLoop.{begin = target, end = instruction.address, instructions = count})
}
return result
}
TeacherMeasure :: (code: []TeacherInstruction, begin: s64, end: s64) -> TeacherMetrics {
result: TeacherMetrics
// Count the union of loop intervals; nested loops must not inflate the
// static instruction count. Back edges are candidates, not hotness data.
loops := TeacherLoops(code, begin, end)
result.back_edges = loops.count
for instruction: code {
if instruction.address < begin || instruction.address >= end { continue }
result.instructions += 1
loop := false
for candidate: loops {
if instruction.address >= candidate.begin && instruction.address <= candidate.end { loop = true }
}
if loop { result.loop_instructions += 1 }
operands := instruction.operands
memory := TextContains(operands, "[")
if memory {
result.memory += 1
if TextContains(operands, "*") || TextContains(operands, "+r") || TextContains(operands, "+e") { result.indexed += 1 }
// Stack references include locals, saved registers and spills.
// They cannot be identified as allocator spills from assembly alone.
if TextContains(operands, "[rsp") || TextContains(operands, "[rbp") {
comma := TextFind(operands, ",")
bracket := TextFind(operands, "[")
if comma >= 0 && bracket < comma && instruction.mnemonic != "cmp" && instruction.mnemonic != "test" && instruction.mnemonic != "lea" {
result.stack_writes += 1
} else if instruction.mnemonic != "lea" { result.stack_reads += 1 }
}
}
if TeacherBranch(instruction) {
result.branches += 1
target, valid := TeacherTarget(instruction)
if valid && target > instruction.address { result.forward_branches += 1 }
}
if instruction.mnemonic == "call" { result.calls += 1 }
if TextContains(operands, "xmm") || TextContains(operands, "ymm") || TextContains(operands, "zmm") { result.vectors += 1 }
if instruction.mnemonic == "imul" || instruction.mnemonic == "mul" { result.multiplies += 1 }
if instruction.mnemonic == "idiv" || instruction.mnemonic == "div" { result.divides += 1 }
if instruction.mnemonic == "shl" || instruction.mnemonic == "shr" || instruction.mnemonic == "sar" { result.shifts += 1 }
if loop && (TextContains(operands, ",0x") || instruction.mnemonic == "lea" && TextContains(operands, "[rip")) {
result.loop_constants += 1
}
}
return result
}
+213
View File
@@ -0,0 +1,213 @@
// SIGPROF sampling of a private child, Linux x86-64. Install ITIMER_PROF at
// exec's first stop, restore its instruction and registers, and then sample
// unchanged code. No signal handler or runtime is added to the measured ELF.
#import "std/c_string"
#import "std/file"
#import "std/number_text"
#import "std/text_tools"
using Vectors :: #import "std/vec"
#scope_file
libc_teacher :: #system_library "libc";
Ptrace :: (request: s64, pid: s32, address: u64, data: u64) -> s64 #foreign libc_teacher "ptrace";
Fork :: () -> s32 #foreign libc_teacher "fork";
Exec :: (path: *u8, arguments: **u8) -> s32 #foreign libc_teacher "execv";
Exit :: (code: s32) -> void #foreign libc_teacher "_exit";
WaitPid :: (pid: s32, status: *s32, options: s32) -> s32 #foreign libc_teacher "waitpid";
Kill :: (pid: s32, number: s32) -> s32 #foreign libc_teacher "kill";
Open :: (path: *u8, flags: s32) -> s32 #foreign libc_teacher "open";
Dup :: (from: s32, to: s32) -> s32 #foreign libc_teacher "dup2";
Close :: (fd: s32) -> s32 #foreign libc_teacher "close";
PreadRaw :: (fd: s32, buffer: *u8, count: u64, offset: s64) -> s64 #foreign libc_teacher "pread";
Errno :: () -> *s32 #foreign libc_teacher "__errno_location";
Registers :: struct { words: [27]u64 }
Wait :: (pid: s32, status: *s32) -> bool {
while true {
if WaitPid(pid, status, 0) == pid { return true }
if Errno()[0] != 4 { return false }
}
}
Hex :: (text: string) -> u64 {
value: u64 = 0
for byte: text {
if byte >= #char "0" && byte <= #char "9" { value = value * 16 + cast(u64)(byte - #char "0") }
else if byte >= #char "a" && byte <= #char "f" { value = value * 16 + cast(u64)(byte - #char "a") + 10 }
else { break }
}
return value
}
// The first executable mapping without a path in MAPS, read from the
// stopped child's memory.
CaptureImage :: (pid: s32, maps: string, profile: *TeacherProfile) {
lines := TextLines(maps)
for line: lines {
dash := TextFind(line, "-")
space := TextFind(line, " ")
if dash <= 0 || space <= dash || space + 4 > line.count || line[space + 3] != #char "x" { continue }
// Anonymous mappings end after the inode field: five fields only.
fields: s64 = 0
at: s64 = 0
while at < line.count {
while at < line.count && line[at] == #char " " { at += 1 }
if at < line.count { fields += 1 }
while at < line.count && line[at] != #char " " { at += 1 }
}
if fields != 5 { continue }
begin := Hex(line[0:dash])
end := Hex(line[dash + 1:space])
if end <= begin || end - begin > 268435456 { return }
buffer: [32]u8
parts := string.["/proc/", FormatInteger(cast(s64)pid, buffer[:]), "/mem"]
path: [64]u8
if !CopyCString(TextDetach(TextJoin(parts[:], "")), path[:]) { return }
fd := Open(*path[0], 0)
if fd < 0 { return }
unused VecResize(profile.image, cast(s64)(end - begin))
if PreadRaw(fd, *profile.image[0], end - begin, cast(s64)begin) == cast(s64)(end - begin) { profile.image_base = begin }
else { unused VecResize(profile.image, 0) }
unused Close(fd)
return
}
}
Trace :: (request: s64, pid: s32, address: u64, data: u64) -> bool {
error := Errno()
error[0] = 0
result := Ptrace(request, pid, address, data)
return result != -1 || Errno()[0] == 0
}
#scope_export
TeacherSample :: struct { address: u64; count: s64 }
TeacherProfile :: struct {
samples: Vec(TeacherSample)
total: s64
runs: s64
valid: bool
exit_code: s32
// With maps requested: the child's first anonymous executable mapping
// (an in-process native image) and its address.
image_base: u64
image: Vec(u8)
}
TeacherSampleRun :: (path: string, profile: *TeacherProfile) -> bool {
arguments := string.[path]
return TeacherSampleProcess(arguments[:], profile, null)
}
// Samples ARGUMENTS[0] run with ARGUMENTS. MAPS, when not null, receives
// the child's /proc maps at its 64th sample, so samples in anonymous code
// (an in-process native image) and in shared libraries can be attributed.
TeacherSampleProcess :: (arguments: []string, profile: *TeacherProfile, maps: *Vec(u8)) -> bool {
if arguments.count < 1 || arguments.count > 15 { return false }
text: [8192]u8
sink: [16]u8
pointers: [16]*u8
used: s64 = 0
for index: cast(s64)0..arguments.count - 1 {
if used + arguments[index].count + 1 > text.count || !CopyCString(arguments[index], text[used:]) { return false }
pointers[index] = *text[used]
used += arguments[index].count + 1
}
pointers[arguments.count] = null
if !CopyCString("/dev/null", sink[:]) { return false }
cpath := pointers[0]
pid := Fork()
if pid < 0 { return false }
if pid == 0 {
fd := Open(*sink[0], 1)
if fd < 0 { Exit(120); return false }
unused Dup(fd, 1); unused Dup(fd, 2); unused Close(fd)
if !Trace(0, 0, 0, 0) { Exit(121); return false }
unused Exec(cpath, *pointers[0])
Exit(122)
return false
}
reaped := false
status: s32
defer {
if !reaped {
// Confirm this PID is still our unreaped child before signaling.
pending := WaitPid(pid, *status, 1)
if pending == 0 || pending == pid && (status & 255) == 127 {
unused Kill(pid, 9)
unused Wait(pid, *status)
}
}
}
if !Wait(pid, *status) { return false }
if (status & 255) != 127 { reaped = true; return false }
// EXITKILL ensures a stopped child cannot outlive a failed tracer.
if !Trace(16896, pid, 0, 1048576) { return false }
saved: Registers
if !Trace(12, pid, 0, cast(u64)*saved) { return false }
ip := saved.words[16]
error := Errno()
error[0] = 0
original := Ptrace(1, pid, ip, 0)
if original == -1 && Errno()[0] != 0 { return false }
// syscall is two bytes; single-step it with setitimer(ITIMER_PROF).
patched := (cast(u64)original & ~cast(u64)65535) | 1295
if !Trace(4, pid, ip, patched) { return false }
timer := saved.words[19] - 128
values: [4]u64 = .[0, 1000, 0, 1000]
for index: 0..3 { if !Trace(5, pid, timer + cast(u64)index * 8, values[index]) { return false } }
registers := saved
registers.words[10] = 38
registers.words[14] = 2
registers.words[13] = timer
registers.words[12] = 0
if !Trace(13, pid, 0, cast(u64)*registers) || !Trace(9, pid, 0, 0) || !Wait(pid, *status) { return false }
if (status & 255) != 127 || !Trace(12, pid, 0, cast(u64)*registers) || registers.words[10] != 0 { return false }
if !Trace(4, pid, ip, cast(u64)original) || !Trace(13, pid, 0, cast(u64)*saved) || !Trace(7, pid, 0, 0) { return false }
while Wait(pid, *status) {
if (status & 127) == 0 {
reaped = true
profile.exit_code = (status >> 8) & 255
profile.runs += 1
return true
}
if (status & 255) != 127 { reaped = true; return false }
signal_number := (status >> 8) & 255
if signal_number == 27 {
if !Trace(12, pid, 0, cast(u64)*registers) { return false }
address := registers.words[16]
found := false
for index: 0..profile.samples.count - 1 {
if profile.samples[index].address == address { profile.samples[index].count += 1; found = true; break }
}
if !found { unused VecPush(profile.samples, TeacherSample.{address = address, count = 1}) }
profile.total += 1
if maps != null && profile.total == 64 {
buffer: [32]u8
parts := string.["/proc/", FormatInteger(cast(s64)pid, buffer[:]), "/maps"]
path := TextDetach(TextJoin(parts[:], ""))
captured: Vec(u8)
if ReadFileInto(path, *captured) {
CaptureImage(pid, TextView(captured[:]), profile)
unused VecResize(<<maps, 0)
for byte: captured { unused VecPush(<<maps, byte) }
}
VecFree(captured)
}
signal_number = 0
}
if !Trace(7, pid, 0, cast(u64)signal_number) { return false }
}
return false
}
TeacherSampleProgram :: (path: string, expected: s32) -> TeacherProfile {
profile: TeacherProfile
valid := true
for run: 0..29 {
if !TeacherSampleRun(path, *profile) || profile.exit_code != expected { valid = false; break }
if profile.total >= 150 { break }
}
profile.valid = valid
return profile
}
+59
View File
@@ -0,0 +1,59 @@
// Mine candidates only. Matching two assembly idioms proves nothing about
// program equivalence; the learning verifier must certify their semantics.
#import "c_teacher_assembly"
#import "std/text_tools"
using Vectors :: #import "std/vec"
TeacherRewrite :: struct { factor: s64; native: string; teacher: string }
TeacherLeaFactor :: (operands: string) -> s64 {
left := TextFind(operands, "[")
right := TextFind(operands, "]")
if left < 0 || right < left { return 0 }
body := operands[left + 1:right]
plus := TextFind(body, "+")
if plus <= 0 { return 0 }
base := body[:plus]
index := body[plus + 1:]
star := TextFind(index, "*")
if star < 0 { return ifx base == index then 2 else 0 }
if index[:star] != base { return 0 }
scale, valid := TeacherHex(index[star + 1:])
if !valid || scale != 1 && scale != 2 && scale != 4 && scale != 8 { return 0 }
return 1 + scale
}
TeacherIdiomFactor :: (instruction: TeacherInstruction) -> s64 {
if instruction.mnemonic == "lea" { return TeacherLeaFactor(instruction.operands) }
parts := TextSplit(instruction.operands, ",")
if parts.count != 2 { return 0 }
if instruction.mnemonic == "add" && TextTrim(parts[0]) == TextTrim(parts[1]) { return 2 }
if instruction.mnemonic != "shl" && instruction.mnemonic != "sal" { return 0 }
shift, valid := TeacherHex(TextTrim(parts[1]))
if !valid || shift < 1 || shift > 30 { return 0 }
return cast(s64)(cast(u64)1 << cast(u64)shift)
}
TeacherMineRewrites :: (native: []TeacherInstruction, begin: s64, end: s64,
teacher: []TeacherInstruction, cbegin: s64, cend: s64) -> Vec(TeacherRewrite) {
result: Vec(TeacherRewrite)
for instruction: native {
if instruction.address < begin || instruction.address >= end || instruction.mnemonic != "imul" { continue }
operands := TextSplit(instruction.operands, ",")
if operands.count != 3 { continue }
factor, valid := TeacherHex(TextTrim(operands[2]))
if !valid || factor < 2 { continue }
duplicate := false
for rule: result { if rule.factor == factor { duplicate = true; break } }
if duplicate { continue }
for candidate: teacher {
if candidate.address < cbegin || candidate.address >= cend || TeacherIdiomFactor(candidate) != factor { continue }
n := string.[instruction.mnemonic, " ", instruction.operands]
c := string.[candidate.mnemonic, " ", candidate.operands]
unused VecPush(result, TeacherRewrite.{factor = factor,
native = TextDetach(TextJoin(n[:], "")), teacher = TextDetach(TextJoin(c[:], ""))})
break
}
}
return result
}
+220
View File
@@ -0,0 +1,220 @@
// Offline calibration of the bounded leaf pass. Run through bench/bench.zi.
// Uses the teacher's long, checksum-checking kernel wrappers and generated C.
#import, file "../cmd/compiler_exec_link.zi";
#import, file "../cmd/compiler_opt.zi";
#import, file "../cmd/compiler_lowered_ir.zi";
#import, file "../cmd/compiler_bundle.zi";
#import, file "../cmd/compiler_learning.zi";
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/json_document"
#import "std/number_text"
#import "std/process_run_linux"
#import "std/text_tools"
#import "std/timer_linux"
#import "std/vec"
#scope_file
Join :: (a: string, b: string) -> string { parts := string.[a, b]; return TextDetach(TextJoin(parts[:], "")) }
Number :: (n: s64) -> string { digits: [32]u8; return Join("", FormatInteger(n, digits[:])) }
Capture :: (arguments: []string) -> (text: string, code: s32) {
run: ProcessRun
options := ProcessOptions.{arguments = arguments, capture_output = true, merge_error = true}
if !RunProcess(options, *run) { return "cannot start child", 127 }
return TextDetach(BuilderFinish(run.output)), run.code
}
Require :: (arguments: []string) -> bool {
text, code := Capture(arguments)
if code != 0 { print("calibration failed (%): %\n%\n", code, TextJoin(arguments, " "), text); return false }
return true
}
Digest :: (path: string) -> string {
command := string.["sha256sum", "--", path]
text, code := Capture(command[:])
return ifx code == 0 && text.count >= 64 then text[:64] else ""
}
TextField :: (document: *JsonDocument, root: s32, key: string, value: string) {
JsonSet(document, root, key, JsonNewStringCopy(document, value))
}
Policy :: (document: *JsonDocument, row: s32, leaf: s32) {
policy := JsonNewObject(document)
JsonSet(document, row, "policy", policy)
JsonSet(document, policy, "leaf_operations", JsonNewInteger(document, leaf))
JsonSet(document, policy, "unroll_factor", JsonNewInteger(document, 1))
JsonSet(document, policy, "block_layout", JsonNewInteger(document, 1))
JsonSet(document, policy, "allocation", JsonNewInteger(document, 0))
}
// Clone/verify and vary only the leaf pass. The canonical input has already
// passed the ordinary optimizer; running other passes again would confound it.
Variant :: (source: string, output: string, leaf: s32) -> bool {
bytes, found := ReadEntireFile(source)
if !found { return false }
decoded: ZxExecOwner
defer ZxExecReadFree(*decoded)
if ZxExecRead(*decoded, bytes, LirDefaultLimits()).problem != .None || decoded.assets != 0 { return false }
if ZxExecReadProgram(*decoded).checks { return false }
optimized: LirOptOwner
defer LirOptFree(*optimized)
options := LirOptOptions.{maximum_rounds = 1, inline_leaf_operations = leaf}
result := LirOptBuild(*optimized, ZxExecReadProgram(*decoded), LirDefaultLimits(), options)
if result.problem != .None { return false }
program := LirOptProgram(*optimized)
assets: [0]Asset
empty: []u8
measured := ZxExecWrite(program, assets[:], empty, TextView(decoded.interface[:]))
if measured.problem != .None { return false }
encoded: Vec(u8)
defer VecFree(encoded)
if !VecResize(encoded, measured.size) { return false }
written := ZxExecWrite(program, assets[:], encoded[:], TextView(decoded.interface[:]))
if written.problem != .None || written.size != measured.size { return false }
print("leaf=% inlined_calls=% source=%\n", leaf, result.counters.inline_leaf.instructions, source)
return WriteEntireFile(output, TextView(encoded[:]))
}
Time :: (executable: string) -> s64 {
command := string.[executable]
options := ProcessOptions.{arguments = command[:], output_path = "/dev/null", error_path = "/dev/null"}
run: ProcessRun
start := MonotonicNanoseconds()
if !RunProcess(options, *run) || run.code != 42 { return -1 }
return MonotonicNanoseconds() - start
}
Record :: (corpus: string, bundle: string, elf: string, original: string, compiler: string) -> string {
format := Join("zx", Join(Number(ExecutableVersionNumber()), Join("-lir", Number(LirVersion))))
zx_digest := Digest(bundle)
native_digest := Digest(elf)
relative := Join(format, Join("/", Join(zx_digest, Join("/x86_64-", native_digest))))
stem := Join(corpus, Join("/", relative))
folder := PathParent(stem)
if !CreateDirectories(folder) { return "" }
copy_zx := string.["cp", "--", bundle, Join(folder, "/program.zx")]
copy_elf := string.["cp", "--", elf, Join(stem, ".elf")]
map := string.["build/bin/zx2native", "--emit", "map", "-o", Join(stem, ".map.json"), bundle]
if !Require(copy_zx[:]) || !Require(copy_elf[:]) || !Require(map[:]) { return "" }
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
TextField(*document, root, "format", format)
TextField(*document, root, "target", "x86_64")
TextField(*document, root, "platform", "linux")
TextField(*document, root, "zx2native_sha256", compiler)
TextField(*document, root, "input_sha256", original)
TextField(*document, root, "producer", "c-teacher-tune")
if !WriteEntireFile(Join(stem, ".record.json"), JsonWrite(*document, root, JsonCompactStyle())) { return "" }
return Join(relative, ".record.json")
}
Epoch :: (work: string) -> string {
// Hash the source inventory too: exact tool identities alone cannot detect
// edits awaiting a rebuild. Include untracked learning modules explicitly.
command := string.["git", "ls-files", "cmd", "std", "Makefile", "assembly.mk", "bench"]
inventory, code := Capture(command[:])
if code != 0 { return "" }
paths := TextLines(inventory)
defer VecFree(paths)
text: Vec(u8)
for path: paths {
if path == "" || TextHasPrefix(path, "bench/results/") { continue }
hash := Digest(path)
if hash.count != 64 { VecFree(text); return "" }
BuilderAppend(text, path); BuilderAppend(text, hash)
}
extra := string.["build/bin/zi2c", "build/bin/zi2zx", "build/bin/zx2native",
"cmd/compiler_opt_inline.zi", "cmd/compiler_learning.zi", "cmd/compiler_learning_policy.zi",
"cmd/compiler_learning_table.zi", "bench/c_teacher_tuning.zi"]
for path: extra {
hash := Digest(path)
if hash.count != 64 { VecFree(text); return "" }
BuilderAppend(text, path); BuilderAppend(text, hash)
}
receipt := Join(work, "/source-epoch")
return ifx WriteEntireFile(receipt, BuilderFinish(text)) then Digest(receipt) else ""
}
#scope_export
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
output: string; corpus: string
if argc != 5 { print("usage: c-teacher-tune --output FILE --corpus DIR\n"); return 1 }
for index: cast(s32)1..argc - 1 {
value := TextFromCString(argv[index])
if value == "--output" && index + 1 < argc { output = TextFromCString(argv[index + 1]) }
if value == "--corpus" && index + 1 < argc { corpus = TextFromCString(argv[index + 1]) }
}
if output == "" || corpus == "" || EnvironmentText("ZIRAN_LEARN") != "off" { return 1 }
policy := LearningTuningChoice()
if policy.leaf_operations != 0 || policy.block_layout != 1 {
print("calibration needs the baseline leaf/layout table and freshly prepared teacher inputs\n"); return 1
}
work := "build/c-teacher/tuning"
if !CreateDirectories(work) || !CreateDirectories(corpus) { return 1 }
epoch := Epoch(work)
compiler := Digest("build/bin/zx2native")
host := string.["hostname"]
hostname, host_code := Capture(host[:])
if epoch.count != 64 || compiler.count != 64 || host_code != 0 { return 1 }
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
JsonSet(*document, root, "checks", JsonNewBool(*document, false))
TextField(*document, root, "target", "x86_64-linux")
TextField(*document, root, "learning", "off")
TextField(*document, root, "host", TextTrim(hostname))
TextField(*document, root, "source_epoch_sha256", epoch)
TextField(*document, root, "method", "paired process wall time; 1024 checksum-checked kernel calls; includes startup; 11 samples")
rows := JsonNewArray(*document)
JsonSet(*document, root, "measurements", rows)
names := string.["Sieve", "Records", "Hash", "Vectors", "Calls", "Printing"]
for name: names {
folder := Join(work, Join("/", name))
if !CreateDirectories(folder) { return 1 }
original := Join("build/c-teacher/", Join(name, ".zx"))
source := Join("build/c-teacher/teacher_", Join(name, ".zi"))
reference_folder := Join(folder, "/c")
reference := Join(reference_folder, Join("/teacher_", name))
c := string.["env", "CFLAGS=-O2", "build/bin/zi2c", "--exe", "--root", "build/c-teacher", "--module-path", "bench", "--module-path", "std",
"--entry", Join("teacher_", Join(name, ":main")), "-o", reference_folder, source]
if !Require(c[:]) { return 1 }
for leaf: cast(s32)0..cast(s32)1 {
bundle := Join(folder, Join("/policy-", Join(Number(leaf), ".zx")))
native := Join(folder, Join("/policy-", Number(leaf)))
if !Variant(original, bundle, leaf) { return 1 }
encode := string.["build/bin/zx2native", "-o", native, bundle]
if !Require(encode[:]) { return 1 }
record := Record(corpus, bundle, native, Digest(original), compiler)
if record == "" || Time(native) <= 0 || Time(reference) <= 0 { return 1 }
row := JsonNewObject(*document)
unused JsonAppend(*document, rows, row)
TextField(*document, row, "workload", name)
TextField(*document, row, "input_sha256", Digest(original))
TextField(*document, row, "zx_sha256", Digest(bundle))
TextField(*document, row, "native_sha256", Digest(native))
TextField(*document, row, "compiler_sha256", compiler)
TextField(*document, row, "corpus_record", record)
TextField(*document, row, "checksum", "42"); TextField(*document, row, "c_checksum", "42")
file := OpenRead(native)
if !file.valid { return 1 }
JsonSet(*document, row, "code_bytes", JsonNewInteger(*document, FileSize(file)))
CloseFile(file)
Policy(*document, row, leaf)
ns := JsonNewArray(*document); cs := JsonNewArray(*document)
JsonSet(*document, row, "native_ns", ns); JsonSet(*document, row, "c_ns", cs)
for sample: 0..10 {
// Alternate native/reference order to reduce drift bias.
n: s64; ctime: s64
if sample % 2 == 0 { n = Time(native); ctime = Time(reference) }
else { ctime = Time(reference); n = Time(native) }
if n <= 0 || ctime <= 0 { return 1 }
unused JsonAppend(*document, ns, JsonNewInteger(*document, n))
unused JsonAppend(*document, cs, JsonNewInteger(*document, ctime))
}
}
}
if Epoch(work) != epoch || Digest("build/bin/zx2native") != compiler { print("compiler/source changed; calibration rejected\n"); return 1 }
if !WriteEntireFile(output, JsonWrite(*document, root, JsonPythonStyle(2))) { return 1 }
print("Saved measured leaf policies: %, corpus %\n", output, corpus)
return 0
}
+28 -19
View File
@@ -406,7 +406,7 @@ def main():
if not cc or not hasattr(os, 'wait4'):
parser.error('a C compiler and POSIX wait4 are required')
bins = args.bin_dir.resolve()
required = ['ziran', 'zi2zir', 'zi2c', 'zi2go', 'zi2zx']
required = ['ziran', 'zi2zir', 'zi2c', 'zi2go', 'zi2zx', 'zx2wasm']
for name in required:
if not (bins / name).is_file():
parser.error(f'missing compiler tool: {bins / name}; build the toolchain first')
@@ -477,7 +477,7 @@ def main():
'correctness': 'Python oracle, all native vectors, then source/saved IR small bundle outputs; all before timing',
'warm_native': 'fresh process, one full untimed call on identical input, then one timed call; both results checked',
'cold_process': 'first call in a fresh process, no cache flush; process wall/CPU include startup and kernel initialization',
'portable_process': 'fresh portable VM process for each sample; includes bundle load/verification and interpreter startup',
'portable_process': 'fresh portable engine process for each sample; includes bundle load/verification and interpreter startup',
'kernel_region': 'initialization, scalar algorithm, checksum and call overhead; excludes code generation, build and process startup',
'compile': 'single separately recorded build phase, no claim of cold or repeated compile performance'},
limitations=[
@@ -500,10 +500,10 @@ def main():
metadata['toolchain'] = {'cc': invoke([cc, '--version'], 'metadata', 'C compiler version')[0],
'cc_target': invoke([cc, '-dumpmachine'], 'metadata', 'C compiler target')[0],
'python': sys.version}
tool_files = [bins / name for name in required] + [bins / 'zi2wasm', bins.parent / 'libziran.a']
tool_files = [bins / name for name in required] + [bins.parent / 'libziran.a']
metadata['tools'] = {str(path): dict(sha256=digest(path), size=path.stat().st_size, mtime_ns=path.stat().st_mtime_ns)
for path in tool_files if path.is_file()}
inputs = [Path(__file__), ROOT / 'tests/compiler_kernel_benchmarks.sh',
inputs = [Path(__file__), ROOT / 'bench/compiler_kernel_benchmarks.sh',
FIXTURES / 'codec_kernels.zi', FIXTURES / 'codec_kernels_layout.zi']
metadata['input_hashes'] = {str(path.relative_to(ROOT)): digest(path) for path in inputs}
# Capture compiler/library source identity without loading source contents.
@@ -621,7 +621,7 @@ def main():
wasm_python = importlib.util.find_spec('wasmtime') is not None
browser = shutil.which('firefox') or shutil.which('chromium')
wasm_engine = wasm_python or bool(browser)
capabilities['wasm'] = dict(generator=str(bins / 'zi2wasm'), execution='available' if wasm_engine else 'unavailable',
capabilities['wasm'] = dict(generator=f"{bins / 'zi2zx'} | {bins / 'zx2wasm'}", execution='available' if wasm_engine else 'unavailable',
runner='Python Wasmtime' if wasm_python else f'private headless {Path(browser).name}' if browser else None,
reason='' if wasm_engine else 'No Python wasmtime binding, Firefox or Chromium executable; Node/npm/npx prohibited. Generated modules do not count as executed validation.')
if wasm_python:
@@ -634,18 +634,23 @@ def main():
for function in ['Validate', *[kind + 'Bench' for kind in KERNELS]]:
wanted = validation if function == 'Validate' else oracle(function[:-5], 8, 37)
bundle = out / f'{form}-{function}.zx'
invoke([ziran, 'bundle', '--root', root, '--entry', f'codec_kernels:{function}', '-o', bundle, entry], 'codegen', f'{form} {function} bundle')
# `run --vm` is explicitly the portable interpreter, not native dispatch.
command = [bins / 'zi2zx', 'run', '--vm', bundle]
invoke([bins / 'zi2zx', '--root', root, '--entry', f'codec_kernels:{function}', '-o', bundle, entry], 'codegen', f'{form} {function} bundle')
# A bundle runs on the portable instruction engine.
command = [bins / 'zi2zx', 'run', bundle]
actual = invoke(command, 'correctness', f'{form} portable {function}')[0]
if actual != str(wanted):
raise AssertionError(f'{form} portable {function}: {actual} != {wanted}')
if function != 'Validate':
portable.append((f'{form}-portable-{function[:-5]}', command, wanted))
if (bins / 'zi2wasm').is_file():
if (bins / 'zx2wasm').is_file():
wasm = out / f'{form}-{function}.wasm'
_, row, diagnostic = invoke([bins / 'zi2wasm', '--root', root, '--entry', f'codec_kernels:{function}',
'-o', wasm, entry], 'codegen', f'{form} {function} Wasm', allow_failure=True)
wasm_wire = out / f'{form}-{function}-wasm.zx'
_, row, diagnostic = invoke([bins / 'zi2zx', '--target', 'wasm', '--root', root,
'--entry', f'codec_kernels:{function}', '-o', wasm_wire, entry],
'codegen', f'{form} {function} Wasm ZX', allow_failure=True)
if not row['returncode']:
_, row, diagnostic = invoke([bins / 'zx2wasm', '-o', wasm, wasm_wire],
'codegen', f'{form} {function} Wasm', allow_failure=True)
if row['returncode']:
capabilities[f'wasm-{form}-{function}'] = {'generation': 'unsupported', 'execution': 'unavailable', 'reason': diagnostic, 'command': row}
else:
@@ -659,19 +664,23 @@ def main():
if function != 'Validate':
portable.append((f'{form}-wasm-{function[:-5]}', command, wanted))
else:
capabilities['wasm']['reason'] = 'zi2wasm tool is not built'
capabilities['wasm']['reason'] = 'zx2wasm tool is not built'
bundle = out / f'{form}-layout.zx'
invoke([ziran, 'bundle', '--root', root, '--entry', 'codec_kernels_layout:Sizes', '-o', bundle, audit_entry], 'codegen', f'{form} logical size bundle')
value = int(invoke([bins / 'zi2zx', 'run', '--vm', bundle], 'audit', f'{form} portable logical sizes')[0])
invoke([bins / 'zi2zx', '--root', root, '--entry', 'codec_kernels_layout:Sizes', '-o', bundle, audit_entry], 'codegen', f'{form} logical size bundle')
value = int(invoke([bins / 'zi2zx', 'run', bundle], 'audit', f'{form} portable logical sizes')[0])
logical_fingerprint = 8 * 1000000 + 8 * 10000 + 16 * 100 + 24
if value != logical_fingerprint:
raise AssertionError(f'{form} portable size_of differs from TypeLayout: {value}')
layout[f'{form}-portable-size-fingerprint'] = value
if (bins / 'zi2wasm').is_file():
if (bins / 'zx2wasm').is_file():
wasm = out / f'{form}-layout.wasm'
_, row, diagnostic = invoke([bins / 'zi2wasm', '--root', root, '--entry',
'codec_kernels_layout:Sizes', '-o', wasm, audit_entry],
'codegen', f'{form} Wasm layout audit', allow_failure=True)
wasm_wire = out / f'{form}-layout-wasm.zx'
_, row, diagnostic = invoke([bins / 'zi2zx', '--target', 'wasm', '--root', root,
'--entry', 'codec_kernels_layout:Sizes', '-o', wasm_wire, audit_entry],
'codegen', f'{form} Wasm layout ZX', allow_failure=True)
if not row['returncode']:
_, row, diagnostic = invoke([bins / 'zx2wasm', '-o', wasm, wasm_wire],
'codegen', f'{form} Wasm layout audit', allow_failure=True)
capabilities[f'wasm-{form}-layout'] = {'generation': 'unsupported' if row['returncode'] else 'succeeded',
'execution': 'unavailable', 'reason': diagnostic, 'command': row}
if not row['returncode'] and wasm_engine:
@@ -787,7 +796,7 @@ def main():
if digest(path) != identity['sha256']:
raise RuntimeError(f'tool changed during run: {path}')
capabilities['native-c'] = {'execution': 'validated', 'modes': ['dispatch', 'ZIRAN_NO_ASM']}
capabilities['portable-zx'] = {'execution': 'validated', 'runner': str(bins / 'zi2zx') + ' run --vm'}
capabilities['portable-zx'] = {'execution': 'validated', 'runner': str(bins / 'zi2zx') + ' run'}
wasm_results = [value['execution'] for key, value in capabilities.items()
if key.startswith('wasm-') and key.endswith('Bench')]
if wasm_results and all(value == 'validated' for value in wasm_results):
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env -S ziran run --target=c
// Time a full native rebuild. --profile records each make shell recipe.
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/float_text"
#import "std/json_document"
#import "std/number_text"
#import "std/process_run_linux"
#import "std/text_tools"
#import "std/timer_linux"
using Vectors :: #import "std/vec"
#scope_file
libc_build :: #system_library "libc";
ProcessId :: () -> s32 #foreign libc_build "getpid";
TimeValue :: struct { seconds: isize; microseconds: isize }
Usage :: struct { user: TimeValue; system: TimeValue; counters: [14]isize }
GetUsage :: (kind: s32, usage: *Usage) -> s32 #foreign libc_build "getrusage";
Concat :: (left: string, right: string) -> string {
parts: [2]string = .[left, right]
return TextJoin(parts[:], "")
}
Number :: (value: s64) -> string {
bytes: [64]u8
return TextDetach(TextCopy(FormatInteger(value, bytes[:])))
}
PutText :: (doc: *JsonDocument, object: s32, key: string, value: string) {
JsonSet(doc, object, key, JsonNewStringCopy(doc, value))
}
PutInteger :: (doc: *JsonDocument, object: s32, key: string, value: s64) {
JsonSet(doc, object, key, JsonNewInteger(doc, value))
}
PutFloat :: (doc: *JsonDocument, object: s32, key: string, value: float64) {
JsonSet(doc, object, key, JsonNewNumber(doc, Float64Repr(value)))
}
Capture :: (arguments: []string, directory: string) -> string {
options: ProcessOptions = .{arguments = arguments, directory = directory,
capture_output = true, merge_error = true}
run: ProcessRun
if !RunProcess(options, *run) || run.code != 0 { return "" }
return TextTrim(BuilderFinish(run.output))
}
Fingerprint :: (repo: string) -> string {
source_diff: [12]string = .["git", "diff", "--binary", "HEAD", "--", "Makefile",
"cmd", "include", "std", "bootstrap", "scripts", "VERSION"]
scratch := JoinPath(repo, "build/scratch")
if !CreateDirectories(scratch) { return "" }
difference := JoinPath(scratch, Concat("compiler-build-source-", Concat(Number(ProcessId()), ".diff")))
if !WriteEntireFile(difference, Capture(source_diff[:], repo)) { return "" }
hash_command: [2]string = .["sha256sum", difference]
hash_text := Capture(hash_command[:], repo)
RemoveFile(difference)
return ifx hash_text.count >= 64 then hash_text[0:64] else ""
}
ShellRecipe :: (argc: s32, argv: **u8) -> s32 {
if argc < 4 || EnvironmentText("ZIRAN_BUILD_PROFILE") == "" { return 2 }
command: Vec(string)
VecPush(command, "/bin/sh")
for index: 2..argc - 1 { VecPush(command, TextFromCString(argv[index])) }
options: ProcessOptions = .{arguments = VecSlice(command, 0, command.count)}
run: ProcessRun
started := MonotonicNanoseconds()
ok := RunProcess(options, *run)
finished := MonotonicNanoseconds()
doc: JsonDocument
object := JsonNewObject(*doc)
PutInteger(*doc, object, "pid", ProcessId())
PutInteger(*doc, object, "started_ns", started)
PutInteger(*doc, object, "finished_ns", finished)
PutInteger(*doc, object, "wall_ns", finished - started)
PutInteger(*doc, object, "exit_code", run.code)
PutText(*doc, object, "command", TextJoin(VecSlice(command, 2, command.count), " "))
name := Concat(Concat(Number(ProcessId()), "-"), Concat(Number(started), ".json"))
record := JoinPath(EnvironmentText("ZIRAN_BUILD_PROFILE"), name)
if !WriteEntireFile(record, JsonWrite(*doc, object, JsonPythonStyle(2))) {
print("cannot write recipe profile: %\n", record)
return 1
}
return ifx ok then run.code else 127
}
CollectProfile :: (directory: string) -> bool {
names: Vec(string)
if !ListDirectory(directory, *names) { return false }
defer { FreeDirectoryNames(*names) }
collected: JsonDocument
array := JsonNewArray(*collected)
top: Vec(s32)
for name: VecSlice(names, 0, names.count) {
if !TextHasSuffix(name, ".json") { continue }
text, found := ReadEntireFile(JoinPath(directory, name))
document: JsonDocument
if !found || !JsonRead(*document, text) { return false }
node := JsonCopy(*collected, *document, document.root)
if node < 0 || !JsonAppend(*collected, array, node) { return false }
VecPush(top, node)
index := top.count - 1
value, value_ok := JsonInteger(*collected, JsonMember(*collected, node, "wall_ns"))
if !value_ok { return false }
while index > 0 {
previous, previous_ok := JsonInteger(*collected, JsonMember(*collected, top[index - 1], "wall_ns"))
if !previous_ok { return false }
if previous >= value { break }
top[index] = top[index - 1]
top[index - 1] = node
index -= 1
}
if top.count > 20 && !VecResize(top, 20) { return false }
}
summary: JsonDocument
if JsonCount(*collected, array) == 0 { return false }
slowest := JsonNewArray(*summary)
for node: VecSlice(top, 0, top.count) {
if !JsonAppend(*summary, slowest, JsonCopy(*summary, *collected, node)) { return false }
}
parent := PathParent(directory)
if !WriteEntireFile(JoinPath(parent, "recipes.json"), JsonWrite(*collected, array, JsonCompactStyle())) ||
!WriteEntireFile(JoinPath(parent, "slowest-recipes.json"), JsonWrite(*summary, slowest, JsonPythonStyle(2))) {
return false
}
for name: VecSlice(names, 0, names.count) {
if TextHasSuffix(name, ".json") && !RemoveFile(JoinPath(directory, name)) { return false }
}
return true
}
#scope_export
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc > 1 && TextFromCString(argv[1]) == "--shell" { return ShellRecipe(argc, argv) }
if argc == 3 && TextFromCString(argv[1]) == "--collect-profile" {
return ifx CollectProfile(TextFromCString(argv[2])) then 0 else 1
}
repo := PathParent(PathParent(EnvironmentText("ZIRAN_SCRIPT_FILE")))
if repo == "" || !IsFile(JoinPath(repo, "Makefile")) { repo = ResolvePath(".") }
if !IsFile(JoinPath(repo, "Makefile")) { print("run from the Ziran repository\n"); return 2 }
nproc: [1]string = .["nproc"]
cpus, count := IntegerPrefix(Capture(nproc[:], repo))
if count == 0 { cpus = 2 }
jobs := EnvironmentNumber("BUILD_QUEUE_JOBS", 0)
if jobs < 1 {
jobs = cpus / 2
if jobs < 2 { jobs = 2 }
if jobs > 16 { jobs = 16 }
}
output := JoinPath(repo, "bench/results/compiler-build")
profile := false
index: s32 = 1
while index < argc {
option := TextFromCString(argv[index])
if option == "--help" {
print("compiler_build.zi [--jobs N] [--out DIR] [--profile]\n")
return 0
}
if option == "--profile" { profile = true; index += 1; continue }
if index + 1 >= argc { print("% needs a value\n", option); return 2 }
value := TextFromCString(argv[index + 1])
if option == "--jobs" {
parsed, valid := TextInteger(value)
if !valid || parsed < 1 { print("--jobs must be positive\n"); return 2 }
jobs = parsed
} else if option == "--out" { output = value }
else { print("unknown argument: %\n", option); return 2 }
index += 2
}
if !CreateDirectories(output) { print("cannot create %\n", output); return 1 }
output = ResolvePath(output)
environment: [8]string = .["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
"DBUS_SESSION_BUS_ADDRESS", "MAKEFLAGS", "MFLAGS", "HARMONY_DESKTOP_RECOVERY=0",
"ZIRAN_BUILD_PROFILE"]
settings: Vec(string)
for value: environment { VecPush(settings, value) }
command: Vec(string)
fixed: [4]string = .["make", "-B", Concat("-j", Number(jobs)), "all"]
for value: fixed { VecPush(command, value) }
if profile {
directory := JoinPath(output, "recipes")
if !CreateDirectories(directory) { return 1 }
VecPush(settings, Concat("ZIRAN_BUILD_PROFILE=", directory))
self := ResolvePath(TextFromCString(argv[0]))
VecPush(command, Concat("SHELL=", self))
VecPush(command, ".SHELLFLAGS=--shell -c")
}
git: [3]string = .["git", "rev-parse", "HEAD"]
revision := Capture(git[:], repo)
status: [3]string = .["git", "status", "--porcelain"]
dirty := Capture(status[:], repo) != ""
source_fingerprint := Fingerprint(repo)
if source_fingerprint == "" { print("cannot fingerprint build inputs\n"); return 1 }
compiler: [2]string = .["cc", "--version"]
compiler_version := Capture(compiler[:], repo)
log := JoinPath(output, "build.log")
options: ProcessOptions = .{arguments = VecSlice(command, 0, command.count),
directory = repo, environment = VecSlice(settings, 0, settings.count),
output_path = log, merge_error = true}
print("Fresh rebuild: %, % jobs\n", TextJoin(VecSlice(command, 0, command.count), " "), jobs)
before: Usage; after: Usage
GetUsage(-1, *before)
run: ProcessRun
started := MonotonicNanoseconds()
ok := RunProcess(options, *run)
elapsed := MonotonicNanoseconds() - started
GetUsage(-1, *after)
source_fingerprint_after := Fingerprint(repo)
sources_unchanged := source_fingerprint_after == source_fingerprint
text, found := ReadEntireFile(log)
compilations: s64 = 0
lines := TextLines(text)
for line: VecSlice(lines, 0, lines.count) {
if TextContains(line, " -c -o ") { compilations += 1 }
}
doc: JsonDocument
object := JsonNewObject(*doc)
PutInteger(*doc, object, "schema_version", 2)
PutText(*doc, object, "implementation", "Ziran")
PutText(*doc, object, "command", TextJoin(VecSlice(command, 0, command.count), " "))
PutText(*doc, object, "revision", revision)
PutText(*doc, object, "tracked_build_source_diff_sha256", source_fingerprint)
PutText(*doc, object, "tracked_build_source_diff_sha256_after", source_fingerprint_after)
JsonSet(*doc, object, "build_sources_unchanged", JsonNewBool(*doc, sources_unchanged))
PutText(*doc, object, "compiler_version", compiler_version)
PutText(*doc, object, "bootstrap_cflags", ifx EnvironmentText("BOOTSTRAP_CFLAGS") == ""
then "-O0" else EnvironmentText("BOOTSTRAP_CFLAGS"))
PutText(*doc, object, "final_cflags", ifx EnvironmentText("CFLAGS") == ""
then "-O2" else EnvironmentText("CFLAGS"))
PutInteger(*doc, object, "exit_code", run.code)
PutFloat(*doc, object, "wall_seconds", cast(float64)elapsed / 1000000000.0)
PutFloat(*doc, object, "user_cpu_seconds", cast(float64)(after.user.seconds - before.user.seconds) +
cast(float64)(after.user.microseconds - before.user.microseconds) / 1000000.0)
PutFloat(*doc, object, "system_cpu_seconds", cast(float64)(after.system.seconds - before.system.seconds) +
cast(float64)(after.system.microseconds - before.system.microseconds) / 1000000.0)
PutInteger(*doc, object, "parallel_jobs", jobs)
PutInteger(*doc, object, "available_cpus", cpus)
PutInteger(*doc, object, "c_compile_commands", compilations)
JsonSet(*doc, object, "working_tree_dirty", JsonNewBool(*doc, dirty))
JsonSet(*doc, object, "recipe_profile", JsonNewBool(*doc, profile))
JsonSet(*doc, object, "measurement_valid", JsonNewBool(*doc,
ok && run.code == 0 && found && elapsed >= 0 && sources_unchanged))
PutText(*doc, object, "cache_state", "warm filesystem caches; make -B forces every build target")
PutText(*doc, object, "includes", "all native compiler tools and libziran.a")
PutText(*doc, object, "excludes", "queue waiting, benchmark compilation, tests, installation and website build")
PutText(*doc, object, "log", "build.log")
report := JsonWrite(*doc, object, JsonPythonStyle(2))
history_path := JoinPath(output, "samples.jsonl")
history, history_ok := ReadEntireFile(history_path)
unused history_ok
compact := JsonWrite(*doc, object, JsonCompactStyle())
if !WriteEntireFile(JoinPath(output, "latest.json"), Concat(report, "\n")) ||
!WriteEntireFile(history_path, Concat(history, Concat(compact, "\n"))) {
print("cannot retain benchmark report\n"); return 1
}
if profile && !CollectProfile(JoinPath(output, "recipes")) {
print("cannot collate recipe profiles\n"); return 1
}
print("%\n", report)
if !ok || !found { return 127 }
if !sources_unchanged { print("build inputs changed during measurement\n"); return 3 }
return run.code
}
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
# Run on Alpha: build-queue -- sh bench/compiler_kernel_benchmarks.sh [options]
set -eu
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS
unset SESSION_MANAGER XDG_SESSION_ID XDG_SESSION_TYPE ZIRAN_PROFILE
export YUE_DESKTOP_RECOVERY=0
exec python3 "$repo/bench/codec_kernels.py" "$@"
+1 -1
View File
@@ -140,7 +140,7 @@ def main():
*sorted(native.glob('*.c')), '-lm', '-o', binary], label, 'native-compile:c')
run([binary], label, 'run:c', oracle)
bundle = directory / form / 'program.zx'
run([binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'program:Answer', '-o', bundle, entry], label, 'bundle')
run([binaries/'zi2zx', '--root', root, '--entry', 'program:Answer', '-o', bundle, entry], label, 'bundle')
run([binaries/'zi2zx', 'run', bundle], label, 'run:vm', oracle)
(directory / 'fixture-hashes.json').write_text(json.dumps(
{str(path.relative_to(directory)): digest(path) for path in source.glob('*.zi')}, indent=2) + '\n')
+1 -1
View File
@@ -210,7 +210,7 @@ def main():
for form, root, file in [('source', output, entry), ('saved', output/'ir', output/'ir/counts.zir')]:
generated = output/form
repeated([binaries/'zi2c', '--root', root, '-o', generated, file], f'{form} emit C')
repeated([binaries/'zi2zx', 'bundle', '--root', root, '--entry', 'counts:Answer',
repeated([binaries/'zi2zx', '--root', root, '--entry', 'counts:Answer',
'-o', output/f'{form}.zx', file], f'{form} bundle')
host = generated/'host.c'
host.write_text('#include "counts.h"\n#include <stdio.h>\n#include <stdlib.h>\n'
+2 -2
View File
@@ -72,8 +72,8 @@ def main():
bundle = directory/'values.zx'
commands = [
[ROOT/'build/bin/zi2zir', '--root', directory, '-o', directory/'ir', entry],
[ROOT/'build/bin/zi2zx', 'bundle', '--root', directory, '--entry', 'values:Answer', '-o', bundle, entry],
[ROOT/'build/bin/zi2zx', 'bundle', '--root', directory/'ir', '--entry', 'values:Answer',
[ROOT/'build/bin/zi2zx', '--root', directory, '--entry', 'values:Answer', '-o', bundle, entry],
[ROOT/'build/bin/zi2zx', '--root', directory/'ir', '--entry', 'values:Answer',
'-o', directory/'saved.zx', directory/'ir/values.zir'],
]
for argv in commands:
+3 -3
View File
@@ -32,14 +32,14 @@ typedef struct State { size_t calls, count; } State;
typedef struct Context { size_t index; const char *function; State *state; } Context;
static int host_call(void *opaque, const char *module, const char *function,
const VmHostValue *args, int count, VmHostValue *result)
const HostValue *args, int count, HostValue *result)
{
Context *context = opaque;
assert(strcmp(module, "api") == 0 && strcmp(function, context->function) == 0);
assert(context->state->calls % context->state->count == context->index);
assert(count == 1 && args[0].kind == VM_HOST_INTEGER);
assert(count == 1 && args[0].kind == HOST_INTEGER);
context->state->calls++;
result->kind = VM_HOST_INTEGER;
result->kind = HOST_INTEGER;
result->integer = (int64_t)(((uint64_t)args[0].integer * 48271 + context->index + 1) & INT64_MAX);
return 1;
}
+34
View File
@@ -0,0 +1,34 @@
# JSON string scanning and parsing
The 0.4.2 JSON readers share an allocation-free scanner that examines complete
16-byte blocks through portable SIMD operations. Unescaped text remains a borrowed
view. Escape decoding, error positions, duplicate member behavior and secure
cleanup retain their existing policies. Short strings use the scalar tail.
`Simd.Load` and `Simd.LoadLow` accept immutable strings for `u8` vector lanes;
whole-load bounds checks apply on C, Go and the portable engine.
Run `sh bench/json_document.sh`. It builds through Zi2c with the normal native
executable defaults, constructs a 1 MiB ASCII string outside the timer and checks
every parse. Eleven batches of 64 parses report raw nanoseconds per parse and
symmetric inclusive-quartile 1.5×IQR exclusions. Process startup, compilation,
input construction and transport are excluded. The scanner-only comparison is
`bench/json_string_scan.zi`; it checks byte semantics before timing alternating
reference and vector scans. Repeated scans use an opaque start and a compiler
memory barrier to prevent loop hoisting.
The retained reports name the CPU, compiler inputs and exact runtime binaries.
These are warm-cache local measurements on a busy Ryzen 9 9950X Linux machine;
they do not establish performance on other architectures. Go and the portable
VM use the same lane semantics; native vector instructions depend on the target.
The corresponding Xcoder diagnostic also measures the original preserved Codex
V8 host. It times repeated `JSON.parse` inside that actual host and `JsonRead`
inside the sandboxed Zi2c cell, separately from the complete cell round trip.
The JavaScript timer has 1 ms resolution, amortized across 512 parses per batch.
Both validate payload length and its first and last bytes on every parse.
A parser improvement does not remove native sandbox creation and executable
startup. The original single-cell JSON benchmark must remain visible alongside
the direct parser result. Cold custom compilation is reported separately from
warm execution. Ordinary precompiled tool plans are a different workload and do
not invoke the custom-cell compiler or sandboxed executable.
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
ziran=${1:-$repo/build/bin/ziran}
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS
cd "$repo"
output="$repo/build/benchmarks/json-document"
"$ziran" build --target=c --root bench --entry json_document:main --exe -o "$output" bench/json_document.zi
nice -n 19 "$output/json_document"
+43
View File
@@ -0,0 +1,43 @@
// A direct JSON parser benchmark: construction, compilation and process startup
// are outside the timer. Every parse result is checked; input remains alive.
using V :: #import "std/vec"
using J :: #import "std/json_document"
using T :: #import "std/timer_linux"
#import "benchmark_statistics"
Measure :: (text: string, length: s64) -> float64 {
document: JsonDocument
defer JsonReset(*document)
started := MonotonicNanoseconds()
for iteration: 0..63 {
if !JsonRead(*document,text) { return -1.0 }
payload := JsonString(*document,JsonMember(*document,document.root,"payload"))
if payload.count != length || payload[0] != 120 || payload[length - 1] != 120 { return -1.0 }
}
return cast(float64)(MonotonicNanoseconds() - started) / 64.0
}
Numbers :: (values: []float64) { for i: 0..values.count - 1 { if i > 0 { print(",") }; print("%",values[i]) } }
Indices :: (values: []s64) { for i: 0..values.count - 1 { if i > 0 { print(",") }; print("%",values[i]) } }
#program_export
main :: () -> s32 {
bytes: Vec(u8)
prefix := "{\"payload\":\""
suffix := "\"}"
length: s64 = 1048576
if !VecResize(bytes,prefix.count + length + suffix.count) { return 1 }
for i: 0..prefix.count - 1 { bytes[i] = prefix[i] }
for i: 0..length - 1 { bytes[prefix.count + i] = 120 }
for i: 0..suffix.count - 1 { bytes[prefix.count + length + i] = suffix[i] }
text := TextView(bytes[:])
if Measure(text,length) <= 0.0 { return 2 }
samples: [11]float64
for i: 0..10 { samples[i] = Measure(text,length) }
result := BenchmarkAnalyze(samples[:])
if !result.valid { return 3 }
print("{\"case\":\"json_document_plain_1mib\",\"unit\":\"ns_per_parse\",\"rule\":\"symmetric inclusive 1.5xIQR\",\"raw\":[")
Numbers(samples[:]); print("],\"excluded\":["); Indices(result.excluded[:])
print("],\"median\":%}\n",result.median)
return 0
}
+90
View File
@@ -0,0 +1,90 @@
using V :: #import "std/vec"
using T :: #import "std/timer_linux"
using J :: #import "std/json_bytes"
#import "benchmark_statistics"
Reference :: (text: string, start: s64) -> s64 {
if start < 0 { return start }
at := start
while at < text.count {
byte := text[at]
if byte < 32 || byte == 34 || byte == 92 { break }
at += 1
}
return at
}
// Opaque native input and a compiler memory barrier prevent a pure repeated
// scan from being hoisted out of the measured loop. No instructions are needed.
Opaque :: (value: u64) -> u64
#asm("x86_64", "", "=r", "0", "memory", "volatile")
#asm("aarch64", "", "=r", "0", "memory", "volatile") {
return value
}
Check :: () -> bool {
bytes: [80]u8
for size: 0..79 {
for i: 0..79 { bytes[i] = 120 }
for position: 0..size {
for value: 0..255 {
bytes[position] = cast(u8)value
text := TextView(bytes[0:size])
for start: cast(s64)-1..size + 1 {
if Reference(text,start) != JsonStringRunEnd(text,start) {
print("scan mismatch: size % position % value % start %\n",size,position,value,start)
return false
}
}
}
bytes[position] = 120
}
}
return true
}
Measure :: (text: string, candidate: bool) -> float64 {
total: s64
started := MonotonicNanoseconds()
for n: 0..63 {
start := cast(s64)(Opaque(cast(u64)n) % cast(u64)7)
end := ifx candidate then JsonStringRunEnd(text,start) else Reference(text,start)
if end != text.count - 1 { return -1.0 }
total += end - start
}
elapsed := MonotonicNanoseconds() - started
if total != (text.count - 1) * 64 - 189 { return -1.0 }
return cast(float64)elapsed / 64.0
}
Numbers :: (values: []float64) {
for index: 0..values.count - 1 { if index > 0 { print(",") }; print("%",values[index]) }
}
Indices :: (values: []s64) {
for index: 0..values.count - 1 { if index > 0 { print(",") }; print("%",values[index]) }
}
#program_export
main :: () -> s32 {
if !Check() { return 1 }
bytes: Vec(u8)
if !VecResize(bytes,1048577) { return 2 }
for i: 0..1048575 { bytes[i] = 120 }
bytes[1048576] = 34
text := TextView(bytes[:])
before: [9]float64
after: [9]float64
if Measure(text,false) <= 0.0 || Measure(text,true) <= 0.0 { return 3 }
for sample: 0..8 {
if sample % 2 == 0 { before[sample]=Measure(text,false); after[sample]=Measure(text,true) }
else { after[sample]=Measure(text,true); before[sample]=Measure(text,false) }
}
old := BenchmarkAnalyze(before[:]); current := BenchmarkAnalyze(after[:])
if !old.valid || !current.valid { return 4 }
print("{\"case\":\"json_plain_string_1mib\",\"unit\":\"ns_per_scan\",\"rule\":\"symmetric inclusive 1.5xIQR\",\"reference_raw\":[")
Numbers(before[:]); print("],\"candidate_raw\":["); Numbers(after[:])
print("],\"reference_excluded\":["); Indices(old.excluded[:])
print("],\"candidate_excluded\":["); Indices(current.excluded[:])
print("],\"reference_median\":%,\"candidate_median\":%,\"speedup\":%}\n",old.median,current.median,old.median/current.median)
return 0
}
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Build Ziran-authored JSON/UTF-8 workloads and measure all four targets on Alpha.
Uses the existing target hosts and their independent checksum validation. This
is build/measurement orchestration; workload logic and oracles live in Ziran.
"""
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import platform
import random
import shutil
import sys
ROOT = Path(__file__).resolve().parents[1]
SOURCE_SITE = ROOT / 'site'
SITE = SOURCE_SITE
HARNESS_ROOT = Path(os.environ.get('ZIRAN_BENCH_HARNESS_ROOT', ROOT)).resolve()
sys.path.insert(0, str(HARNESS_ROOT / 'scripts'))
import site_targets as base
import site_target_platforms as hosts
from benchmark_samples import GATE_METHOD, HostGate
base.REPO = ROOT
base.SITE = SITE
hosts.ROOT = HARNESS_ROOT
hosts.SITE = base.SITE
CASES = [
('json_string_scan', 'JSON string scan · 16 KiB', 16418),
('json_parse', 'JSON parse · 16 KiB string', 16624),
('json_escaped', 'JSON parse · 128 escaped Unicode objects', 43904),
('json_write', 'JSON write · 256 mixed Unicode strings', 5446),
('json_quote_plain', 'JSON write · 64 KiB ASCII string', 65606),
('text_processing', 'UTF-8 · scan, search, replace and split · 18 KiB', 33788),
]
OUTPUT = SITE / 'generated/json-text'
WORK = ROOT / 'build/benchmarks/json-text'
HARNESSES = ['bench/json_text.py', 'scripts/site_target_platforms.py', 'scripts/site_targets.py',
'scripts/benchmark_samples.py', 'scripts/site_target_node.cjs',
'bench/site_target_host.c', 'bench/site_target_host.go', 'site/target-abi.js', 'site/target-measure.js']
def build(compiler, samples):
if platform.node() != 'alpha':
raise RuntimeError('Benchmark compilation and measurement require the selected Alpha physical host')
os.nice(19)
OUTPUT.mkdir(parents=True, exist_ok=True)
WORK.mkdir(parents=True, exist_ok=True)
env = hosts.environment()
env['PATH'] = str(Path.home() / '.local/bin') + ':' + env['PATH']
env['ZIRAN_JOBS'] = '1'
env['ZIRAN_LEARN'] = 'off'
# All helpers use the same scrubbed environment, including downstream Go.
hosts.environment = lambda: env.copy()
data = {'schema_version': 1, 'revision': hosts.run(['git', 'rev-parse', 'HEAD'], cwd=compiler), 'checks': False, 'learning': 'off', 'host': platform.node() + ' · ' + base.cpu_name(),
'measured_at': datetime.now(timezone.utc).isoformat(), 'samples': samples,
'compiler': {tool: base.sha(compiler / 'build/bin' / tool)
for tool in ('zi2c', 'zi2go', 'zi2zx', 'zx2wasm')},
'stdlib': {str(p.relative_to(compiler)): base.sha(p) for p in sorted((compiler / 'std').glob('*.zi'))},
'harnesses': {p: base.sha((ROOT if p == 'bench/json_text.py' else HARNESS_ROOT) / p) for p in HARNESSES},
'versions': {name: hosts.run(command, env=env).splitlines()[0] for name, command in
{'cc': ['cc', '--version'], 'go': ['go', 'version'], 'node': ['node', '--version']}.items()},
'methodology': hosts.metadata('', '', {}, samples)['methodology'].removesuffix(' Shared machines and uncontrolled clocks; no universal target ranking.') + GATE_METHOD, 'examples': []}
zx = WORK / 'zx-runner'
hosts.runtime_build('cc', compiler / 'build/libziran.a', zx,
['-include', HARNESS_ROOT / 'bench/site_target_backend.h',
'-DMATRIX_ZX_BACKEND=BUNDLE_BACKEND_NATIVE'])
data['zx_backend'] = 'native'
jobs = []
for name, title, expected in CASES:
source = ROOT / 'bench/json_text' / (name + '.zi')
public_source=OUTPUT/'sources'/source.name
public_source.parent.mkdir(parents=True,exist_ok=True)
shutil.copyfile(source,public_source)
row = {'id': name, 'title': title, 'source': public_source.relative_to(SITE).as_posix(),
'source_input':source.relative_to(ROOT).as_posix(), 'entry': 'Answer',
'expected': str(expected), 'stdout': '', 'source_sha256': base.sha(source), 'targets': {}}
for target in ('c', 'go', 'zx', 'wasm'):
directory = WORK / name / target
if directory.exists():
shutil.rmtree(directory)
directory.mkdir(parents=True, exist_ok=True)
common = ['--root', source.parent, '--module-path', compiler / 'std',
'--entry', name + ':Answer']
if target in ('c', 'go'):
command = [compiler / 'build/bin' / ('zi2' + target), '--no-main',
*(['--pkg', 'main'] if target == 'go' else []), *common,
'-o', directory, source]
commands = [command]
elif target == 'zx':
command = [compiler / 'build/bin/zi2zx', *common,
'-o', directory / (name + '.zx'), source]
commands = [command]
else:
wire = directory / (name + '.zx')
command = [compiler / 'build/bin/zi2zx', '--target', 'wasm', *common,
'-o', wire, source]
commands = [command, [compiler / 'build/bin/zx2wasm',
'-o', directory / (name + '.wasm'), wire]]
try:
for stage in commands:
hosts.run(stage, env=env)
except RuntimeError as error:
if target!='wasm' or 'outside the wasm execution subset' not in str(error):
raise
row['targets'][target]={'status':'unavailable','files':[], 'diagnostic':str(error)}
continue
public = OUTPUT / name / target
public.mkdir(parents=True, exist_ok=True)
emitted = []
for path in sorted(directory.rglob('*')):
if path.suffix not in ({'.c', '.h'} if target == 'c' else {'.go'} if target == 'go' else {'.' + target}):
continue
destination = public / path.relative_to(directory)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, destination)
emitted.append(hosts.public(destination))
cell = {'status': 'ok', 'files': emitted,
'command': '\n'.join(base.command_text(stage) for stage in commands)}
row['targets'][target] = cell
if target == 'c':
program = WORK / name / 'c-program'
cell['build_command'] = base.command_text(hosts.c_build(row, 'cc', program))
invoke = [program, '-', expected, samples]
elif target == 'go':
program = WORK / name / 'go-program'
build_command = ['go', 'build', '-p=1', '-o', program, *hosts.go_source(row, WORK / name / 'go-host')]
hosts.run(build_command, env=env)
cell['build_command'] = base.command_text(build_command)
invoke = [program, '-', expected, samples]
elif target == 'zx':
invoke = [zx, base.SITE / emitted[0]['path'], expected, samples]
else:
invoke = ['node', HARNESS_ROOT / 'scripts/site_target_node.cjs', base.SITE / emitted[0]['path'], expected, samples]
jobs.append((row, cell, invoke))
data['examples'].append(row)
random.Random(42).shuffle(jobs)
gate = HostGate()
timed_env = gate.environment(env)
for row, cell, command in jobs:
print('Measuring', row['id'], command[0], flush=True)
measured = hosts.measure(command, row, timed_env, gate)
cell['measurement'] = {**measured, 'command': base.command_text(command)}
(OUTPUT / 'matrix.json').write_text(json.dumps(data, indent=2) + '\n')
def check():
data = json.loads((OUTPUT / 'matrix.json').read_text())
assert data['schema_version'] == 1 and data['host'].startswith('alpha · ') and 3 <= data['samples'] <= 31
assert [(row['id'], row['expected']) for row in data['examples']] == [(name, str(oracle)) for name, _, oracle in CASES]
base.check_committed(base.published_revision(OUTPUT / 'matrix.json'), data['harnesses'], 'Benchmark harness')
base.check_committed(data['revision'], data['stdlib'], 'Standard library')
base.check_committed(data['revision'], {row['source_input']: row['source_sha256'] for row in data['examples']}, 'Workload')
for row in data['examples']:
assert base.sha(SITE / row['source']) == row['source_sha256']
assert set(row['targets']) == {'c', 'go', 'zx', 'wasm'}
for cell in row['targets'].values():
if cell['status']=='unavailable':
assert row['targets']['wasm'] is cell and 'outside the wasm execution subset' in cell['diagnostic'] and not cell['files']
continue
measured = cell['measurement']
assert measured['stdout_verified'] and hosts.summarize(measured, row['expected']) == measured
assert len(measured['batch_samples_ms']) == data['samples']
for file in cell['files']:
path = SITE / file['path']
assert path.stat().st_size == file['bytes'] and base.sha(path) == file['sha256']
print('Alpha JSON/text source, artifact, oracle and raw-sample local validation passed')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--compiler-root', type=Path, default=ROOT)
parser.add_argument('--site-dir', type=Path, default=SOURCE_SITE,
help='write generated artifacts and the results page under this directory')
parser.add_argument('--samples', type=int, default=11)
parser.add_argument('--check', action='store_true')
args = parser.parse_args()
SITE = args.site_dir.resolve()
base.SITE = hosts.SITE = SITE
OUTPUT = SITE / 'generated/json-text'
if not 3 <= args.samples <= 31:
parser.error('--samples must be between 3 and 31')
check() if args.check else build(args.compiler_root.resolve(), args.samples)
+28
View File
@@ -0,0 +1,28 @@
// Decode JSON: parse 128 objects with UTF-8, a control escape, a BMP escape and a
// surrogate pair. The independent oracle is 128 * (9 bytes + 206 + 128).
using V :: #import "vec"
using J :: #import "json_document"
input: Vec(u8);
Answer :: () -> s64 {
if input.count==0 {
if !BuilderAppend(input,"[") { return -1 }
for index: 0..127 {
if index>0 && !BuilderAppend(input,",") { return -2 }
if !BuilderAppend(input,"{\"label\":\"λ\\n\\u03bb\\uD83D\\uDE80\"}") { return -3 }
}
if !BuilderAppend(input,"]") { return -4 }
}
document: JsonDocument
defer JsonReset(*document)
if !JsonRead(*document,TextView(input[:]))||JsonCount(*document,document.root)!=128 { return -5 }
sum: s64
child:=JsonFirst(*document,document.root)
while child>=0 {
text:=JsonString(*document,JsonMember(*document,child,"label"))
if text.count!=9 { return -6 }
sum+=text.count+cast(s64)text[0]+cast(s64)text[text.count-1]
child=JsonNext(*document,child)
}
return sum
}
+19
View File
@@ -0,0 +1,19 @@
// Parse JSON: materialize a 16 KiB JSON string. The input is
// prepared once, before measured calls; the result consumes its bytes.
using V :: #import "vec"
using J :: #import "json_document"
input: Vec(u8);
Answer :: () -> s64 {
if input.count==0 {
if !BuilderAppend(input,"{\"payload\":\"") { return -1 }
for index: 0..16383 { if !VecPush(input,120) { return -2 } }
if !BuilderAppend(input,"\"}") { return -3 }
}
document: JsonDocument
defer JsonReset(*document)
if !JsonRead(*document,TextView(input[:])) { return -4 }
payload:=JsonString(*document,JsonMember(*document,document.root,"payload"))
if payload.count!=16384 { return -5 }
return payload.count+cast(s64)payload[0]+cast(s64)payload[payload.count-1]
}
+12
View File
@@ -0,0 +1,12 @@
// Quote ASCII: serialize 64 KiB and check the full output size and ends;
// input generation is excluded after the first warmup call.
using V :: #import "vec"
using J :: #import "json_quote"
input: Vec(u8);
Answer :: () -> s64 {
if input.count==0 { if !VecResize(input,65536) { return -1 }; for index: 0..65535 { input[index]=120 } }
output: Vec(u8)
if !JsonQuoteInto(*output,TextView(input[:]),true)||output.count!=65538||output[1]!=120||output[65536]!=120 { return -2 }
return output.count+cast(s64)output[0]+cast(s64)output[output.count-1]
}
+16
View File
@@ -0,0 +1,16 @@
// Scan a JSON string: validate its span without building a document tree.
// The closing quote follows 16 KiB of ASCII; consume the complete span.
using V :: #import "vec"
Json :: #import "json_bytes"
input: Vec(u8);
Answer :: () -> s64 {
if input.count==0 {
if !VecResize(input,16385) { return -1 }
for index: 0..16383 { input[index]=120 }
input[16384]=34
}
end:=Json.JsonStringRunEnd(TextView(input[:]),0)
if end!=16384||input[end]!=34 { return -2 }
return end+cast(s64)input[end]
}
+13
View File
@@ -0,0 +1,13 @@
// Quote Unicode: write 256 repetitions of ASCII, a BMP scalar and an astral scalar with
// ensure-ASCII semantics: 256 * (3 + 6 + 12) + two quotation marks.
using V :: #import "vec"
using J :: #import "json_quote"
input: Vec(u8);
Answer :: () -> s64 {
if input.count==0 { for index: 0..255 { if !BuilderAppend(input,"abcλ😀") { return -1 } } }
output: Vec(u8)
if !JsonQuoteInto(*output,TextView(input[:]),true)||output.count!=5378||output[0]!=34||output[5377]!=34 { return -2 }
if output[4]!=92||output[5]!=117||output[10]!=92 { return -3 }
return output.count+cast(s64)output[0]+cast(s64)output[output.count-1]
}
+18
View File
@@ -0,0 +1,18 @@
// Process UTF-8: search, replace, split and count scalars. Input
// preparation happens during warmup; output allocation stays in each call.
using V :: #import "vec"
using T :: #import "text_tools"
Utf8 :: #import "utf8"
input: Vec(u8);
Answer :: () -> s64 {
if input.count==0 { for index: 0..1023 { if !BuilderAppend(input,"alpha λ😀 beta\n") { return -1 } } }
text:=TextView(input[:])
found:=TextFind(text,"beta\n",text.count-18)
if found!=text.count-5||Utf8.Count(text)!=14336 { return -2 }
rewritten:=TextReplace(text,"alpha","A")
if rewritten.count!=14336 { return -3 }
lines:=TextSplit(rewritten,"\n")
if lines.count!=1025||lines[0]!="A λ😀 beta"||lines[1024]!="" { return -4 }
return found+rewritten.count+lines.count
}
+59
View File
@@ -0,0 +1,59 @@
# Exact portable square-root normalization
`std/math.zi` normalizes a finite positive input to a mantissa in `[1, 2)`.
After its existing 64-bit exponent steps, the residual exponent is in
`[0, 63]`. Six descending comparisons against `2^32`, `2^16`, `2^8`,
`2^4`, `2^2`, and `2^1` replace the old loop that constructed those powers
with 63 multiplications. Each selected reciprocal is an exactly representable
power of two. The normalized result is at least one, so replacing division by
that power with multiplication by its reciprocal cannot underflow, overflow,
or introduce rounding. The mantissa and exponent remain identical.
`Sqrt` keeps its six Newton iterations, neighboring-result selection and
exceptional-input paths. This is not a hardware-sqrt substitution: its existing
one-ULP accuracy contract, rather than correctly rounded libm behavior, remains
unchanged. No allocation, compiler lowering, runtime feature or host shim is
introduced. `Log`, which shares `MathSplit`, benefits from the same change.
## Local tests
Run from the canonical checkout, using an existing toolchain:
```sh
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
build/bin/check-runner --bin-dir "$PWD/build/bin" --jobs 1 --filter math
```
Set `CC` to an existing managed compiler wrapper when compilation is assigned
to another machine. Both math shell tests honor it. `math_sqrt.sh` tests exact
agreement with the pre-change algorithm for one million deterministic IEEE
patterns, every normal exponent boundary, all subnormal powers and their
neighbors, signed zeros, NaNs, infinities and negative-domain inputs. Native
source and saved IR both run the full set. Portable source and saved IR run
the same bounded edge set and produce byte-identical bundles. The existing
`math_float64.sh` also checks all 21 elementary functions against libm and in
the portable engine. NaN tests compare classification, not payload bits.
## Repeatable microbenchmark
```sh
build-queue -- env -u DISPLAY -u WAYLAND_DISPLAY \
sh bench/math_sqrt.sh "$PWD/build/bin/ziran"
```
The benchmark compiles the old algorithm from `tests/spec/math_sqrt_reference.zi`
and the current standard library together at `-O2`, without fast-math or LTO.
It first checks exact agreement on its inputs. Each sample makes 1,024,000
calls; a warmup precedes nine samples, alternating baseline/candidate order.
It covers squared-length-like values in `(0, 16]` and positive normal values
spread across binary64 exponents. Checksums keep the calls observable. Raw
nanoseconds per call and excluded sample indices are printed. Both algorithms
use the same symmetric 1.5-times-IQR rule with inclusive interpolated quartiles.
The November 11, 2026 local result is retained in
`results/math-sqrt-2026-11-11.json`: geometry median 32.04 to 11.44 ns/call
(2.80x); exponent-spread median 57.44 to 25.74 ns/call (2.23x). C objects were
compiled on physical Alpha with two workers and an 8 GiB managed limit;
timing ran locally on the Ryzen 9 9950X desktop. These are microbenchmarks,
not actual-room frame timings or proof of 60 fps. Parent-owned renderer
reference-frame and application integration validation remain separate.
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
ziran=${1:-$repo/build/bin/ziran}
work="$repo/build/math-sqrt-bench"
mkdir -p "$work"
unset DISPLAY WAYLAND_DISPLAY
cd "$repo"
printf 'source_revision '; git rev-parse HEAD
sha256sum std/math.zi tests/spec/math_sqrt_reference.zi bench/math_sqrt.zi
"$ziran" build --target=c --root bench --module-path std --module-path tests/spec \
-o "$work/c" bench/math_sqrt.zi
"${CC:-cc}" -std=c11 -O2 -iquote "$work/c" "$work/c"/*.c -lm -o "$work/math_sqrt"
"$work/math_sqrt"
+68
View File
@@ -0,0 +1,68 @@
#import "std/math"
#import "std/binary"
#import "std/timer_linux"
#import "math_sqrt_reference"
#import "benchmark_statistics"
Measure :: (values: []float64, reference: bool) -> float64 {
total: float64 = 0.0
started := MonotonicNanoseconds()
for repeat: 0..999 {
for value: values {
if reference { total += ReferenceSqrt(value) }
else { total += Sqrt(value) }
}
}
elapsed := MonotonicNanoseconds() - started
print("checksum %\n", total)
return cast(float64)elapsed / (cast(float64)values.count * 1000.0)
}
Report :: (name: string, samples: []float64) -> float64 {
result := BenchmarkAnalyze(samples)
for index: cast(s64)0..samples.count - 1 { print("% sample % ns_per_call %\n", name, index, samples[index]) }
for index: result.excluded { print("% excluded_index %\n", name, index) }
print("% median_ns_per_call %\n", name, result.median)
if !result.valid { return 0.0 }
return result.median
}
Run :: (name: string, values: []float64) -> bool {
baseline: [9]float64
candidate: [9]float64
Measure(values, true)
Measure(values, false)
for sample: 0..8 {
if sample % 2 == 0 {
baseline[sample] = Measure(values, true)
candidate[sample] = Measure(values, false)
} else {
candidate[sample] = Measure(values, false)
baseline[sample] = Measure(values, true)
}
}
print("distribution %\n", name)
before := Report("reference", baseline[:])
after := Report("candidate", candidate[:])
print("speedup %\n", before / after)
return before > 0.0 && after > 0.0
}
#program_export
main :: () -> s32 {
geometry: [1024]float64
spread: [1024]float64
state: u64 = 88172645463325252
for index: 0..1023 {
state ^= state << cast(u64)13
state ^= state >> cast(u64)7
state ^= state << cast(u64)17
geometry[index] = 0.000001 + cast(float64)(state & 0xffffff) / 16777216.0 * 16.0
bits := ((cast(u64)index * 2045 / 1023 + 1) << cast(u64)52) | (state & 0x000fffffffffffff)
spread[index] = Float64FromBits(bits)
if Sqrt(geometry[index]) != ReferenceSqrt(geometry[index]) ||
Sqrt(spread[index]) != ReferenceSqrt(spread[index]) { return 1 }
}
if !Run("geometry_0_to_16", geometry[:]) || !Run("normal_exponent_spread", spread[:]) { return 2 }
return 0
}
+29
View File
@@ -0,0 +1,29 @@
// Emit the same source/FFI fixture exercised by the native cache regression.
#import "native_test"
#import "native_cache_support"
#import "check_support"
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file_tree_linux"
#import "std/json_document"
#import "std/text_tools"
using Vectors :: #import "std/vec"
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 3 { print("pass compiler and fixture directory\n"); return 2 }
test: NativeTest
test.repo = TextDetach(ResolvePath(PathParent(PathParent(EnvironmentText("ZIRAN_SCRIPT_FILE")))))
test.ziran = TextDetach(ResolvePath(TextFromCString(argv[1])))
directory := TextFromCString(argv[2])
if !NativeAssert(*test, CreateDirectories(directory), "create requested native fixture directory") { return 1 }
test.work = TextDetach(ResolvePath(directory)); output := CheckPath(test.work, "out with spaces"); compiler := NativeCompiler()
command := string.[test.ziran, "build", "--target=c", "--exe", "--entry", "app:Answer", "--diagnostics=json", "--root", test.work, "-o", output, CheckPath(test.work, "app.zi")]
fixture := CacheFixture.{*test, command[:], compiler, output}
if !CachePrepare(fixture) { return 1 }
document: JsonDocument; document.root = JsonNewObject(*document)
CheckPut(*document, document.root, "out", output); CheckPut(*document, document.root, "headers", CheckPath(test.work, "headers"))
arguments := JsonNewArray(*document); for argument: command { JsonAppend(*document, arguments, JsonNewString(*document, argument)) }; JsonSet(*document, document.root, "command", arguments)
print("%\n", JsonWrite(*document, document.root, JsonCompactStyle()))
return 0
}
-45
View File
@@ -1,45 +0,0 @@
/* Build the same insertion workload with the current or a preserved cache
* implementation. This is a container benchmark, not total compiler time. */
#include "../cmd/zir-c/zir_c_cache.c"
#include <assert.h>
#include <inttypes.h>
static uint64_t nanoseconds(void)
{
struct timespec value;
assert(clock_gettime(CLOCK_MONOTONIC, &value) == 0);
return (uint64_t)value.tv_sec * UINT64_C(1000000000) + (uint64_t)value.tv_nsec;
}
int main(int argc, char **argv)
{
assert(argc == 3);
int count = atoi(argv[1]), rounds = atoi(argv[2]);
assert(count > 0 && count <= MAX_ITEMS && !(count & (count - 1)) && rounds > 0);
char **input = calloc((size_t)count, sizeof(*input));
assert(input);
for(int i = 0; i < count; i++)
assert(asprintf(&input[i], "/shared/project/include/long/common/path/component/header-%08d.h", (i * 1297) % count) >= 0);
uint64_t total = 0, checksum = 0;
for(int round = 0; round < rounds; round++) {
Names names = {0};
uint64_t started = nanoseconds();
for(int i = 0; i < count; i++) assert(add_name(&names, input[i]));
for(int i = count - 1; i >= 0; i--) assert(add_name(&names, input[i]));
assert(names.count == count);
checksum = UINT64_C(14695981039346656037);
for(int i = 0; i < count; i++) {
assert(!strcmp(names.items[i], input[i]));
for(const unsigned char *p = (const unsigned char *)names.items[i]; *p; p++)
checksum = (checksum ^ *p) * UINT64_C(1099511628211);
checksum *= UINT64_C(1099511628211);
}
free_names(&names);
total += nanoseconds() - started;
}
for(int i = 0; i < count; i++) free(input[i]);
free(input);
printf("{\"count\":%d,\"rounds\":%d,\"total_ns\":%" PRIu64 ",\"checksum\":%" PRIu64 "}\n",
count, rounds, total, checksum);
return 0;
}
-88
View File
@@ -1,88 +0,0 @@
#!/usr/bin/env python3
"""Measure the native cache's ordered name collection against a Git revision."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import random
import shutil
import statistics
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def expected_checksum(count):
value = 14695981039346656037
for index in range(count):
key = f'/shared/project/include/long/common/path/component/header-{(index * 1297) % count:08d}.h'
for byte in key.encode()+b'\0': value = ((value ^ byte) * 1099511628211) & ((1 << 64)-1)
return value
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', type=Path, required=True)
parser.add_argument('--before-ref', required=True)
parser.add_argument('--repetitions', type=int, default=15)
args = parser.parse_args()
if args.repetitions < 1: parser.error('repetitions must be positive')
out = args.out.resolve()
if out.exists(): parser.error('archive records and remove inactive outputs before reuse')
out.mkdir(parents=True)
env = {k:v for k,v in os.environ.items() if k not in ('DISPLAY','WAYLAND_DISPLAY','XAUTHORITY','DBUS_SESSION_BUS_ADDRESS','ZIRAN_PROFILE')}
env['YUE_DESKTOP_RECOVERY']='0'
compiler, timer = shutil.which('cc'), []
if tool := shutil.which('time'):
probe = subprocess.run([tool,'--version'],capture_output=True,text=True)
if probe.returncode == 0 and 'GNU' in probe.stdout+probe.stderr: timer = [tool]
if not timer and (tool := shutil.which('busybox')):
probe = subprocess.run([tool,'time','--help'],capture_output=True,text=True)
if '-f FMT' in probe.stdout+probe.stderr and '-o FILE' in probe.stdout+probe.stderr: timer = [tool,'time']
if not compiler or not timer: parser.error('requires cc and GNU or BusyBox time')
ref = subprocess.check_output(['git','rev-parse','--verify',args.before_ref+'^{commit}'],cwd=ROOT,text=True).strip()
old = subprocess.check_output(['git','show',ref+':cmd/zir-c/zir_c_cache.c'],cwd=ROOT,text=True)
source = (ROOT/'bench/native_cache_names.c').read_text()
marker = '#include "../cmd/zir-c/zir_c_cache.c"'
assert source.count(marker)==1
common = [compiler,'-O2','-D_GNU_SOURCE','-std=c11','-Iinclude','-Icmd/zir','-Ibootstrap/compiler_ir','-Icmd/zir-c']
subprocess.run([*common,'-x','c','-','-x','none','build/libziran.a','-lm','-pthread','-o',str(out/'before')],input=source.replace(marker,old),text=True,cwd=ROOT,env=env,check=True)
subprocess.run([*common,'bench/native_cache_names.c','build/libziran.a','-lm','-pthread','-o',str(out/'current')],cwd=ROOT,env=env,check=True)
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
meta = dict(schema=1,platform=platform.platform(),before_ref=ref,repetitions=args.repetitions,measurement_launcher=timer,
cpu_affinity=sorted(os.sched_getaffinity(0)) if hasattr(os,'sched_getaffinity') else None,
compiler_version=subprocess.check_output([compiler,'--version'],text=True),
before_cache_sha256=hashlib.sha256(old.encode()).hexdigest(),current_cache_sha256=sha(ROOT/'cmd/zir-c/zir_c_cache.c'),
benchmark_c_sha256=sha(ROOT/'bench/native_cache_names.c'),benchmark_py_sha256=sha(Path(__file__)),
binaries={label:sha(out/label) for label in ('before','current')},
caveats=['Ordered-name insertion/duplicate checking, content verification and cleanup in one native process; not whole compiler time.',
'Common path prefixes and large sets stress the previous linear duplicate scans and repeated array growth.',
'Process RSS includes the harness and its inputs; it does not isolate container allocations or whole compiler memory.'])
rows=[]
for count in (16,256,2048,8192):
rounds=max(1,8192//count);expected=expected_checksum(count)
for repetition in range(args.repetitions+1):
order=['before','current'];random.Random(count+repetition).shuffle(order)
for label in order:
rss=out/'rss.txt'
result=subprocess.run([*timer,'-f','%M','-o',str(rss),str(out/label),str(count),str(rounds)],env=env,capture_output=True,text=True,check=True,timeout=60)
sample=json.loads(result.stdout)
assert sample['count']==count and sample['rounds']==rounds and sample['checksum']==expected,sample
row=dict(count=count,rounds=rounds,variant=label,repetition=repetition,warmup=repetition==0,
container_ms=sample['total_ns']/rounds/1e6,max_rss_kib=int(rss.read_text()),checksum=expected)
rows.append(row)
with (out/'samples.jsonl').open('a') as f:f.write(json.dumps(row)+'\n')
print('validated ordered names '+str(count),flush=True)
summary=[]
for count in (16,256,2048,8192):
for label in ('before','current'):
values=[row for row in rows if row['count']==count and row['variant']==label and not row['warmup']]
summary.append(dict(count=count,variant=label,samples=len(values),median_container_ms=statistics.median(row['container_ms'] for row in values),median_max_rss_kib=statistics.median(row['max_rss_kib'] for row in values)))
(out/'metadata.json').write_text(json.dumps(meta,indent=2)+'\n')
(out/'summary.json').write_text(json.dumps(summary,indent=2)+'\n')
print(f'{sum(not row["warmup"] for row in rows)} ordered-name samples validated against independent checksums.',flush=True)
if __name__=='__main__': main()
+1 -1
View File
@@ -49,7 +49,7 @@ def generate(source, groups=GROUPS, width=WIDTH, consumers=CONSUMERS, read_last=
def host_source(groups=GROUPS, width=WIDTH):
GROUPS, WIDTH = groups, width
size = GROUPS * WIDTH * 4
return ('#include "common.h"\n'
return ('#include <stddef.h>\n#include "common.h"\n'
f'_Static_assert(sizeof(Bundle) == {size}, "full foreign ABI");\n'
f'_Static_assert(offsetof(Bundle, g{GROUPS - 1}.l{WIDTH - 1}.value) == {size - 4}, "last ABI field");\n'
f'uint32_t prepare(Bundle *value, uint32_t seed) {{ value->g{GROUPS - 1}.l{WIDTH - 1}.value = seed + 3; '
+25 -23
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env python3
"""Measure complete native builds under controlled probe-version interleaving."""
import argparse
import ast
import hashlib
import json
import os
@@ -11,7 +10,6 @@ import shlex
import shutil
import statistics
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
@@ -40,33 +38,36 @@ def main():
if not compiler or not timer: parser.error('requires cc and GNU or BusyBox time')
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
# Reuse the regression's real C compiler shim and five-object FFI fixture.
# Execute only its setup, before the first build or any test mutations.
test = ROOT/'tests/native_build_cache_test.py'
tree = ast.parse(test.read_text(),str(test))
setup = []
for node in tree.body:
if isinstance(node,ast.Expr) and isinstance(node.value,ast.Call) and isinstance(node.value.func,ast.Name) and node.value.func.id == 'build': break
setup.append(node)
assert len(setup) < len(tree.body)
helper = [node.value.args[0].value for node in tree.body
if isinstance(node,ast.Expr) and isinstance(node.value,ast.Call) and isinstance(node.value.func,ast.Attribute)
and isinstance(node.value.func.value,ast.Name) and node.value.func.value.id == 'proxy_source' and node.value.func.attr == 'write_text']
assert len(helper) == 1
# The native regression and benchmark share one Ziran fixture producer.
# Its real C compiler shim is ordinary input data, not a Python test import.
test = ROOT/'bench/native_cache_fixture.zi'
proxy_source = ROOT/'tests/fixtures/native_cache/proxy.c.in'
shim = out/'gcc'
subprocess.run([compiler,'-D_GNU_SOURCE','-DREVISION=0','-DREAL_CC='+json.dumps(compiler),'-x','c','-','-o',shim],input=helper[0],text=True,env=env,check=True)
subprocess.run([compiler,'-D_GNU_SOURCE','-DREVISION=0','-DREAL_CC='+json.dumps(compiler),'-x','c',proxy_source,'-o',shim],env=env,check=True)
cases = {}
prefix = '\tcompiled by GNU C version 99.0.0, '
banner = 'GNU assembler version 2.44 (target) using BFD version 2.44\n'
for label,tools in [('before',args.before_bin_dir.resolve()),('current',args.bin_dir.resolve())]:
work = out/label; work.mkdir()
scope = {'__file__':str(test),'__name__':'fixture'}
original = sys.argv
try:
sys.argv = [str(test),str(tools/'ziran'),str(work)]
exec(compile(ast.Module(body=setup,type_ignores=[]),str(test),'exec'),scope)
finally: sys.argv = original
scope['env'].update(env)
prepared = subprocess.run([args.bin_dir.resolve()/'ziran', 'run', '--target=c',
'--root', ROOT/'bench', '--module-path', ROOT/'tests', test, '--', tools/'ziran', work],
env=env,capture_output=True,text=True,check=True)
record = json.loads(prepared.stdout)
output, headers = Path(record['out']), Path(record['headers'])
scope = dict(out=output,headers=headers,command=record['command'],env=dict(env))
def objects(output=output):
return {str(path.relative_to(output/'.objects')): (path.stat().st_mtime_ns,path.stat().st_ino)
for path in (output/'.objects').rglob('*.o')}
def build(answer,changed=None,scope=scope,objects=objects):
before=objects()
result=subprocess.run(scope['command'],env=scope['env'],capture_output=True,text=True,timeout=30)
assert result.returncode==0,result.stderr
for line in result.stderr.splitlines(): assert json.loads(line)['code']=='zir_c.toolchain',line
assert subprocess.run([scope['out']/'app'],env=scope['env']).returncode==answer
updates={name for name,value in objects().items() if before.get(name)!=value}
if changed is not None: assert updates==changed,(updates,changed)
return updates
scope.update(objects=objects,build=build)
scope['env'].update(CC=str(shim),CFLAGS='-O2 -isystem '+str(scope['headers']),LDFLAGS='-L'+str(work),LDLIBS='-lbase')
probe = subprocess.run([compiler,*shlex.split(scope['env']['CFLAGS']),'-I',scope['out'],'-pthread','-I',ROOT/'include','-pipe','-v','-x','c','-c','/dev/null','-o','/dev/null'],env=scope['env'],capture_output=True,text=True,check=True).stderr
saved = work/'probe.txt';scope['env']['CACHE_PROBE_TEXT'] = str(saved)
@@ -117,6 +118,7 @@ def main():
assert all(identity.values()),identity
metadata=dict(schema=1,repetitions=args.repetitions,compiler=compiler,compiler_version=subprocess.check_output([compiler,'--version'],text=True),measurement_launcher=timer,
cpu_affinity=sorted(os.sched_getaffinity(0)) if hasattr(os,'sched_getaffinity') else None,generator_sha256=sha(Path(__file__)),fixture_sha256=sha(test),shim_sha256=sha(shim),
fixture_sources_sha256={str(path.relative_to(ROOT)):sha(path) for path in [test,ROOT/'tests/native_cache_support.zi',proxy_source]},
source_hashes={str(p.relative_to(ROOT)):sha(p) for folder in ['cmd','std','include'] for p in (ROOT/folder).rglob('*') if p.is_file() and p.suffix in ['.c','.h','.zi']},
tool_hashes={label:{name:sha(tools/name) for name in ['ziran','zi2c']} for label,tools in [('before',args.before_bin_dir.resolve()),('current',args.bin_dir.resolve())]},
flags={label:{k:case['scope']['env'][k] for k in ['CC','CFLAGS','LDFLAGS','LDLIBS']} for label,case in cases.items()},output_identity=identity,
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Matched frozen-runtime A/B on the existing wasm_tier kernels (physical Alpha)."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import platform
import random
import subprocess
import sys
import wasm_tier as tier
from benchmark_samples import GATE_METHOD, HostGate, summarize_samples
def identity(path):
path = Path(path).resolve()
digest = hashlib.sha256()
with path.open('rb') as source:
for block in iter(lambda: source.read(1024 * 1024), b''):
digest.update(block)
return {'path': str(path), 'sha256': digest.hexdigest(), 'bytes': path.stat().st_size}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--before', type=Path, required=True)
parser.add_argument('--after', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
virt = subprocess.run(['systemd-detect-virt'], capture_output=True, text=True)
if platform.node().split('.')[0].lower() != 'alpha' or virt.returncode != 1 or virt.stdout.strip() != 'none':
parser.error('measurement requires physical Alpha')
if args.output.exists():
parser.error('output already exists')
os.environ['ZIRAN_LEARN'] = 'off'
env = HostGate.environment(tier.platforms.environment())
gate = HostGate()
rng = random.Random(29)
kernels, artifacts, oracles = {}, {}, {}
for name in tier.KERNELS:
bundle = tier.WORK / (name + '.zx')
output = subprocess.run([tier.tool('zi2zx'), 'run', '--backend', 'engine', bundle],
env=env, check=True, capture_output=True, text=True).stdout
expected = '0' if name == 'Printing' else output.splitlines()[-1]
stdout = output if name == 'Printing' else output[:output.rstrip('\n').rfind('\n') + 1]
example = {'id': name, 'expected': expected, 'stdout': stdout}
commands = {'c': [tier.WORK / (name + '-c'), '-', expected],
'before': [args.before, bundle, expected], 'after': [args.after, bundle, expected]}
kernels[name] = (example, commands)
oracles[name] = example
artifacts[name] = {'bundle': identity(bundle), 'c': identity(commands['c'][0])}
artifacts.update(before=identity(args.before), after=identity(args.after),
engine=identity(tier.tool('zi2zx')), driver=identity(__file__))
runs = {name: {label: [] for label in ('c', 'before', 'after')} for name in kernels}
order = []
for round_index in range(11):
jobs = [(name, label) for name in kernels for label in runs[name]]
rng.shuffle(jobs)
for name, label in jobs:
example, commands = kernels[name]
command = [*commands[label], '11']
measured = tier.platforms.measure(command, example, env, gate)
measured['command'] = [str(part) for part in command]
runs[name][label].append(measured)
order.append([round_index, name, label])
print(f'round {round_index + 1}/11 complete', flush=True)
summary = {name: {label: summarize_samples([run['execution_ms'] for run in values])
for label, values in labels.items()} for name, labels in runs.items()}
report = {'host': platform.node(), 'virtualization': virt.stdout.strip(),
'measured_at': datetime.now(timezone.utc).isoformat(), 'learning': 'off',
'rounds': 11, 'samples_per_run': 11, 'seed': 29, 'artifacts': artifacts,
'oracles': oracles, 'order': order, 'runs': runs, 'summary': summary,
'methodology': '11 shuffled matched rounds; identical bundles, frozen static runtime runners and C references. '
'Each run warms 150 ms then measures 11 calibrated batches; every checksum and stdout is verified '
'against the instruction engine. Symmetric inclusive 1.5xIQR applied within each run and across '
'run medians; raw samples and excluded indices retained. ' + GATE_METHOD}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + '\n')
print('kernel | C us | before us | after us | after/before')
for name, labels in summary.items():
c, before, after = (labels[label]['median_ms'] * 1000 for label in ('c', 'before', 'after'))
print(f'{name} | {c:.3f} | {before:.3f} | {after:.3f} | {after / before:.4f}')
if __name__ == '__main__':
main()
+1 -1
View File
@@ -417,7 +417,7 @@ def main():
if not equality[target]:
raise AssertionError(f'{target} source and saved IR emission differ')
for kind, root, source in [('source', FIX, ZI), ('saved', IR, SAVED)]:
repeated([BIN / 'zi2zx', 'bundle', '--root', root,
repeated([BIN / 'zi2zx', '--root', root,
'--module-path', ROOT / 'std', '--entry', 'records:Answer',
'-o', OUT / f'{kind}.zx', source], 'ziran', f'{kind} to zx')
if (OUT / 'source.zx').read_bytes() != (OUT / 'saved.zx').read_bytes():
@@ -0,0 +1,2 @@
{"asset_bytes":1000000,"bundle_bytes":1000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[37,194,20,27,176,58,156,51,209,194,4,13,69,223,87,93,255,20,92,193,155,239,170,211,42,234,171,211,37,3,109,169],"content_identity":[108,103,45,1,245,77,89,231,112,223,169,153,115,163,113,48,113,31,49,89,3,223,68,96,77,140,35,110,78,198,249,239],"samples_ns":[3903304,3873521,4031240,4568817,6078163,3885425,3876850,3944065,3884335,3928744,3890097]}
{"asset_bytes":75000000,"bundle_bytes":75000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[140,146,218,49,232,156,101,169,130,212,253,247,203,195,97,51,232,190,195,46,219,94,140,192,154,83,197,124,198,90,126,67],"content_identity":[64,40,38,203,59,101,215,125,236,47,86,79,228,16,218,27,45,233,227,11,167,141,242,136,122,26,95,251,42,38,194,28],"samples_ns":[291416430,283968212,291549050,298719639,289953063,292520883,291144700,294325959,288278339,295167755,294985478]}
@@ -0,0 +1,2 @@
{"asset_bytes":1000000,"bundle_bytes":1000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"samples_ns":[7222309,6136048,5406500,5068298,5066495,5061515,5073100,5063878,5085195,5071416,5097492]}
{"asset_bytes":75000000,"bundle_bytes":75000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"samples_ns":[370829279,386735547,372795918,369875583,369998273,368584362,374932839,374786265,367915773,369741776,369379626]}
@@ -0,0 +1,2 @@
{"asset_bytes":1000000,"bundle_bytes":1000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[37,194,20,27,176,58,156,51,209,194,4,13,69,223,87,93,255,20,92,193,155,239,170,211,42,234,171,211,37,3,109,169],"content_identity":[108,103,45,1,245,77,89,231,112,223,169,153,115,163,113,48,113,31,49,89,3,223,68,96,77,140,35,110,78,198,249,239],"samples_ns":[4990679,4987763,4987935,5142164,5027256,5087958,5318701,5087849,5219289,5103524,5232645]}
{"asset_bytes":75000000,"bundle_bytes":75000692,"identity":[147,148,66,160,185,37,92,215,181,45,229,48,116,97,194,17,173,248,74,122,33,182,120,24,121,31,155,135,145,43,82,196],"assets_identity":[140,146,218,49,232,156,101,169,130,212,253,247,203,195,97,51,232,190,195,46,219,94,140,192,154,83,197,124,198,90,126,67],"content_identity":[64,40,38,203,59,101,215,125,236,47,86,79,228,16,218,27,45,233,227,11,167,141,242,136,122,26,95,251,42,38,194,28],"samples_ns":[372081671,372255239,371330025,372086237,376693237,368831105,376700490,374658442,371790001,372838035,367910734]}
@@ -0,0 +1,65 @@
{
"host": "alpha",
"physical_host_verified": "systemd-detect-virt: none",
"cpu": "Intel Core i7-8700 @ 3.20GHz",
"affinity_cpu": 3,
"cflags": "-O2",
"learning": "off",
"samples": 11,
"warmups": 1,
"comparison": "sequential before/after, not interleaved",
"source_baseline_revision": "31f41848",
"source_before_sha256": "81643c45850d1651b54589f38746254828e41884c9dc703036af9e84b955dc6d",
"source_after_sha256": "6a0f297a22859a6cbbc51c34cd7fdef383ae4686efc7638827fc9cc018b28a57",
"probe_sha256": "f622aea386518d3da48288321c956709426689637ee60c5006a849de784fd6b6",
"generated_reader_before_sha256": "9c24004eea4ed3ece86a577c6b935a37ee52ba5b0fa18e9f391ebbc80200d7b0",
"generated_reader_after_sha256": "1543fa2b1d5a0febc05f1c121440e5b449f651a7995a77df8fda398bea43d46a",
"executable_before_sha256": "c4eded0e74d65498dc639b38f090aebcb5108dd88ec733b4c2ed194779e8d030",
"executable_after_sha256": "918e9d027125774ab8add1c4e0a27e216662c446aef7e5ba1cc37f6648cb1eb7",
"linked_runtime_sha256": "fe2641e24f151d0d00b8d0316e1b6820bb6eab09f4772ef8458ba93215272d02",
"identities_match": true,
"statistics": "symmetric 1.5xIQR fences, inclusive interpolated quartiles",
"results": [
{
"asset_bytes": 1000000,
"before": {
"median_ms": 5.087958,
"MB_s": 196.5425029058809,
"excluded_indices": []
},
"after": {
"median_ms": 3.890097,
"MB_s": 257.06299868615105,
"excluded_indices": [
3,
4
]
}
},
{
"asset_bytes": 75000000,
"before": {
"median_ms": 372.170738,
"MB_s": 201.52041077447632,
"excluded_indices": [
10
]
},
"after": {
"median_ms": 292.0349665,
"MB_s": 256.8185614855131,
"excluded_indices": [
1
]
}
}
],
"build_command": "env -u DISPLAY -u WAYLAND_DISPLAY CFLAGS=-O2 ZIRAN_LEARN=off LDLIBS=\"$PWD/build/libziran.a\" build-queue -- ziran build --target=c --exe --entry asset_digest:main --root bench --module-path cmd -o build/asset-digest bench/asset_digest.zi",
"run_command": "env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off build-queue -- taskset -c 3 build/asset-digest/asset_digest",
"limitations": [
"Synthetic package; not a Breeze first-frame measurement.",
"Alpha-only x86 result; Android SHA2 throughput is unmeasured.",
"Baseline was taken before candidate; this is not an interleaved comparison.",
"Content verification and byte/work limits are unchanged."
]
}
+48
View File
@@ -0,0 +1,48 @@
# Executable asset digest throughput on Alpha
The reader now uses the existing C streaming SHA-256 implementation. It feeds
whole strings, encodes small integer fields in one stack buffer, and uses the
runtime's shared constants and CPU dispatch. The separate Ziran compressor is
removed. Domain tags, integer byte order, budget accounting and identity checks
are unchanged.
| Synthetic asset | Before read (ms) | After read (ms) | Before MB/s | After MB/s |
| --- | ---: | ---: | ---: | ---: |
| 1,000,000 bytes | 5.088 | 3.890 | 196.5 | 257.1 |
| 75,000,000 bytes | 372.171 | 292.035 | 201.5 | 256.8 |
The 75 MB read takes 21.5% less time. These are direct `ZxExecRead` timings on
physical Alpha (Intel Core i7-8700), pinned to CPU 3, compiled with `-O2` and
learning off. Each series has one warmup and eleven retained raw samples.
Before and after were measured sequentially; they were not interleaved.
All program, asset and content identities match between implementations.
The same symmetric 1.5×IQR rule with inclusive interpolated quartiles applies
to every series. Excluded sample indices remain in the metadata.
The baseline reader source matches the current checkout before the change.
Only `compiler_exec_link.zi` changed on Alpha between accepted measurements;
the linked runtime archive, compiler, probe and other sources stayed fixed.
The temporary reader source edit was restored afterward. Source, executable,
generated-reader and runtime hashes, exact commands, excluded indices and
computed medians are in [metadata](asset-digest-alpha-metadata.json).
Raw samples are in [before](asset-digest-alpha-before.jsonl) and
[after](asset-digest-alpha-after.jsonl). An earlier exploratory baseline,
before adding all identity fields to the probe's output, is retained in
[initial baseline](asset-digest-alpha-before-initial.jsonl) and is not used
for the table. The reusable probe is [asset_digest.zi](../asset_digest.zi).
This is a synthetic asset-size measurement, not Breeze's startup or first-frame
time. Android SHA2 acceleration and the application's nested bundles still
need measurements on the device. A parent asset digest and a nested bundle's
program/asset/file digests cover different byte streams and domain tags, so
this change does not skip or reuse any of those validation steps.
Local verification: the executable bundle test passes independent SHA-256
asset identity vectors at 17 sizes (empty payload, SHA padding and block
boundaries, binary bytes, and more than 1 MiB), plus reader rejection after
payload mutation. Forced portable SHA dispatch passes the same bundle cases.
`env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off build-queue -- sh -c
'make check && make check-bootstrap'` passes all 271 retained local tests
(284.7 seconds, none reused), and bootstrap output matches. The benchmark
registry test also passes; `bench/bench.zi -- asset-digest` supplies the
compiler module path and runtime archive used by the probe.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
{
"baseline_receipt": "bench/results/c-teacher-alpha-six-before.json",
"baseline_original_receipt": "bench/results/wasm-tier-targets-2026-11-16.json",
"after_receipt": "bench/results/c-teacher-alpha-six-after.json",
"meaning": "Calls is folded Fib(20); this control measures wrapper/startup, not recursive-call performance.",
"complete": true,
"five_fresh_baseline_native_artifacts_match_historical_six": true,
"harness_original_sha256": "aaa48e7b68a238e20c33ac07762269f6ab3dce251aa463b0d95c098da0ec9044",
"harness_control_sha256": "10f6981cb077a700e1dc15b5b4009eb5c039ef3c0528479df770060f26207dcc",
"calls_native_artifact_unchanged": true,
"tools_unchanged": true,
"harness_restored": true,
"finished_unix": 1794863895
}
@@ -0,0 +1,65 @@
# C teacher: physical Alpha checkpoint, 2026-11-16
Compared the baseline [compiler revision](https://github.com/ziranlang/ziran/commit/96c23c7de6bc622225a916dfce18bff04486ba2b) with the [verified learning feature](https://github.com/ziranlang/ziran/commit/36e6caf9643d82b58434f11aad507da79f895922) on physical Alpha, Intel i7-8700. This is a fixed, pushed compiler comparison; later SSA, rotation, vectorizer and returned-record changes are outside this checkpoint. Learning recording and runtime checks were off. All builds and measurements ran serially through Alpha build-queue; every timing has eleven raw samples and symmetric inclusive-quartile 1.5×IQR exclusions.
The [before](c-teacher-alpha-2026-11-16-before.md) and [after](c-teacher-alpha-2026-11-16-after.md) assembly reports cover all six kernels, Button, Text, Input and hello with GCC 15.2 and Clang 21.1.8 at `-O2`. The after report has 1,506 ranked function comparisons and zero failed workloads. Native map extents identify functions, backward branches identify static loop envelopes, and SIGPROF supplies estimated function shares. Counts and weighted excess are inspection priorities, not cycle estimates or speedup predictions.
| Ranked finding | Native / C instructions | Native stack reads / writes | Function SIGPROF share | Owner |
| --- | ---: | ---: | ---: | --- |
| Records / Clang | 382 / 73 | 4 / 260 | 162 / 162 | records and aggregate lane |
| Sieve / Clang | 77 / 36 | 2 / 2 | 163 / 163 | SSA, rotation and loop lane |
| Hash / GCC | 50 / 26 | 0 / 0 | 158 / 158 | SSA and loop lane |
| Printing / GCC | 59 / 32 | 5 / 5 | 35 / 99 | call and memory selection candidates |
Vectors illustrates the limits of instruction counts: native has 104 instructions versus GCC’s 109, yet runs slower. Native has eleven stack reads and eleven writes versus seven and eight; GCC uses vector registers in its reduction. Stack traffic includes locals and saved registers, and vector-register uses include scalar floating point. Back-edge envelopes include cold paths; loop constants and missing C symbols do not prove LICM or inlining opportunities. Widget startup samples include session/theme setup and do not replace warm scenario timings. Zero samples mean unknown share. Existing detailed path findings were routed to the records, loop and vectorizer owners; this checkpoint adds the controlled Alpha measurements.
Fresh kernel medians, microseconds per call:
| Kernel | Native before | Native after | C after | Native/C after |
| --- | ---: | ---: | ---: | ---: |
| Sieve | 64.481 | 64.040 | 34.923 | 1.83 |
| Records | 47.748 | 47.181 | 15.743 | 3.00 |
| Hash | 40.322 | 40.406 | 27.961 | 1.45 |
| Vectors | 62.574 | 62.221 | 32.703 | 1.90 |
| Printing | 11.292 | 13.047 | 9.352 | 1.40 |
The [fresh baseline](c-teacher-alpha-before.json) and [fresh after receipt](c-teacher-alpha-after.json) use the standard lane’s current five-kernel harness. Sieve and Hash emit identical native artifacts before and after, so their small timing differences are noise observations. Records, Vectors and Printing artifacts change. The small Records/Vectors timing changes do not establish a useful speedup; Printing regresses from 11.292 to 13.047 µs and remains open. Native timings amortize one process over 32 calls; C, engine and Wasm time warm in-process calls. Compilation is excluded.
The original request also includes Calls. The standard lane removed it from its current timing list because Fib(20) is constant folded. The [six-kernel baseline](c-teacher-alpha-six-before.json) preserves the earlier physical-Alpha receipt at the same baseline revision (19:35 UTC), and the [six-kernel after control](c-teacher-alpha-six-after.json) restores Calls for a separate 21:18 UTC run. All five fresh baseline native digests match that older receipt; Calls itself has exactly the same native artifact before and after. Its native median is 6.129 → 5.954 µs (C after 11.450 µs). This is a historical control of a folded result and wrapper/startup overhead, not a fresh paired measurement of recursion. The [control receipt](c-teacher-alpha-2026-11-16-calls-validation.json) records the temporary list change, unchanged tools and exact harness restoration.
Fresh widget medians, microseconds per scenario:
| Widget | Native before | Native after | Improvement | C after | Go after |
| --- | ---: | ---: | ---: | ---: | ---: |
| Button | 8.807 | 6.969 | 20.9% | 2.726 | 4.162 |
| Text | 9.716 | 8.557 | 11.9% | 3.129 | 3.735 |
| Input | 12.882 | 9.963 | 22.7% | 3.924 | 6.610 |
The [before](c-teacher-alpha-2026-11-16-widgets-before.json) and [after](c-teacher-alpha-2026-11-16-widgets-after.json) widget receipts use the same Kryon revision and manifest. They exercise public layout, interaction and paint-command generation with checked batches, excluding pixel rasterization, system fonts and OS I/O. These improvements cover the integrated compiler revisions, including the constructor lane; they are not isolated gains from the learned scalar idioms. The gap to C and Go remains open.
Provenance required a correction: Alpha’s Kryon manifest pins Ziran v0.5, and `--project` selected that cached compiler even when invoked through the current launcher. The site harness’s compiler metadata alone did not establish the selected compiler. Earlier attempts failed safely and restored source/tools. Both accepted stages used an ignored temporary local override:
```toml
[overrides]
ziran = "/home/wao/Projects/ziranlang/ziran"
```
Before each accepted stage, the absolute current `build/bin/ziran pkg path ziran` command from Kryon’s directory resolved to that canonical compiler repository. Generated widget IR was archived and regenerated. The local override and lock bytes were restored afterward. Omega already had the canonical local override, so this discovery does not invalidate its previous widget checkpoint. The parent coordinator and widget lane received the compiler-selection metadata issue for routing a general harness fix.
The [validation receipt](c-teacher-alpha-2026-11-16-validation.json) records eight tool/runtime hashes, aggregate digests over 1,811 baseline and 1,819 after source files (compiler, harness and Kryon inputs), stable hashes during each stage, and exact preservation of `bench/standard` plus `build/standard`. All 336 tracked compiler/stdlib inputs were verified against the pushed target tree. The receipt retains the failed incremental target build and the successful full rebuild recovery; restored archive timestamps had left generated engine files stale. Both accepted compiler epochs use a full forced rebuild.
Exact accepted build/measurement commands, inside Alpha `build-queue`, with `ZIRAN_LEARN=off`, `HARMONY_BUILD_LOCAL=1`, and display variables removed:
```sh
make -B -j2 all
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-alpha-before --output bench/results/c-teacher-alpha-before.json
build/bin/ziran run --target=c bench/bench.zi -- library-targets --project /home/wao/Projects/kryonlabs/kryon --manifest /home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json --samples 11
build/bin/ziran run --target=c bench/bench.zi -- c-teacher --output bench/results/c-teacher-alpha-2026-11-16-before.md
make -B -j2 all
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-alpha-after --output bench/results/c-teacher-alpha-after.json
build/bin/ziran run --target=c bench/bench.zi -- library-targets --project /home/wao/Projects/kryonlabs/kryon --manifest /home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json --samples 11
build/bin/ziran run --target=c bench/bench.zi -- c-teacher --output bench/results/c-teacher-alpha-2026-11-16-after.md
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-alpha-calls-control --output bench/results/c-teacher-alpha-six-after.json
```
All accepted commands returned zero. The completed feature’s Ziran differential tests compare 70,210 C/native output lines across 34 multiply factors, deterministic edge/random inputs and eight integer widths, followed by retained parity. Offline training twice produced byte-identical checked-in table source. Full retained local tests and bootstrap provenance, including concurrent peer changes and the later successful focused site reruns, remain in the [Omega feature summary](c-teacher-omega-2026-11-16-summary.md). No compiler source changed for this report milestone. CI has not been checked for this report. Alpha build tools were updated for measurement; this does not claim an owner launcher installation or a release.
@@ -0,0 +1,195 @@
{
"schema_version": 1,
"host": "alpha",
"virtualization": "none",
"learning": "off",
"checks": false,
"started_unix": 1794863300,
"baseline_revision": "96c23c7de6bc622225a916dfce18bff04486ba2b",
"target_revision": "36e6caf9643d82b58434f11aad507da79f895922",
"commands": [
{
"command": [
"make",
"-B",
"-j2",
"all"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"wasm-tier",
"--samples",
"11",
"--label",
"c-teacher-alpha-before",
"--output",
"bench/results/c-teacher-alpha-before.json"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"library-targets",
"--project",
"/home/wao/Projects/kryonlabs/kryon",
"--manifest",
"/home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
"--samples",
"11"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"c-teacher",
"--output",
"bench/results/c-teacher-alpha-2026-11-16-before.md"
],
"code": 0
},
{
"command": [
"git",
"fetch",
"origin",
"master"
],
"code": 0
},
{
"command": [
"make",
"-j2",
"all"
],
"code": 2
},
{
"command": [
"make",
"-B",
"-j2",
"all"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"wasm-tier",
"--samples",
"11",
"--label",
"c-teacher-alpha-after",
"--output",
"bench/results/c-teacher-alpha-after.json"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"library-targets",
"--project",
"/home/wao/Projects/kryonlabs/kryon",
"--manifest",
"/home/wao/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
"--samples",
"11"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"c-teacher",
"--output",
"bench/results/c-teacher-alpha-2026-11-16-after.md"
],
"code": 0
}
],
"stages": {
"before": {
"revision": "96c23c7de6bc622225a916dfce18bff04486ba2b",
"tools": {
"build/bin/ziran": "dd24f284ee21f1217a245b608a1a33b1632fcdbc0ce8938a963e35dcfa3d4f29",
"build/bin/zi2c": "2e21cbdd222519dc2f54993721c5168719b0340fc00d4271c4ca101dd8300152",
"build/bin/zi2go": "0628df64c2fc17eee1fb64d73e8182906cb559123668a0e648023b8adf1c34d9",
"build/bin/zi2zir": "0bea673e4df7d9d8446e179564e60ebab8be739839b6b1047d9a7a8f56f55bd7",
"build/bin/zi2zx": "eb47203a4eef36585fcca75340e026e86b2fd34895b22c8dda342e127f956c00",
"build/bin/zx2native": "c1cf0932e45b017e8fbc90bb935966c4e67dbd4e700e22ecd52e0346597e1433",
"build/bin/zx2wasm": "f621cdbae99ed4abf839861905eba2c22a18839a7c18c3da3d4f7e41bc05ba75",
"build/libziran.a": "fdc99f231806aeed93dd1079625cb7e15903051beda4a34d040c22a3d01b4344"
},
"tools_unchanged": true,
"source_files": 1811,
"source_epoch_sha256": "e8065511e450ff5bd6cc5c6bc4fc19122d6c2c6de7b3f58fa6d2d57fb3b27297",
"changed_sources": []
},
"after": {
"revision": "36e6caf9643d82b58434f11aad507da79f895922",
"tools": {
"build/bin/ziran": "6f2433eefc3721145be0a6527a77156067b45e78f092d9c8c3e08c40b69c2e39",
"build/bin/zi2c": "2e21cbdd222519dc2f54993721c5168719b0340fc00d4271c4ca101dd8300152",
"build/bin/zi2go": "0628df64c2fc17eee1fb64d73e8182906cb559123668a0e648023b8adf1c34d9",
"build/bin/zi2zir": "0bea673e4df7d9d8446e179564e60ebab8be739839b6b1047d9a7a8f56f55bd7",
"build/bin/zi2zx": "50f84b648068e97d7e7ded2937f8cc4400edf5ba9a9b113f61e280275972777f",
"build/bin/zx2native": "3e4ce36573c6bc0857b3a571e10088c24464093b5d08a1a7369a1af0cc75891f",
"build/bin/zx2wasm": "f621cdbae99ed4abf839861905eba2c22a18839a7c18c3da3d4f7e41bc05ba75",
"build/libziran.a": "9d160e94e3a009ad9881171570ae3aa720e4e5b380bebfc79dfa185831158b4e"
},
"tools_unchanged": true,
"source_files": 1819,
"source_epoch_sha256": "68b334fd8ed3cc79bc3fc23efb0c5d8a448116fa6f5300f310423034b97a22d8",
"changed_sources": []
}
},
"complete": true,
"preparation_retry": "Prior attempts rolled back. Kryon --project selected pinned v0.5 despite current launcher; use temporary ignored local toolchain override and verify selected compiler path. Rebuild baseline completely and regenerate widget IR.",
"standard_before_sha256": "283ab41156a967162e807d9dedd78aec2a1b54f7fc05f6543fb57784fa2db19b",
"widget_selected_toolchain_before": "/home/wao/Projects/ziranlang/ziran",
"verified_compiler_source_files": 336,
"kryon_configuration_restored": true,
"standard_after_sha256": "283ab41156a967162e807d9dedd78aec2a1b54f7fc05f6543fb57784fa2db19b",
"standard_unchanged": true,
"finished_unix": 1794863723,
"recovered_attempts": [
{
"error": "command failed: make",
"rolled_back": true,
"reason": "Restored archive timestamps left generated engine files stale; force a complete target rebuild."
}
],
"recovery_command_start_index": 6,
"widget_selected_toolchain_after": "/home/wao/Projects/ziranlang/ziran"
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,117 @@
{
"schema_version": 1,
"native_sha256": "9978ae84253c8a66826459bd18f3379aa9b73784caf6e1942727fc5bffbfe82e",
"zx_sha256": "5c47cb8218aeed347661abe511c183dca5e1278e852b5791595e3dcbe7f4b75e",
"c_sha256": "c77c158bdc0e61b8c246fb0fb2efd8e62a5f537c6e0ef7fc7e573b897bd6d311",
"compiler": "cc (Debian 14.2.0-19) 14.2.0",
"candidates": [
{
"rule": "x86-multiply-constant",
"function": "tree_input_SecondaryPointerSample",
"factor": 3,
"native": "imul r11,rax,0x3",
"teacher": "lea rdx,[rax+rax*2]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "tree_TreeRead",
"factor": 65536,
"native": "imul r11,rcx,0x10000",
"teacher": "shl r8,0x10",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "cursor_CursorHoverFrameStart",
"factor": 16,
"native": "imul r11,rax,0x10",
"teacher": "shl rdx,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "paint_queue_SnapshotTextJoin",
"factor": 512,
"native": "imul r11,rdi,0x200",
"teacher": "shl rax,0x9",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "tree_TreeStoreLabel",
"factor": 65536,
"native": "imul r11,r9,0x10000",
"teacher": "shl rdx,0x10",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "contextmenu_Draw",
"factor": 16,
"native": "imul r11,rax,0x10",
"teacher": "shl rbx,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "cursor_CursorHoverFrameCommit",
"factor": 16,
"native": "imul r11,rax,0x10",
"teacher": "shl rax,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_icon_behavior_PaintSvgIcon",
"factor": 5,
"native": "imul r11,r14,0x5",
"teacher": "lea rdx,[r12+r12*4]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_icon_behavior_SvgIconTexture",
"factor": 5,
"native": "imul r11,rcx,0x5",
"teacher": "lea rcx,[rcx+rcx*4]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_icon_behavior_SvgIconCells",
"factor": 5,
"native": "imul r11,rcx,0x5",
"teacher": "lea rsi,[rcx+rcx*4]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_shape_ShapeCoverEdges",
"factor": 16,
"native": "imul r11,rcx,0x10",
"teacher": "shl r12,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_shape_ShapeAddEdge",
"factor": 16,
"native": "imul r11,rdx,0x10",
"teacher": "shl rdx,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
}
]
}
@@ -0,0 +1,78 @@
{
"started_unix": 1794856923,
"revision": "42dc1b0f41489e8affae19815a52aa3a875ff0d9",
"commands": [
{
"command": [
"make",
"-j1",
"check"
],
"code": 0
},
{
"command": [
"make",
"-j1",
"check-bootstrap"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"wasm-tier",
"--samples",
"11",
"--label",
"c-teacher-final",
"--output",
"bench/results/c-teacher-omega-final.json"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"library-targets",
"--project",
"/mnt/storage/Projects/kryonlabs/kryon",
"--manifest",
"/mnt/storage/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
"--samples",
"11"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"c-teacher",
"--output",
"bench/results/c-teacher-omega-2026-11-16-final.md"
],
"code": 0
}
],
"changed": [
"cmd/compiler_machine_aggregate.zi",
"tests/machine_place_cases.zi"
],
"finished_unix": 1794857182,
"complete": false,
"source_files": 1056,
"start_epoch_sha256": "d1189e0d940d29b38732e3f6ba42344977b296d1369f10cf5c663f9671082574",
"end_epoch_sha256": "76ce23f6965ad9660265dd485aaf17fee1e3a52457918f76f8b191efcf10fdde"
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
{
"schema_version": 1,
"host": "omega",
"learning": "off",
"checks": "manual-safety default; test-specific assertions retained",
"github_ci": "not checked",
"local_tests": [
{
"receipt": "16151a4867e2fa478e3d0afde52731aaa7a0",
"revision": "42dc1b0f41489e8affae19815a52aa3a875ff0d9",
"suite": "make -j1 check",
"code": 0,
"passed": 281,
"total": 281,
"bootstrap_code": 0,
"source_guard": "two concurrent constructor files changed; compiler binaries unchanged"
},
{
"receipt": "34159fa4c599897ee55a627d0b74327deffa",
"suite": "constructor canonical build, check and check-bootstrap",
"build_code": 0,
"bootstrap_code": 0,
"passed": 279,
"total": 281,
"source_guard": "3409 guarded inputs and seven compiler identities unchanged",
"failed": [
"site_pages.sh: missing targets receipt",
"site_targets.sh: Publish one measured host"
]
},
{
"receipt": "8382856e6704249164010f4a322be36d05e9",
"revision": "efefbb1f40dacbd00972b41126bc26ef5349463e",
"command": "env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off HARMONY_BUILD_LOCAL=1 build-queue -- sh -c 'sh tests/site_pages.sh build/bin/ziran && sh tests/site_targets.sh build/bin/ziran'",
"code": 0,
"result": "Both prior publication-data failures resolved; pages, matrices, hashes, samples and independent artifact oracles passed."
}
],
"learning_verification": {
"receipt": "d001bab87cfb730312d572c86d3128929bc9",
"differential_output_lines": 70210,
"retained_zx_parity": "passed"
},
"offline_calibration": {
"receipt": "e5cffefb436f30c04174e17009bdec81bc1a",
"c_optimization": "-O2",
"deterministic_training_repeat": "byte-identical",
"selected_policy": 1,
"leaf_operations": 0,
"same_artifacts": "Both leaf settings produce identical artifacts for all six kernels."
}
}
Loaded 100 of 3478 files, more files were not shown because too many files have changed in this diff. Show more