Files
ziran/site/guide/usage.html
T
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

2046 lines
150 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Compiler and standard library guide: the Ziran guide, rendered from docs/USAGE.md."><title>Compiler and standard library guide · Ziran guide</title><link rel="canonical" href="https://ziran-lang.org/guide/usage"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html" aria-current="page">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../docs.html#guide">Guide</a></p><h1>Compiler and standard library guide</h1><p>Rendered from <a href="https://github.com/ziranlang/ziran/blob/master/docs/USAGE.md">docs/USAGE.md</a>. See the <a href="../docs.html#guide">documentation index</a> for the other guides.</p></div>
<div class="article-grid"><aside class="page-toc"><strong>On this page</strong><a href="#assembly-with-a-portable-body">Assembly with a portable body</a><a href="#build-and-test">Build and test</a><a href="#compiler-commands">Compiler commands</a><a href="#generate-c-and-go-binaries">Generate C and Go binaries</a><a href="#save-and-inspect-zir-modules">Save and inspect ZIR modules</a><a href="#imports">Imports</a><a href="#foreign-functions">Foreign functions</a><a href="#multiline-strings">Multiline strings</a><a href="#returned-views">Returned views</a><a href="#shadowing">Shadowing</a><a href="#integer-literals">Integer literals</a><a href="#standard-library">Standard library</a></aside><div class="article-body">
<section class="prose"><p><a href="https://github.com/ziranlang/ziran/blob/master/README.md">Back to the README</a> · <a href="implementation-status.html">Implementation status</a></p>
<h2 id="assembly-with-a-portable-body">Assembly with a portable body</h2>
<p>An ordinary procedure can supply architecture-specific assembly and a required
Ziran implementation. C output selects assembly when built by GCC or Clang
for that architecture. Go can opt into native assembly through cgo as described
below. Other compilers and <code>.zx</code> use the checked Ziran body. Define
<code>ZIRAN_NO_ASM</code> when compiling generated C to force the portable body.</p>
<pre><code class="language-zi">Increment :: (value: $T) -&gt; T #asm(&quot;x86_64&quot;, &quot;add $1, %[out]&quot;, &quot;=r&quot;, &quot;0&quot;, &quot;cc&quot;, &quot;&quot;) #asm(&quot;aarch64&quot;, &quot;add %[out], %[value], #1&quot;, &quot;=r&quot;, &quot;r&quot;, &quot;&quot;, &quot;&quot;) {
return value + 1
}
</code></pre>
<p>Each <code>#asm</code> takes four to six arguments: architecture, assembly template,
output constraints, input constraints, and optionally clobbers and options
(both default to <code>""</code>). The architecture and options are literal strings.
Templates, constraints and clobbers can also name compile-time string
constants; options are <code>""</code> or <code>"volatile"</code>. Use semicolons to separate constraints and clobbers; commas
remain available for the assembler's constraint alternatives. Templates use GNU
extended assembly syntax, including named operands, register modifiers,
multiple instructions, escaped newlines, and assembler directives. Templates
are quoted as data in generated source. The native compiler and assembler
validate instruction syntax and machine-specific constraints.</p>
<p>A template constant can be generated in the same file with
<code>TEMPLATE :: #run MakeTemplate();</code> and used as <code>#asm("x86_64", TEMPLATE, ...)</code>.
The generator can use builders, loops, pointers and slices. Put its helpers
under <code>#scope_file</code> and restore <code>#scope_export</code> before the public kernel;
<code>tests/spec/asm_dct8.zi</code> generates three architectures from one transform
description this way.</p>
<p>Generated C uses positional operands internally, so source operand aliases
may also be C keywords. Named matching inputs retain the same binding.</p>
<p>Input operands follow parameter order and use the parameter names. Parameters
must be scalars, pointers or slices of scalars; a slice operand is its data
pointer, so pass the count separately. Pointer and slice parameters imply a
<code>"memory"</code> clobber. A scalar or pointer result has operand name
<code>out</code>; a record result has one operand named <code>out_FIELD</code> per declared field,
in field order. Result fields must be named scalars or pointers. Void results
have no output constraints. Outputs require <code>=</code> constraints, including
early-clobber <code>=&amp;r</code>; use an input constraint such as <code>"0"</code> to initialize a tied
read/write output. Output and input operand names must be distinct. The limit
is 30 combined input/output operands.</p>
<p>Generic procedures retain their variants through specialization, including
from separately saved libraries. Declarations check syntax, input counts and
known operand types; every concrete instance checks all scalar/pointer inputs,
result fields, local bindings and its portable body. A type-dependent result
must match the declared output constraints at each call. Aggregate inputs are
rejected even when the current target would execute the portable body.
Generic local blocks follow the same rules. <code>tests/generic_assembly.sh</code> checks
integer widths, floating-point copies, tied outputs, memory aliases, caller-owned
record types and multiple results across native and portable targets.</p>
<p>For example, a two-field record can use output constraints <code>"=a;=d"</code> to capture
two registers. A pointer parameter can give assembly access to memory; declare
<code>"memory"</code> in the clobbers when accessing memory beyond named operands, and
use <code>"volatile"</code> when the operation must survive dead-result elimination.
Follow the <a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html">GNU extended assembly contract</a>
for register lifetimes, early clobbers, matching constraints, flags and memory.</p>
<p>Architecture names are <code>x86_64</code>, <code>x86</code>, <code>aarch64</code>, <code>arm</code>, <code>wasm32</code>, <code>riscv64</code>,
<code>riscv32</code>, <code>powerpc64</code>, <code>powerpc</code>, <code>s390x</code>, and <code>loongarch64</code>. Selection uses
the native compiler's target macros, so cross-compilation selects the
destination architecture. Append required CPU features with <code>+</code>, for example
<code>"x86_64+popcnt"</code>, <code>"x86_64+avx2+bmi2"</code>, <code>"aarch64+crc32"</code>, <code>"arm+neon"</code>, or
<code>"wasm32+simd128"</code>.</p>
<pre><code class="language-zi">Count :: (value: u64) -&gt; s64 #asm(&quot;x86_64+popcnt&quot;, &quot;popcnt %[value], %[out]&quot;, &quot;=r&quot;, &quot;r&quot;, &quot;cc&quot;, &quot;&quot;) {
bits := value
total: s64
while bits != 0 { total += cast(s64)(bits &amp; 1); bits &gt;&gt;= 1 }
return total
}
</code></pre>
<p>A kernel can list one variant per line between its header and its portable body,
long templates as <code>#string</code> text. The body is required: it runs on every other
target (Go, WebAssembly, <code>.zx</code>) and is the reference the variants are tested
against.</p>
<pre><code class="language-zi">// dst[i] = saturate(dst[i] + src[i]), eight lanes per block.
AddSaturate :: (dst: []s16, src: []s16, blocks: s64)
#asm(&quot;x86_64&quot;, #string END
xorl %%eax, %%eax
1: cmpq %[blocks], %%rax
jge 2f
movq %%rax, %%rcx
shlq $4, %%rcx
movdqu (%[dst],%%rcx), %%xmm0
movdqu (%[src],%%rcx), %%xmm1
paddsw %%xmm1, %%xmm0
movdqu %%xmm0, (%[dst],%%rcx)
incq %%rax
jmp 1b
2:
END, &quot;&quot;, &quot;r;r;r&quot;, &quot;rax;rcx;xmm0..xmm1;cc&quot;)
#asm(&quot;aarch64&quot;, #string END
cbz %[blocks], 2f
mov x9, %[dst]
mov x10, %[src]
mov x11, %[blocks]
1: ld1 {v0.8h}, [x9]
ld1 {v1.8h}, [x10], #16
sqadd v0.8h, v0.8h, v1.8h
st1 {v0.8h}, [x9], #16
subs x11, x11, #1
b.ne 1b
2:
END, &quot;&quot;, &quot;r;r;r&quot;, &quot;x9..x11;v0..v1;cc&quot;) {
for i: 0..blocks * 8 - 1 {
sum := cast(s32)dst[i] + src[i]
if sum &gt; 32767 { sum = 32767 }
if sum &lt; -32768 { sum = -32768 }
dst[i] = cast(s16)sum
}
}
</code></pre>
<p>Clobbers name registers or numbered ranges: <code>xmm0..xmm7</code>, <code>x9..x11</code>,
<code>v0..v3</code>, and on ARMv7 <code>q0..q1</code>, which stands for <code>d0..d3</code>. The checker
requires every register a template names to be a clobber or pinned by a
constraint (<code>"a"</code> holds <code>rax</code>), every <code>%[name]</code> and <code>%N</code> to be an operand, and
no clobber to overlap a pinned register. Templates may read, but never
clobber, the stack, frame and platform registers: <code>rbp</code>/<code>rsp</code> on x86-64,
<code>x18</code>/<code>x29</code>/<code>sp</code> on AArch64, <code>r7</code>/<code>r11</code>/<code>sp</code>/<code>pc</code> on ARMv7.</p>
<p>Build generated C with <code>-DZIRAN_ASM_CHECK</code> to test the variants: each call of
such a procedure runs its portable body, then every variant the CPU supports
on copies of the same inputs, compares results and the memory its slice and
pointer parameters reach, and aborts with <code>#asm check failed: AddSaturate
variant "x86_64" differs from its portable body in dst</code> on a difference.
Callers receive the portable results. Run it over random and edge-case
inputs. Local <code>#asm</code> blocks are not
checked this way. <code>tests/spec/asm_dct8.zi</code> is a complete kernel: AV1's 8x8
inverse DCT with SSSE3, AArch64 and ARMv7 NEON variants, about ten times
faster than its portable body.</p>
<p>A <code>.zx</code> bundle is lowered from each procedure's portable body, so a bundle
holds no machine code and a downloaded bundle cannot run instructions of its
own; <code>ziran run FILE.zi</code> runs the portable bodies too. Native builds of the
source keep every variant. Run <code>sh tests/zx_native_asm.sh build/bin/ziran</code>.</p>
<p>Feature variants use isolated functions compiled for the requested ISA. The
ordinary caller keeps the build's baseline ISA, checks CPU availability once,
and caches its selection with atomic accesses. x86 GCC/Clang GNU-ABI drivers
use the compiler's CPU detection; Linux/Android AArch64 and ARMv7 C use the
kernel's hardware-capability information. Other platforms or unavailable
capabilities use the next eligible variant or the checked Ziran body. <code>ZIRAN_NO_ASM</code> forces
the portable body. Build the caller for the oldest CPU you intend to support;
globally enabling <code>-march=native</code> or extra ISA options can also affect its
ordinary generated code.</p>
<p>x86 and x86_64 features are <code>popcnt</code>, <code>sse2</code>, <code>ssse3</code>, <code>sse4.1</code>, <code>sse4.2</code>,
<code>avx</code>, <code>avx2</code>, <code>avx512f</code>, <code>bmi</code>, <code>bmi2</code>, <code>lzcnt</code>, <code>fma</code>, <code>aes</code>, and <code>pclmul</code>.
AArch64 features are <code>aes</code>, <code>crc32</code>, <code>pmull</code>, <code>sha2</code>, <code>atomics</code>, and <code>simd</code>.
ARMv7 (<code>arm</code>) has <code>neon</code>, and <code>wasm32</code> has <code>simd128</code>.
Other architecture/feature combinations are rejected. Feature combinations
require every listed feature. Variants are considered in source order; put
more demanding variants first and an architecture-only variant last. Duplicate
or shadowed variants are rejected. Baseline variants must use instructions
guaranteed by the selected build target. See
<a href="https://gcc.gnu.org/onlinedocs/gcc/x86-Built-in-Functions.html">GCC CPU detection</a>,
<a href="https://clang.llvm.org/docs/AttributeReference.html#target">function target attributes</a>,
and <a href="https://www.kernel.org/doc/html/latest/arch/arm64/elf_hwcaps.html">ARM64 hardware capabilities</a>.</p>
<p><code>arm+neon</code> variants need ARMv7-A or later with a hard-float ABI (Linux
<code>armhf</code>, Android <code>armeabi-v7a</code> from API 18). Their helpers run in ARM state, so
Thumb-2 callers work, and the caller keeps the build's FPU option. Name the
NEON registers you use in the clobbers (<code>q0</code> or <code>d0;d1</code>). Write <code>vld1</code>/<code>vst1</code>
without <code>:64</code>/<code>:128</code> alignment qualifiers unless the address is known to be
aligned: a qualified access to a misaligned address faults.</p>
<p>A WebAssembly engine rejects a whole module that holds SIMD instructions it
does not support, so <code>wasm32+simd128</code> is a build option rather than a run-time
check. Its variants are compiled in, inline, only when the generated C is
built with <code>-msimd128</code>; otherwise the next variant or the Ziran body runs.
Build the module twice, with and without <code>-msimd128</code>, and load the SIMD module
only where <code>WebAssembly.validate</code> accepts a SIMD module. Operands are locals
(<code>local.get %[value]</code>, <code>local.set %[out]</code>), and inputs must not be written.
<code>v128</code> values cannot be operands: keep them on the operand stack or in memory
passed by pointer. From Clang 19 (current Emscripten qualifies) a template can
carry them through <code>block (v128) -&gt; (v128)</code> and <code>loop (v128) -&gt; (v128)</code>; Clang 18
crashes on any typed block in inline assembly. Use <code>v128.load 0:p2align=0</code> for
unaligned data.</p>
<p>Assembly and the fallback must implement the same behavior; checking the
fallback does not prove their equivalence, so test with <code>ZIRAN_ASM_CHECK</code>. These variants do not yet provide
<code>asm goto</code>, naked functions, standalone assembler files, or direct Go ABI
assembler output. Saved IR preserves the variants; <code>.zx</code>
executes only portable code. Rebuild older IR/bundles with the current compiler.</p>
<p>Generated Go packages use their checked Go implementation by default. Enable
the native bridge with <code>CGO_ENABLED=1 go build -tags=ziran_asm .</code> in the
generated package. Build packages rather than explicit filename lists so Go
applies companion-file build constraints. A working C cross-compiler is
required when cross-compiling with cgo. The bridge reuses the C assembly
emitter, including GNU constraints, labels, architecture selection and CPU
feature guards; it does not translate templates into Go assembler syntax.
<code>CGO_ENABLED=0</code> always uses the checked body. To force that body while testing
the native build configuration, set
<code>CGO_CFLAGS="-O2 -g -DZIRAN_NO_ASM"</code> together with the build tag.</p>
<p>Go bridge signatures carry scalars and pointers to storage containing no Go
pointers. Flat record results are reconstructed from primitive result fields.
Pointer-bearing objects, pointer-valued local-block outputs or memory inputs,
and local-block pointers to arrays retain the checked body. Standard cgo
pointer checks remain enabled. Assembly must not retain Go pointers after the
call or create pointers that violate Go's pointer rules. Unavailable variants
leave their Go dispatch unset, including before Ziran startup code executes.</p>
<p>Each bridge invocation pays a cgo transition. A whole-loop assembly kernel can
amortize that cost; calling the bridge for every small operation can be much
slower than the Go body. Measure the intended call granularity before enabling
the tag. Default builds retain a compile-time-disabled native branch.</p>
<p>Run <code>tests/assembly.sh build/bin/ziran</code> for source/saved IR execution and
rejection checks, and <code>tests/assembly_features.sh</code> for CPU selection,
concurrent calls, unavailable features and isolated helpers. It runs ARMv7
NEON and its masked fallback under <code>qemu-arm</code> with GCC and Clang
(<code>ZIRAN_ARM_CC</code>, <code>ZIRAN_ARM_CLANG</code>, <code>ZIRAN_QEMU_ARM</code>; <code>ARM_REQUIRED=1</code> fails
instead of skipping).
<code>tests/zx_wasm.sh</code> builds SIMD128 and baseline modules
with <code>ZIRAN_WASM_CC</code> (default <code>clang</code>, <code>WASM_REQUIRED=1</code> to require it).
<code>tests/go_assembly.sh</code> checks native and default Go builds, forced fallback,
strict cgo pointer checking, startup dispatch, memory aliases, concurrency and
source/saved IR. <code>bench/go_assembly.py</code> compares whole-loop and per-operation
bridges with checked Go bodies, a preserved compiler and native C controls.
<code>bench/assembly.py</code>
measures baseline assembly against its forced fallback and handwritten C/Go;
<code>bench/cpu_features.py</code> measures CPU-selected loop kernels against an optimized
Ziran body and handwritten C, with independent result validation. Use assembly
where measurements or access to a specific instruction justify it; compilers
already recognize many byte swaps and arithmetic patterns.</p>
<h3 id="local-assembly-blocks">Local assembly blocks</h3>
<p>A block can read and write scalar or pointer locals and parameters inside an
ordinary procedure. Its six strings use the same architecture, template,
clobber and option rules. Each output/input item is <code>constraint:binding</code>, or
<code>constraint:alias=binding</code> when the assembly operand needs a different name.
The template refers to the alias, while the binding names existing lexical
storage. Every variant must bind the same operands in the same order.</p>
<pre><code class="language-zi">Answer :: () -&gt; s64 {
value: s64 = 41
result: s64
#asm(&quot;x86_64&quot;, &quot;leaq 1(%[value]), %[result]&quot;, &quot;=r:result&quot;, &quot;r:value&quot;, &quot;&quot;, &quot;&quot;) {
result = value + 1
}
return result
}
</code></pre>
<p>For a read/write value, use output <code>"=r:total"</code> with an input such as
<code>"0:old=total;r:value"</code>; the first input initializes the output register and
<code>value</code> supplies another operand. Aliases must be distinct across all inputs
and outputs. Multiple outputs and zero-operand blocks are supported. Bindings
cannot be global names, constants, members, indexed expressions or aggregates;
pass a pointer when assembly needs to access other storage, and declare the
memory and register clobbers required by the GNU contract.</p>
<p>Architecture-only blocks emit inline assembly. CPU-feature blocks use isolated
helpers. C helpers receive input values and return a single <code>=r</code>/<code>=&amp;r</code> output directly;
other or multiple outputs use each binding's actual address. Selection is cached
atomically per block. Their portable body is always checked, runs on unsupported
targets or with <code>ZIRAN_NO_ASM</code>, and must fall through to the following statement.
It may contain local loops and their loop control, but cannot return or break
out of the assembly block. Native instructions must preserve that fallthrough,
stack discipline and the declared side effects as well as result values;
checking cannot prove this equivalence. Run
<code>tests/assembly_blocks.sh</code> for source/saved IR, native/portable, concurrent
selection, typed operands and malformed-metadata checks. Inside a native
<code>#parallel</code> loop, operand bindings from the enclosing scope are captured even
when only the assembly template uses them; the portable body retains the same
loop bindings. Assembly outputs must remain iteration-local, and GPU regions
reject pointer operands. Native parallel regions currently support up to 16
captured bindings.</p>
<h2 id="build-and-test">Build and test</h2>
<p>Run <code>make</code> to build the current toolchain and <code>make check</code> for the complete
lean language, backend, and portable bundle suite. Pruning removed 263
redundant check scripts and their unused helpers. Local and CI runs
execute every retained check. Explicit <code>CHECK_FILTER</code> runs include every
matching check. Workers follow the build queue's allocation; set <code>CHECK_JOBS=1</code>
to run serially or choose another positive worker count. <code>make sanitize</code> runs
the retained suite under AddressSanitizer and UBSan.</p>
<p>A project's GitHub Actions job sets up the Ziran its <code>ziran.lock</code> pins with
<code>uses: ziranlang/ziran/.github/actions/setup@COMMIT</code>. It checks out that
commit with its compiler built and puts <code>build/bin</code> on <code>PATH</code>; <code>fetch: true</code>
also fetches the locked packages. On Linux the build tree is the one the
Toolchains workflow published for that commit, so the job builds nothing; on
other systems, or for a commit without one, the job builds Ziran once and
caches it. Run the Toolchains workflow for an older commit a lock still pins.</p>
<p>Dependency-owned native recipes accept per-build options without editing project
settings: <code>ziran pkg artifact provider:native --platform linux-x86_64-gnu
--option provider:mode=release</code>. Repeat <code>--option Alias:key=value</code> for declared
string or boolean keys, including <code>group.name.key</code> for named tables. Values are
literal argv data; quote paths containing spaces. Overrides reach prerequisite
recipes and contribute to cache identity. See <a href="packages.html#dependency-owned-native-artifacts">package artifacts</a>
for validation, alias mapping and the programmatic entry points.</p>
<h2 id="compiler-commands">Compiler commands</h2>
<p>The compiler commands are <code>zi2zir</code> (including
<code>--check-only</code>), <code>zi2c</code>, <code>zi2go</code>, and <code>zi2zx</code>.
Run a program with <code>ziran run hello.zi</code> or <code>zi2zx run hello.zi</code>; Ziran checks
the file and executes <code>main</code> in one step. <code>make install-user</code> installs both
commands in <code>~/.local/bin</code>.
<code>zi-fmt</code> formats source. <code>ziran guide</code> prints a short reference from the
installed compiler, including current safety and target limits.
<code>ziran capabilities --target=go --json</code> reports a versioned machine-readable
target summary; see the <a href="capabilities.html">capability schema</a>.
<code>ziran api --json --root src src/main.zi</code> checks an entry and its imports,
then reports their public types and procedure signatures; see the
<a href="api-discovery.html">API query schema</a>.
<code>ziran check --lint</code> also warns about casts a program no longer needs: a cast
to the value's own type, and one that only widens a whole typed initializer,
assignment, argument, or result, which the compiler now widens itself.
It also warns when a byte is compared with a printable character's code
written as a number, as C ports do: <code>text[i] == 65</code> reads better as
<code>text[i] == #char "A"</code>. And it warns about an integer local that only ever
holds 0 or 1 and is only compared with them, which reads better as a <code>bool</code>.
Warnings do not fail the check (<code>"severity":"warning"</code> in JSON).
<code>ziran check|ir|api|inspect|build|bundle|run|fmt</code> remains a convenience dispatcher
for the same tools. <a href="https://github.com/ziranlang/ziran/blob/master/bench/README.md">Cross-target benchmarks</a> measure the
compiler, downstream toolchains, and validated runtime cases separately.</p>
<p>Portable bundles run with <code>ziran run app.zx</code>. Graphical
bundles use installed package-provided platform hosts through the same command;
see <a href="zx.html#running-bundles">runtime providers</a>.</p>
<h3 id="output-routes">Output routes</h3>
<p>The experimental <code>zi2zx</code> pipeline checks source into <code>.zir</code>, links and lowers
LIR, verifies it, runs LIR optimizations, and writes portable ZX instructions.
The portable interpreter executes those instructions directly.
The experimental direct-native route lowers the same verified instructions to
machine code, applies a target ABI/platform veneer, and writes a platform
binary; only rows with explicit implementation and execution evidence count as
supported. It never changes to another engine after a gap.</p>
<p>Native output from source first encodes and reads verified ZX bytes, exactly
as <code>zx2native --target x86_64 --platform linux --emit elf -o app app.zx</code> does.
The <code>zi2zx</code> default output is first-class
portable output; <code>--emit lir</code> remains a text inspection view. The standalone
<code>.lirb</code>, <code>--emit exec</code> and <code>--input exec</code> routes are removed. Optimization is
mandatory before ZX; <code>--opt</code> only selects the optimized source LIR view or its
source-only <code>--emit opt-report</code>. ZX input is not reoptimized. Native map source
origins remain a gap because the required ZX payload is stripped.
<code>ziran bundle</code> writes the same ZX; see <a href="zx.html">ZX</a>.</p>
<p>The C and Go targets are separate generated-code exporters. With <code>--exe</code>, their
downstream C or Go toolchains also produce platform binaries. These outputs are
not called native by the direct-backend documentation and do not satisfy or
rescue a direct-native request.</p>
<p>Portable host capabilities and platform bindings are also separate layers. A
capability gives ZX code a typed service contract; a host binding implements
it. A direct target's ABI veneer instead implements target-specific entry,
calling-convention, syscall, and exit details used by direct machine code.</p>
<p>The opt-in <code>zx2native --target x86_64 --platform linux --emit elf</code> path is the first such veneer. It
produces a static no-libc executable with target-owned <code>write_all</code> and process
exit. Its literal formatter supports strings/text views, bools, every fixed
signed and unsigned integer width, and <code>%%</code>; floats and unavailable platform
services fail with stable named diagnostics.</p>
<h2 id="generate-c-and-go-binaries">Generate C and Go binaries</h2>
<p><code>ziran build FILE.zi</code> defaults to a direct native binary named after the source
stem, composing <code>zi2zx</code> and host-target <code>zx2native</code>. Use <code>--target=zx</code>,
<code>--target=wasm</code>, <code>--target=c</code>, or <code>--target=go</code> to request another exact route.</p>
<p>Use <code>ziran build --target=c</code> for C99 output. Add <code>--exe --entry
module:function</code> to also compile it into <code>DIR/module</code>, a program that runs
that procedure and exits with its integer result; the entry takes nothing or
<code>(argc: s32, argv: **u8)</code> (signed byte pointers are also accepted). <code>CC</code>,
<code>CFLAGS</code> (default <code>-O3</code>), <code>LDFLAGS</code>, and <code>LDLIBS</code> apply as in make. Add
<code>--release</code> for final builds: the default flags become <code>-O3 -flto=auto</code>, which
optimizes across modules. Each link then generates code for the whole program
again, so one-file edits rebuild many times slower. <code>CFLAGS</code> still wins.</p>
<p>Small public procedures are inlinable across modules in every C build: the
module's header carries a <code>static inline</code> copy that other modules' calls use,
while the module's own <code>.c</code> keeps the one external definition, so a
procedure's address is the same everywhere. Each module still compiles and
caches on its own; editing such a procedure's body rebuilds the modules that
call it. Procedures that call file-scope code, or that use string
literals, constant tables or function values, stay out of line. A C file that
defines a module's procedures itself, such as a test mock, puts
<code>#define ZIRAN_&lt;MODULE&gt;_H_SOURCE 1</code> (the header guard plus <code>_SOURCE</code>) before
including that module's header, so the header leaves out its copies.
<code>-DZIRAN_NO_HEADER_INLINE</code> leaves out every module's copies, so all calls
reach the external definitions; a test that interposes procedures at link
time, as with <code>ld --wrap</code>, builds with it.</p>
<p>A closed program, one linked with <code>--entry</code> that builds with <code>--exe</code> or has
its own C <code>main</code>, carries only the code it uses. Its generated files are the
only ones that include its headers, so each header declares just the types,
procedures, constants, variables and foreign bindings that another generated
file names. The module's own <code>.c</code> keeps whatever only it reads, a header copy
stays only for a procedure another module calls, and a module whose header
would declare nothing has no header. Runtime headers such as <code>zir_bounds.h</code>
keep only the helpers some generated file calls. A library build, without
<code>--exe</code> or a C <code>main</code>, keeps each header's whole public interface for the C
code that hosts it.</p>
<p><code>#inline</code> after a procedure's result asks generated C to always inline it:
<code>Mix :: (value: s64) -&gt; s64 #inline { ... }</code>. GCC and Clang get
<code>always_inline</code>, a public procedure's header copy is kept whatever its
size, and a procedure that calls itself is rejected. <code>#cold</code> does the
opposite for slow paths such as a refill: the procedure is never inlined,
is laid out as rarely run, and other modules call its one definition
rather than a header copy. Neither changes what a call does, and Go marks
a <code>#cold</code> procedure <code>//go:noinline</code>.</p>
<p>A call that returns an array writes its result straight into the array a
declaration creates or a plain assignment names, such as <code>grid := Make(4)</code>,
<code>row = Next(row)</code> or <code>holder.values = Make(10)</code>, with no temporary and copy in
C. The callee stores its result only when it returns, so arguments and
globals that name the destination still read the old value during the call.
Returning an array works the same way: <code>return Make(n)</code> hands the caller's
destination on, and <code>return out</code>, <code>return holder.values</code> or a parameter is
copied out once. A local array passed by value to a Ziran procedure, as in
<code>Sum(values)</code>, is copied once, by the procedure as it starts; the caller
copies it first only when a later argument could change it.</p>
<p>Indexing stays checked in every build, but generated C leaves out a check
it can prove always passes: a loop counter its condition bounds, such as <code>i</code> in
<code>for i: 0..7</code> over a <code>[8]T</code> array or in <code>for i: 0..view.count-1</code> over a
slice or string nothing reassigns, and values bounded by their type or by
<code>&amp;</code>, <code>%</code>, <code>&gt;&gt;</code> or <code>&lt;&lt;</code> by a constant, such as <code>table[x &amp; 255]</code>,
<code>bytes[(row &lt;&lt; 4) + t]</code> for <code>row</code> in <code>0..15</code> and <code>t</code> in <code>0..3</code>, or <code>bytes[b]</code>
for a <code>u8</code> <code>b</code> and 256-entry arrays.
Locals built from such values keep their ranges: after <code>line := row * 16</code>
and <code>at := line + (offset &amp; 15)</code> for <code>row</code> in <code>0..15</code>, <code>bytes[at]</code> over a
256-entry array needs no check, and a counter declared without a value
starts at zero. An
index whose variable has its address taken or is changed before the read keeps
its check. Run <code>sh tests/proven_index_ranges.sh build/bin/ziran</code>.</p>
<p>Guards count too. After
<code>if stride &gt; 64 || input.count &lt; cast(s64)(height + 3) * stride + width + 4 { return }</code>,
with <code>width</code> and <code>height</code> bounded the same way, <code>input[row * stride + column]</code>
in <code>for row: 0..height + 3</code> and <code>for column: 0..width + 3</code> reads without a
check. An enclosing <code>if</code> or <code>while</code> condition, earlier <code>&amp;&amp;</code> and <code>||</code>
operands, and an earlier <code>if</code> that ends in <code>return</code>, <code>break</code> or <code>continue</code>
all act as guards until a value they compare changes. A local declared
before the guard counts too: after <code>at := row * stride + column</code> and a
guard bounding <code>row</code>, <code>column</code> and <code>4 &lt;= stride &lt;= 36</code> that returns when
<code>cast(s64)at + 4 * cast(s64)stride &gt;= levels.count</code>, <code>levels[at + 1]</code>,
<code>levels[at + stride]</code> and <code>levels[at + 4 * stride]</code> need no check unless
something writes <code>row</code>, <code>column</code> or <code>stride</code> in between. Every step of the
guard and of the index must provably not wrap, so
<code>if first + 1 + second &gt; view.count { return }</code> does not prove <code>view[first]</code>. Run
<code>sh tests/guarded_index_ranges.sh build/bin/ziran</code>.</p>
<p>An <code>if</code> inside a loop only adds to what the loop proves. After
<code>if flag &gt; 3 { continue }</code>, <code>if i &gt;= 32 { continue }</code> or
<code>if code != 0 { return code }</code>, and inside <code>if i &lt; 32 { ... }</code>, the read
<code>view[i * width + j]</code> in <code>for i: 0..height - 1</code> still uses <code>i &lt;= height - 1</code>.
Facts chain, too: inside <code>for j: 0..width - 1</code> the width is at least 1, so
after <code>if stride &lt; width || samples.count &lt; (cast(s64)height - 1) * stride + width { return }</code>
the read <code>samples[i * stride + j]</code> needs no check. A local chosen by <code>ifx</code>,
such as <code>yy := ifx flip_rows then cast(s64)height - 1 - i else i</code>, is proven
for both choices, so <code>samples[yy * stride + xx]</code> needs none either. The
guard may also write <code>cast(s64)(height - 1) * stride</code>: inside the loop
<code>height</code> is at least 1, so <code>height - 1</code> did not wrap in <code>s32</code>. A long
<code>||</code> guard works as well as a short one: comparisons about values no index
reads, such as <code>gain &gt; 255</code>, do not crowd out the ones it needs. A window
offset such as <code>(iy + 2 - radius) * stride + 2 - radius + k * stride + j</code>
is proven too after <code>if radius &lt; 1 || radius &gt; 2 { return }</code>. An <code>else</code>
runs where each branch before it was false: after <code>if i == 0 { ... }</code> and
<code>else if j == 0 { ... }</code>, the <code>else</code> reads <code>view[(i - 1) * width + j - 1]</code>
without a check, and <code>if i != 8</code> inside <code>for i: 0..8</code> leaves <code>i &lt;= 7</code>.</p>
<p>Fields count as well. For <code>frame: *Frame</code>, after
<code>if source.count != frame.count || destination.count != frame.count { return }</code>
the copy <code>for i: 0..frame.count - 1 { destination[i] = source[i] }</code> needs no
checks: the loop reads <code>frame.count</code> once, before its stores. A field read
through a pointer keeps what guards showed until a call or a store through
any pointer, slice or global could change it, so a read after <code>Grow(frame)</code>
or <code>other.count = 0</code>, or in a loop body that stores through a slice, keeps
its check. A record parameter's fields, such as <code>shape.width</code> for
<code>shape: Shape</code>, change only with the parameter. Run
<code>sh tests/field_guard_ranges.sh build/bin/ziran</code>.</p>
<p>A local declared without a value starts at zero, and generated C leaves
the fill out when every element is stored before anything could read it.
For <code>block: Block</code> with <code>samples: [64]u16</code>, the loop
<code>for i: 0..7 { Simd.Store(block.samples[:], i * 8, row) }</code> writes every
lane, so C declares <code>Block block;</code>. Stores count at constant positions, in
loops with constant bounds, one field at a time or whole; a branch or loop
that names nothing of the local is passed over. The fill stays when a store
may be missing or late: a loop that stops or skips early, a store or break
under a condition not known there, any earlier use of the local such as a
read, a view or a <code>using</code> field, an index not known or one that wraps, and
records whose fields differ in size. Run
<code>sh tests/definite_initialization.sh build/bin/ziran</code>.</p>
<p>Generated C keeps Ziran's integer rules: a zero divisor or a shift count
outside 0 to width-1 aborts, and the minimum signed value divided by -1 wraps
to itself. Arithmetic compiles to C operators, a constant divisor or shift
count needs no check, and other divisions and shifts call a small checked
helper of their width. Generated Go shifts by a variable count in the
operand's own type after checking the count.</p>
<p><code>#parallel_gpu for</code> is an explicit Gap on every target. The checker still
enforces the GPU storage and argument rules, but no target has a GPU device
backend and CPU execution is never substituted. There are no GPU device
selection environment variables.</p>
<p>In a closed program the entry is C's <code>main</code> itself, with no adapter and no
other name: <code>int main(void)</code>, or <code>int main(int argc, char **argv)</code> when the
body uses its parameters. An <code>s32</code> count is main's own parameter, other
parameter types the body reads are copied from main's, an integer result is
the process status and a procedure returning nothing returns 0. This also
applies to a procedure exported under the symbol <code>main</code> through
<code>#program_export "main"</code>.</p>
<p>The entry keeps its own name, and a standard <code>int main(int, char **)</code> adapter
calls it, when other code in the program calls it or takes it as a value, when
it is exported under another symbol, when it carries assembly or <code>#target</code>
clones, in a library build and with <code>--no-main</code>. The procedure keeps its
declared parameter and result types for those calls and function values. The
adapter converts its integer result to a process status; a procedure returning
nothing exits successfully.</p>
<p>C-generated executable builds compile source files concurrently on at most half
of the available CPUs, with no more workers than free memory holds at 512 MiB
each; <code>ZIRAN_JOBS=N</code> lowers the count. Compiler commands run at niceness 10
with low disk priority, which their C compilers inherit; <code>ZIRAN_NICE=N</code>
chooses another niceness from 0 to 19. The build links and replaces the
executable only after success. The output directory has
a writer lock and keeps intermediate objects under <code>.objects</code>; unchanged
objects can be reused with supported GCC/Clang invocations. Reuse checks source
and header contents (including system headers), compiler executables and their
reported subtools, command flags, the environment and header search locations.
New headers that shadow an earlier dependency invalidate reuse too. The driver
always links again, so changed libraries reach the executable.</p>
<p>Compiler wrappers, unsupported flags, time macros, nonliteral header probes and
assembly includes use ordinary compilation. Missing or damaged cache files
are rebuilt. Nested generated modules and manually supplied root-level C hosts
participate in the link.</p>
<p>Use
<code>ziran build --target=go --pkg main --exe --entry module:function -o DIR</code>
for Go output. C foreign procedures with scalar or pointer parameters and
results route through generated cgo adapters; native Go package imports
continue to call those packages directly. C ABI calls need <code>CGO_ENABLED=1</code>
and a C compiler. <code>LDFLAGS</code> and <code>LDLIBS</code> are preserved in the cgo preamble.
Slice, record and variadic C ABI parameters are rejected on Go; modules
can wrap those APIs with scalar and pointer declarations.</p>
<p>Go can also bind a C header directly with <code>go:C/&lt;relative-header&gt;</code>. The header
supplies the function declarations and native type layout; generated adapters
do not redeclare its ABI. For example:</p>
<pre><code class="language-ziran">c :: #system_library &quot;go:C/example/signature.h&quot;;
builtin :: #system_library &quot;go:builtin&quot;;
Signature :: #type #foreign c &quot;signature&quot;;
New :: () -&gt; *Signature #foreign c &quot;signature_new&quot;;
Length :: (value: *Signature) -&gt; usize #go_field #foreign c &quot;(*signature).length&quot;;
FreeAtReturn :: (value: *Signature) #go_defer #foreign c &quot;signature_free&quot;;
NativeAvailable :: () -&gt; bool #foreign builtin &quot;cgo_enabled&quot;;
</code></pre>
<p>Header calls accept scalar values and pointers to scalars or declared C types.
<code>#go_field</code> supports native fields and header constants; <code>#go_defer</code> preserves
cleanup during returns and panic unwinding. Pass include and library paths to
Go through <code>CGO_CFLAGS</code> and <code>CGO_LDFLAGS</code>, or preserve linker flags at generation
through <code>LDFLAGS</code> and <code>LDLIBS</code>. Calls still obey cgo's pointer ownership rules.
Header paths cannot be absolute or contain empty, <code>.</code> or <code>..</code> segments.</p>
<p>Header bindings generate <code>.cgo.go</code> and <code>.nocgo.go</code> companions. Ordinary Ziran
procedures remain available in either build. <code>cgo_enabled</code> reports the native
build setting so application code can choose its unavailable path before a C
call. With <code>CGO_ENABLED=0</code>, C pointer types are opaque and C calls panic instead
of fabricating results. Build the generated Go package with <code>go build .</code> or
<code>go run .</code>, which honor the build tags. Reachable header bindings and native
availability checks require Go; pruning a portable entry can remove them.</p>
<p>Pass <code>--entry module:function</code> to a C99 build to retain functions, types,
globals, and constants reachable from that entry. A native host implementation
of a called foreign function is retained when it is among the input modules.
Type-only linked modules emit headers without empty C files. Without <code>--entry</code>,
all checked declarations and module C files are emitted as before. Runtime
branches in reachable functions remain; this pass does not specialize them.</p>
<p><code>ziran compile-commands DIR</code> writes <code>DIR/compile_commands.json</code> for the C
files in <code>DIR</code>, so clangd and other editors can read generated code with the
flags it builds with. <code>--compiler "cc -O2"</code> sets the compiler and its extra
flags (default <code>$CC</code>, then <code>cc</code>), <code>--include DIR</code> names Ziran's headers
(default: the pinned toolchain's with <code>--project</code>, otherwise the checkout
beside the launcher), and <code>-o FILE</code> writes elsewhere.</p>
<h2 id="save-and-inspect-zir-modules">Save and inspect ZIR modules</h2>
<p><code>ziran ir --entry module:function</code> saves that reachable graph as
per-module <code>.zir</code> files before code generation.</p>
<h3 id="compile-time-target-facts">Compile-time target facts</h3>
<p>The typed compile-time values <code>TARGET</code>, <code>OS</code>, and <code>CPU</code> describe the selected
output, never the machine running the compiler. <code>TARGET</code> is an enum with <code>.C</code>,
<code>.GO</code>, <code>.WASM</code>, and <code>.ZX</code>; <code>OS</code> has <code>.LINUX</code>, <code>.WINDOWS</code>, <code>.MACOS</code>, <code>.ANDROID</code>,
<code>.WEB</code>, and <code>.NONE</code>; and <code>CPU</code> has <code>.X64</code>, <code>.ARM64</code>, <code>.WASM32</code>, and <code>.NONE</code>.
They work in <code>#if</code>, <code>#ifx</code>, <code>#assert</code>, and <code>#run</code>, including compound tests:</p>
<pre><code class="language-ziran">#if TARGET == .C &amp;&amp; OS == .LINUX {
File :: #import &quot;std/file_linux&quot;
}
</code></pre>
<p>Imports in an inactive <code>#if</code> arm are not loaded. Native C and Go compilers use
the host OS and CPU by default and accept <code>--target-os</code> and <code>--target-cpu</code> for
cross-target output. WebAssembly selects <code>.WASM</code>/<code>.WEB</code>/<code>.WASM32</code>; portable ZX
selects <code>.ZX</code>/<code>.NONE</code>/<code>.NONE</code>.</p>
<p>Metaprograms that actually need compiler-machine information use
<code>Compiler.HostOS</code> and <code>Compiler.HostCPU</code>. <code>Compiler.Target</code>,
<code>Compiler.TargetOS</code>, <code>Compiler.TargetCPU</code>, and the string <code>Compiler.Options</code>
report the selected compilation. Host facts must not select target imports.</p>
<p>An untargeted <code>ziran ir</code>/<code>zi2zir</code> invocation is deliberately portable: it
checks with <code>TARGET == .ZX</code>, <code>OS == .NONE</code>, and <code>CPU == .NONE</code>, folds all
compile-time directives, and saves those results in <code>.zir</code>. Loading that file
later does not reevaluate compile-time branches for the consuming backend.
Select an explicit target while creating IR when a native-platform result is
intended.</p>
<p><code>ziran bundle --entry module:function --retain other:entry</code> also keeps the
named function and its dependencies. Repeat <code>--retain</code> for further entry
points; unrelated functions remain outside the payload. Every retained entry
must exist in the checked input graph.
Saved <code>.zir</code> files are binary. <code>ziran inspect path/to/module.zir</code> shows their
declarations, statements, and checked expression links as readable text;
<code>ziran inspect --hex path/to/module.zir</code> shows bytes and offsets.
<code>ziran inspect program.zx</code> shows a portable bundle’s entry, linked modules and
assets without executing it; <code>--hex</code> shows its binary bytes.
<code>ziran build --target=wasm --entry module:main --root DIR -o program.wasm FILE.zi</code>
produces WebAssembly. Its <code>zx.host_i64</code> dispatch reserves index <code>UINT32_MAX</code>
for builtin string output: the i64 argument packs byte length in its upper
32 bits and memory offset in its lower 32 bits; the callback writes those bytes
and returns zero. Other reserved indices format signed integers (<code>UINT32_MAX - 1</code>),
unsigned integers (<code>- 2</code>), float64 bits (<code>- 3</code>), float32 bits (<code>- 4</code>), and booleans
(<code>- 5</code>). Scalar formatted print arguments use these callbacks. Host capabilities
cross through the typed <code>zx.host</code> import that <a href="zx.html">ZX</a> describes. Slices support
omitted bounds (<code>values[:]</code>, <code>values[:end]</code>, <code>values[start:]</code>) and empty views
at the end of their storage. Both inspection views read the saved file and
leave it unchanged.</p>
<h2 id="imports">Imports</h2>
<p>For ordinary imports, pass the entry file and a library directory with
<code>--module-path DIR</code> (repeat for multiple directories). There is no fixed
module-root count limit; storage grows with the inputs, subject to available
memory and operating-system argument limits. Search order remains the order
of the supplied paths. <code>check</code>, <code>ir</code>,
<code>api</code>, <code>build</code>, and <code>bundle</code> load extensionless <code>#import "module"</code> dependencies
transitively from <code>.zi</code> or saved <code>.zir</code>. For example:</p>
<pre><code class="language-sh">build/bin/zi2zir --check-only --root app --module-path ../kryon/src/ui app/main.zi
</code></pre>
<p>A package-qualified import such as <code>#import "kryon/text"</code> resolves
through the package's dependencies in a <code>--project</code> build. Quoted export keys
may contain identifier-only namespaces: <code>[exports] "host/desktop" =
"src/host/desktop.zi"</code> is imported as <code>#import "kryon/host/desktop"</code>.
Outside a project, name the package's module directory instead:
<code>--module-path kryon=../kryon/src/ui</code> serves <code>kryon/NAME</code> imports from that
directory (and only those; repeat it for more directories). A package
builds the same way in both modes when each export has its module's name.
With <code>--project</code>, <code>--module-path DIR</code> adds a folder of generated modules to
the project's own package only; see
<a href="packages.html#generated-modules">generated modules</a>.</p>
<p><code>#import, file "../lib/helper.zi";</code> loads an explicit source file relative to
the importing file. Saved <code>.zir</code> builds resolve its module by name from the
saved IR directory or a module path.
<code>Helper :: #import "helper";</code> and
<code>Helper :: #import, file "../lib/helper.zi";</code> expose public declarations as
<code>Helper.Name</code> without adding them to the unqualified scope.
<code>Helper :: #import, dir "../lib/helper";</code> loads that directory's <code>module.zi</code>.
An ordinary <code>#import "helper"</code> also discovers <code>helper/module.zi</code> on a module
search path.
<code>#load "relative/file.zi";</code> adds another file to the current module. Loads
can nest, and imports inside loaded files resolve relative to those files.
<code>#import, string "Value :: () -&gt; s32 { return 42 }";</code> compiles source text
as a module. It also accepts a raw <code>#string</code> body, and
<code>Generated :: #import, string "...";</code> exposes its declarations as
<code>Generated.Name</code>.</p>
<h3 id="module-initializers">Module initializers</h3>
<p>A module-level variable whose initializer calls a procedure is the module's
initializer. It runs once, before the entry, after the initializers of the
modules it imports, on the C, Go and portable targets alike:</p>
<pre><code class="language-zi">// feature.zi
Host :: #import &quot;host&quot;;
Double :: (value: s32) -&gt; s32 { return value * 2 }
registered: bool = Host.Register(Double);
</code></pre>
<p>Importing a module is what includes it. <code>#import "feature"</code> runs the
initializer even when the importer names nothing from the module, so a module
can register a procedure with another module that never imports it. A program
that does not import <code>feature</code> carries neither that module nor anything only
it reaches, and <code>Host</code> finds its procedure variable still null.</p>
<p>This is how an optional part of a library stays out of programs that do not
use it. The library calls the part through a procedure variable instead of
importing it, and the module a caller imports to use the part registers it.
An exported procedure that nothing calls is left out in the same way.
A startup cycle between initializers aborts the program at startup; no
initializer is skipped or run twice.</p>
<h3 id="module-parameters">Module parameters</h3>
<p>A module can declare compile-time parameters as its first declaration, and a
program chooses their values where it imports the module. Each parameter is an
ordinary <code>NAME :: value</code> constant of the module, so <code>#if</code>, <code>#ifx</code>, <code>#run</code>,
array lengths and other constants see the chosen value. Code that an <code>#if</code>
leaves out never reaches C, Go, ZX, Wasm or native code:</p>
<pre><code class="language-zi">// fonts.zi
#module_parameters(STB := false, CACHE: s32 = 8, LABEL := &quot;plain&quot;)
#if STB {
Raster :: (code: s32) -&gt; s32 { return code + 1000 }
}
Glyph :: (code: s32) -&gt; s32 {
#if STB {
return Raster(code)
}
return code + CACHE
}
Table: [CACHE]s32;
// app.zi
Fonts :: #import &quot;fonts&quot;(STB = false, CACHE = 4);
</code></pre>
<p>Only comments and blank lines may come before <code>#module_parameters</code>, and it
belongs in the module's entry file (<code>module.zi</code> for a directory module). Each
parameter is <code>NAME := literal</code>, which takes its type from the literal (<code>bool</code>,
<code>string</code>, <code>s64</code> for an integer, <code>float64</code> for a float), or <code>NAME: Type =
literal</code>, with <code>bool</code>, <code>string</code>, an integer type or a float type. Every
parameter needs a default. A quoted module import names parameters as
<code>(NAME = literal, ...)</code>; values are integer, float or string literals, <code>true</code>
or <code>false</code>. <code>#import, file</code>, <code>#import, dir</code> and <code>#import, string</code> take no
parameters.</p>
<p>One program binds each module's parameters once. Every import of a module
has to give every parameter the same value, with omitted parameters taking
their defaults, so <code>#import "fonts"</code> and <code>#import "fonts"(STB = true)</code> cannot
meet in one program. Integer values compare by number: <code>CACHE = 0x4</code> and
<code>CACHE = 4</code> agree. Different programs that share the module can choose
differently. These named diagnostics reject an import:</p>
<ul>
<li><code>module.parameter_unknown</code>: the module does not declare that name.</li>
<li><code>module.parameter_type</code>: the value does not fit the declared type,
including an integer outside its range.</li>
<li><code>module.parameter_conflict</code>: another import of the same module gives it a
different value.</li>
</ul>
<p>Saved <code>.zir</code> keeps each import's list and each module's declared types,
defaults and bound values. A saved import that disagrees with the module it
loads is rejected the same way. The checks are the same for source and saved
IR, so no backend needs to know about parameters.</p>
<h3 id="generated-declarations">Generated declarations</h3>
<p><code>#insert NAME;</code> at file scope splices the text of a compile-time string
constant into the module where the directive stands. The text is checked like
the rest of the file, so a compile-time procedure can write declarations that
generics cannot express. The constant can be a string, a raw <code>#string</code> body or
a <code>#run</code> call of a pure procedure:</p>
<pre><code class="language-zi">LEVEL :: 3;
BuildPowers :: (cube: bool) -&gt; string {
square := &quot;Square :: (x: s32) -&gt; s32 { return x * x }\n&quot;
if cube { return &quot;Square :: (x: s32) -&gt; s32 { return x * x }\nCube :: (x: s32) -&gt; s32 { return x * Square(x) }\n&quot; }
return square
}
POWERS :: #run BuildPowers(LEVEL &gt; 2);
#insert POWERS;
</code></pre>
<p>The constant is evaluated before the module's declarations are read, with the
rules and step budget of <code>#run</code>, so declarations it adds are visible anywhere
in the module, including to <code>#if</code> conditions and <code>#run</code> calls above the
<code>#insert</code>. A value that is not a compile-time string, such as a global, fails.
Inserted text shares the file's scope and <code>#scope_file</code> privacy, and its
diagnostics name the line of the <code>#insert</code>. <code>#insert</code> stays outside procedure
bodies and <code>#if</code> blocks, and inserted text cannot <code>#insert</code> again; choose the
text with <code>#run</code> or <code>#ifx</code> instead. Saved IR holds only the checked
declarations, so every backend sees them as if they had been written by hand.</p>
<h2 id="foreign-functions">Foreign functions</h2>
<p>Ordinary <code>#import</code> accepts a module identifier. C headers are no longer
imported as source modules; foreign procedures use <code>#system_library</code> and
<code>#foreign</code> declarations.
For a native symbol with an unmangled name, put <code>#program_export</code> on its own
line immediately before the function declaration.
Foreign procedures use a Jai-style library declaration and <code>#foreign</code>:</p>
<pre><code class="language-jai">libc :: #system_library &quot;libc&quot;;
Abs :: (value: s32) -&gt; s32 #foreign libc &quot;abs&quot;;
</code></pre>
<h3 id="go-packages">Go packages</h3>
<p>For a Go package, use an explicit <code>go:</code> library path. This also supports
standard packages whose import paths contain no slash:</p>
<pre><code class="language-jai">strings :: #system_library &quot;go:strings&quot;;
TrimSpace :: (value: string) -&gt; string #foreign strings &quot;TrimSpace&quot;;
</code></pre>
<p>The Go target emits a direct package call. These declarations remain Go
imports in saved <code>.zir</code>; they are not portable host capabilities.</p>
<p>An explicit <code>#program_export "NativeName"</code> emits a typed Go function with that
exact name. Checked Ziran calls retain their module-qualified implementation
name. Reserved names and collisions with functions, types, imports and module
startup are rejected; colliding globals and constants keep their generated
private names.</p>
<p>Native Go tests use <code>_test.zi</code> files and named exports such as
<code>#program_export "TestSigning"</code>. Modules using native <code>testing</code> bindings or
named test, fuzz and benchmark exports generate <code>_test.go</code> files, including
when their module names need disambiguation. Their native adapters expose
<code>*testing.T</code>, <code>*testing.F</code>, <code>*testing.B</code> or <code>*testing.M</code> directly for Go's test
discovery. Test helper modules may import the testing bindings from another
Ziran module. Ordinary Ziran checks without this native boundary retain the
<code>_test_ziran.go</code> filename and remain ordinary package code.</p>
<p>To require a package for its native initialization, bind its <code>init</code> symbol as a
nullary void procedure:</p>
<pre><code class="language-ziran">driver :: #system_library &quot;go:example.org/database/driver&quot;;
Initialize :: () #foreign driver &quot;init&quot;;
</code></pre>
<p>The generated Go import runs the package's initialization once, before the
generated package's globals. The binding's call then has no work to repeat.
If no types or functions need a named import, the compiler emits a blank import.
Initialization bindings accept no receiver, parameters, results or modifiers.
Keep a call on the entry's dependency path when generating a pruned executable.</p>
<p>Generated Go executable entries carry the same provenance header and output
ownership as other generated files. <code>--prune-stale</code> removes an old entry when
the output directory is later generated with <code>--no-main</code>.</p>
<h3 id="foreign-go-types">Foreign Go types</h3>
<p>Declare an opaque Go type alongside the package's foreign procedures:</p>
<pre><code class="language-jai">json :: #system_library &quot;go:encoding/json&quot;;
RawMessage :: #type #foreign json &quot;RawMessage&quot;;
Envelope :: struct {
payload: RawMessage #go_tag &quot;json:\&quot;payload\&quot;&quot;
}
</code></pre>
<p>The Go target emits a type alias, preserving the imported type's identity,
methods, interface behavior and zero value. Ziran can store, pass, return and
assign these values, including across imports. Fields and layout remain opaque:
record literals and <code>size_of</code> are unavailable. These declarations require an
explicit <code>go:</code> package and are preserved in ZIR. Other targets reject
foreign Go types; an entry build can discard them when they are unused.</p>
<p>A slice can be explicitly converted to or from a foreign Go type whose
underlying storage supports the conversion. The Go compiler checks that
underlying type. Conversions preserve native length, capacity, nil values
and shared backing storage; returned native slices keep that storage alive:</p>
<pre><code class="language-jai">Wrap :: (value: []u8) -&gt; RawMessage { return cast(RawMessage)value }
Unwrap :: (value: RawMessage) -&gt; []u8 { return cast([]u8)value }
</code></pre>
<p>Fixed-array casts, slice-to-slice casts and owned vector elements are rejected.</p>
<h3 id="go-receivers-fields-and-multiple-results">Go receivers, fields and multiple results</h3>
<p>A quoted method expression supplies its receiver as the first parameter.
The receiver must match an opaque type declared from the same Go package:</p>
<pre><code class="language-jai">sync :: #system_library &quot;go:sync&quot;;
Mutex :: #type #foreign sync &quot;Mutex&quot;;
Lock :: (value: *Mutex) #foreign sync &quot;(*Mutex).Lock&quot;;
Unlock :: (value: *Mutex) #foreign sync &quot;(*Mutex).Unlock&quot;;
</code></pre>
<p>Use <code>#go_field</code> before <code>#foreign</code> to read a native field through a typed
getter. It takes exactly one receiver and returns the field value. The Go
compiler verifies that the field exists and has the declared storage type:</p>
<pre><code class="language-jai">http :: #system_library &quot;go:net/http&quot;;
Request :: #type #foreign http &quot;Request&quot;;
Remote :: (request: *Request) -&gt; string #go_field #foreign http &quot;(*Request).RemoteAddr&quot;;
</code></pre>
<p>A getter without a receiver or parameters reads a native package variable or
constant each time it is called. It preserves native interface identity:</p>
<pre><code class="language-jai">#import &quot;go_types&quot;
sql :: #system_library &quot;go:database/sql&quot;;
NoRows :: () -&gt; Error #go_field #foreign sql &quot;ErrNoRows&quot;;
</code></pre>
<p>Getters cannot return owned vectors or records/slices containing them.
A field accessor with a void return is a setter. It takes a pointer receiver
and one value, or just one value when assigning a package variable:</p>
<pre><code class="language-jai">time :: #system_library &quot;go:time&quot;;
Duration :: #type #foreign time &quot;Duration&quot;;
Client :: #type #foreign http &quot;Client&quot;;
SetTimeout :: (client: *Client, value: Duration) #go_field #foreign http &quot;(*Client).Timeout&quot;;
SetDefault :: (client: *Client) #go_field #foreign http &quot;DefaultClient&quot;;
</code></pre>
<p>Setters cannot take owned storage or a value receiver. The Go compiler checks
the field's type and whether the package value can be assigned. Accessors
cannot use variadic parameters, <code>#go_results</code>, or <code>#go_defer</code>.
Methods of predeclared Go interfaces use their native receiver spelling,
for example <code>#foreign builtin "error.Error"</code> with an <code>Error</code> parameter.</p>
<p>Ordinary procedures can implement native Go interfaces with
<code>#go_method "MethodName"</code>. The first parameter is a local named record or its
pointer; remaining parameters and the result form the native method signature.
The generated method calls the ordinary Ziran procedure, preserving pointer,
error and panic identity. Method names must be Go identifiers, unique for the
receiver record, and different from its generated field names. Foreign types,
anonymous record aliases, generic procedures and owned vector signatures are
rejected. Go checks interface satisfaction when compiling the generated code.</p>
<pre><code class="language-jai">Message :: struct { text: string }
Describe :: (message: Message) -&gt; string #go_method &quot;Error&quot; {
return message.text
}
</code></pre>
<p>On an ordinary method procedure, <code>#go_results</code> flattens a nonempty concrete
result record into native Go multiple results in field order. Its fields must
be named without <code>using</code> or owned vectors. Ordinary Ziran calls still receive
that record. C and the portable engine keep the same ordinary procedure body;
method adapters are Go ABI metadata. Both attributes survive saved IR. Go
executable entry selection retains methods of reachable receiver records for
native interface dispatch.</p>
<p>Use <code>#go_results</code> on foreign declarations to pack a Go function's multiple
results into a concrete record. Record fields correspond to Go results in
declaration order, including native error interfaces. It also works with method expressions:</p>
<pre><code class="language-jai">#import &quot;go_types&quot;
net :: #system_library &quot;go:net&quot;;
HostPort :: struct { host: string; port: string; error: Error }
Split :: (address: string) -&gt; HostPort #go_results #foreign net &quot;SplitHostPort&quot;;
</code></pre>
<p>The result record must be nonempty, without owned vectors, <code>using</code> fields or
discard fields. Variadic declarations and combinations with <code>#go_field</code> are
rejected. Both attributes require explicit Go package targets. ZIR
stores their typed signatures and attributes; generation from saved IR does
not infer them from diagnostic source text.</p>
<p>The standard modules <code>sync_go</code>, <code>time_go</code>, <code>random_go</code>, <code>text_go</code>, <code>net_go</code>
and <code>http_go</code> expose mutexes, native monotonic timestamps, cryptographic random
bytes, copied byte strings, IP primitives, HTTP request fields and headers.
<code>atomic_go</code> provides native <code>Uint64</code> counters with atomic <code>Add</code> and <code>Load</code>.
<code>http_go</code> also preserves the native <code>ResponseWriter</code> interface and exposes
response headers and <code>SetHeader</code>.
<code>time_go</code> provides parsing, UTC conversion and formatting while preserving
native <code>time.Time</code> values and parse errors. It also provides native ticker
creation, stopping and boxed channel access. <code>context_go</code> preserves native
contexts and provides <code>Background</code> and the boxed cancellation channel <code>Done</code>.
<code>select_go</code> builds receive, send and default cases over boxed native channels.
<code>Select</code> blocks until a case is ready and returns its index, native reflected
value and receive-success flag. It uses Go's <code>reflect.Select</code>; channel direction
and send-value compatibility are checked at runtime. Nil channels disable their
case, closed channels retain their zero-value/false receive result, and multiple
ready cases use Go's selection behavior. These operations require the Go target.
<code>sql_go</code> exposes native database,
transaction, row and result handles, nullable strings, row iteration and
transaction cleanup. Declare query, execution and scan bindings with the
argument types required by the application; Go checks those native signatures.
<code>errors_go</code> provides native error creation, <code>Is</code>, <code>Unwrap</code> and exact messages.
SQL and context modules expose their native error sentinels through getters.</p>
<h3 id="go-deferred-foreign-calls">Go deferred foreign calls</h3>
<p>Declare a void foreign procedure with <code>#go_defer</code> to schedule its native Go
call at the end of the calling function, including panic unwinding:</p>
<pre><code class="language-jai">#import &quot;sync_go&quot;
sync :: #system_library &quot;go:sync&quot;;
UnlockAtReturn :: (value: *Mutex) #go_defer #foreign sync &quot;(*Mutex).Unlock&quot;;
Work :: (mutex: *Mutex) {
Lock(mutex)
UnlockAtReturn(mutex)
// Work while the mutex is locked.
}
</code></pre>
<p>Arguments are evaluated and captured at the call statement. Scheduled calls
run in reverse order when that function returns or panics; a nested block
does not end the schedule. Declare and call the foreign binding in the
function that needs cleanup. A Ziran wrapper would schedule cleanup at the
wrapper's own return.</p>
<p>The binding requires an explicit Go package target, a void result and no
owned vector arguments or variadic parameters. <code>#go_results</code>, <code>#go_field</code>
and Go predeclared builtins other than typed <code>call</code> cannot be combined with this
attribute. Calls must be standalone statements. ZIR preserves the attribute, and
other targets reject reachable Go bindings. Ordinary Ziran <code>defer</code> keeps
its lexical scope cleanup semantics across targets.</p>
<p>Typed <code>go:builtin</code> <code>call</code> declarations invoke their first procedure argument
with the remaining arguments. The declaration must match that procedure's
parameter and result types and cannot carry owned vector values. A void call
can use <code>#go_defer</code> to run application cleanup during native Go panic unwinding:</p>
<pre><code class="language-jai">builtin :: #system_library &quot;go:builtin&quot;;
Cleanup :: #type (completed: *bool) -&gt; void;
CleanupAtReturn :: (callback: Cleanup, completed: *bool) #go_defer #foreign builtin &quot;call&quot;;
</code></pre>
<p>The callback and its arguments are captured when scheduled. Pass a pointer
when cleanup needs to observe a value changed later in the calling function.
ZIR retains the typed callback and the schedule independently of the
declaration's diagnostic source text.</p>
<p>Typed <code>go:builtin</code> <code>bind</code> declarations capture one or more leading procedure
arguments and return a procedure for the remaining arguments. The first
parameter is the full procedure type; subsequent parameters match its leading
parameters. The returned procedure matches its remaining parameters and result.
Captured values are copied when binding, so pointers retain shared storage while
later replacement of a value does not alter the capture. Binding never invokes
the procedure; native errors, slices and panic values retain their identity.
Captured parameters, remaining parameters and results cannot contain owned
vectors. C callback types are rejected. These signatures are checked in both
source and saved IR.</p>
<p>Ordinary procedure values also resolve each parameter and result in the
declaring procedure type's module. Imported records, pointers, slices and native
Go interfaces keep their type identity across different import aliases.</p>
<pre><code class="language-jai">builtin :: #system_library &quot;go:builtin&quot;;
Full :: #type (count: *s64, amount: s64) -&gt; s64;
Bound :: #type (amount: s64) -&gt; s64;
Bind :: (callback: Full, count: *s64) -&gt; Bound #foreign builtin &quot;bind&quot;;
</code></pre>
<p>Typed <code>go:builtin</code> <code>retain</code> declarations return their one argument unchanged
under Go's managed storage lifetime. The parameter and result types must match
and cannot contain owned vectors. This explicit native boundary allows strings,
slices and records read through pointers to escape a procedure while preserving
their original storage and nil values. It does not copy backing data or keep
foreign C allocations alive; such allocations retain their foreign lifetime.</p>
<p>Typed <code>go:builtin</code> <code>spawn</code> declarations start the first procedure argument in
a native Go goroutine with the remaining arguments. The callback and binding
must return <code>void</code>; their parameter types must match and cannot contain owned
vectors. Arguments are captured before starting the goroutine. Native Go
pointer, slice, map and channel storage stays alive under Go's collector;
shared mutation still requires synchronization. <code>spawn</code> cannot use <code>#go_defer</code>.</p>
<p>Typed <code>go:builtin</code> <code>assert</code> declarations use <code>#go_results</code> and one <code>Any</code>
argument. Their result record has exactly two fields: the target value type
and a <code>bool</code> indicating whether the native Go type assertion succeeded. A
failed assertion returns the target type's zero value and <code>false</code>; a typed
nil can succeed and stays distinct from a nil interface. Asserted slices,
pointers and interfaces retain native storage and identity.</p>
<pre><code class="language-jai">#import &quot;std/go_types&quot;
builtin :: #system_library &quot;go:builtin&quot;;
Worker :: #type (value: s64) -&gt; void;
Start :: (callback: Worker, value: s64) #foreign builtin &quot;spawn&quot;;
IntegerAssertion :: struct { value: s64; present: bool }
AsInteger :: (value: Any) -&gt; IntegerAssertion #go_results #foreign builtin &quot;assert&quot;;
</code></pre>
<p>These operations and the <code>std/channel_go</code> native channel handles are specific
to Go. <code>std/context_go.WithCancel</code> and <code>WithTimeout</code> return a native context
and its cancellation function; call <code>Cancel</code> to release that context. Schedule
cancellation in the owning function with a typed deferred callback when it
must also run during native panic unwinding. Other targets reject reachable
Go bindings; unused Go-only functions can still be excluded from a portable
bundle.</p>
<p><code>io_go</code> exposes native readers, closable readers, writers and <code>ReadAll</code>.
<code>http_go</code> supplies request bodies and contexts, bounded body readers and
response status writes. <code>json_go</code> supplies JSON validation and streaming
encoders and decoders; <code>url_go</code> supplies decoded query values. Native interface
conversions keep the original stream and context objects, and these operations preserve
Go error identity. Schedule <code>ReadCloser.Close</code> with <code>#go_defer</code> in the function
that owns the stream when cleanup must also run after a panic.</p>
<h3 id="go-predeclared-primitives">Go predeclared primitives</h3>
<p>Typed foreign declarations in <code>go:builtin</code> can allocate Go heap objects and
slices/maps, copy bytes into a string, or read a native length:</p>
<pre><code class="language-jai">builtin :: #system_library &quot;go:builtin&quot;;
Allocate :: () -&gt; *HostPort #foreign builtin &quot;new&quot;;
Bytes :: (count: isize, capacity: isize) -&gt; []u8 #foreign builtin &quot;make&quot;;
Text :: (value: []u8) -&gt; string #foreign builtin &quot;string&quot;;
Length :: (value: []u8) -&gt; isize #foreign builtin &quot;len&quot;;
Append :: (values: []u8, value: u8) -&gt; []u8 #foreign builtin &quot;append&quot;;
Panic :: (value: Error) #foreign builtin &quot;panic&quot;;
</code></pre>
<p><code>new</code> takes no arguments and derives the allocated type from its pointer
result. <code>make</code> derives its slice or map type from the result; slices take a
length and optional capacity, and maps take an optional size hint. <code>len</code>
returns <code>isize</code> and accepts strings, arrays, slices, maps and declared foreign
Go types whose underlying type supports native <code>len</code>. Go compilation checks
the underlying operation for opaque types. These calls need no package import
and retain Go's allocation, zero-value and byte-copy behavior.
<code>append</code> takes a slice and one element, returns the same slice type, and keeps
Go's length, capacity and shared backing-storage behavior. Owned vector
elements are rejected; variadic slice expansion is not supported by this binding.
<code>panic</code> takes one non-owned value and returns void. It preserves the supplied
native Go value, including error identity, during panic unwinding.</p>
<h3 id="go-record-metadata">Go record metadata</h3>
<p>Go record fields can carry reflection tags. The checked string is preserved
in saved IR and emitted as a Go struct tag; other targets keep the same fields
and ignore this Go metadata:</p>
<pre><code class="language-jai">Response :: struct {
userID: string #go_tag &quot;json:\&quot;user_id\&quot;&quot;
expiresAt: s64 #go_tag &quot;json:\&quot;expires_at,omitempty\&quot;&quot;
}
</code></pre>
<p>Go can preserve an anonymous native struct's identity with <code>#go_anonymous</code>
alone in its record body:</p>
<pre><code class="language-jai">Reply :: struct {
#go_anonymous
code: isize #go_tag &quot;json:\&quot;code\&quot;&quot;
message: string #go_tag &quot;json:\&quot;message\&quot;&quot;
}
</code></pre>
<p>The Go declaration is <code>type Reply = struct { ... }</code>. Native reflection has
an empty type name, and JSON decoding retains anonymous struct error details.
The annotation preserves ordinary checked Ziran fields and is retained in
saved IR. Other targets keep their ordinary record representation.</p>
<h3 id="c-header-spellings">C header spellings</h3>
<p><code>#c "SPELLING"</code> lets a generated C header match C code that shares the
records. On a field it replaces the C type, or an array's element type. Written
last on an enum, it prefixes each C constant. Saved IR keeps it; Go and the
<code>.zx</code> engine ignore it:</p>
<pre><code class="language-jai">ExprKind :: enum s32 #c &quot;ZIR_EXPR_&quot; { Unknown; Ident } // ZIR_EXPR_Ident
Expr :: struct {
name: *u8 #c &quot;const char *&quot;
op: [8]u8 #c &quot;char&quot; // char op[8]
}
</code></pre>
<p>A <code>using</code> field spelled <code>#c "union"</code> (or <code>"struct"</code>) also lays its record's
fields out as an anonymous C member over the same storage, so C reads
<code>stmt-&gt;name</code> where Ziran reads <code>stmt.name</code>.</p>
<h3 id="c-generated-scripts">C-generated scripts</h3>
<p><code>ziran tool.zi ARGS</code> runs ordinary Ziran source as a C-generated script. Use <code>.zi</code>
for scripts and compiled programs alike. On Unix, start executable scripts
with <code>#!/usr/bin/env ziran</code>, give them an ordinary <code>main</code> procedure, and run
<code>chmod +x tool.zi</code> once. Then <code>./tool.zi ARGS</code> works with <code>ziran</code> on <code>PATH</code>.
Every argument after the filename belongs to the script, including <code>--help</code>.
The caller's working directory and standard streams are preserved.</p>
<p>The explicit form, <code>ziran run --target=c [--no-cache] tool.zi -- ARGS</code>,
also accepts compiler options before the filename. The C-generated runner
builds the program once into <code>$XDG_CACHE_HOME/ziran/native</code>, rebuilds it when
its sources change, and runs it with the arguments, returning its status. The
entry takes nothing or <code>(argc: s32, argv: **u8)</code>. In a project, a tool beside
the module roots, such as <code>tools/check.zi</code>, still imports the project's modules.
The tool reads its source path from <code>ZIRAN_SCRIPT_FILE</code>; see
<code>scripts/build_playground.zi</code> for a maintained build tool.</p>
<h3 id="host-capabilities-and-visibility">Host capabilities and visibility</h3>
<p>Ziran also resolves <code>host_api :: #system_library "host_api";</code> to its host
capability bridge. <code>ziran bundle --bind caller:capability=provider:function</code>
can satisfy a portable host capability with an exported Ziran function in the
bundle; the provider must have the same signature. <code>--bind-host MODULE</code>
binds every remaining capability to MODULE's exported function of the same
name, as a C program links a host's symbols by name, so one Ziran host module
serves <code>ziran bundle</code> and the Go target alike.
The portable host ABI copies returned string bytes into engine-managed storage,
including strings inside records, arrays, slices, and mutable slice updates.
A host can reuse its result buffers on its next call; saved strings retain
their bytes for as long as the program uses them, including across instance
runs. Returned fields and elements must remain valid until that next call.
Opaque pointer results still refer to host-owned storage.
Use <code>#scope_file</code>, <code>#scope_module</code>, and <code>#scope_export</code> to change the
visibility of following declarations.</p>
<h2 id="multiline-strings">Multiline strings</h2>
<p>Raw multiline text uses Jai's <code>#string</code> delimiter form. The body keeps its
whitespace and the newline before the closing delimiter:</p>
<pre><code class="language-jai">Greeting :: #string END
Hello, &quot;world&quot;!
END;
</code></pre>
<h2 id="returned-views">Returned views</h2>
<p>A returned slice, text view or record of views must borrow storage the caller
still owns after the call: a slice or string parameter, a view already stored
in a pointed-to record, or static text. A pointer parameter lends its own
array storage only for the call, so return a view of it by taking the storage
as a slice instead:</p>
<pre><code class="language-jai">Owner :: struct { values: [4]u16; label: string; }
Rest :: (values: []u16) -&gt; []u16 { return values[1:] } // view of caller storage
Label :: (owner: *Owner) -&gt; string { return owner.label } // view stored in the record
// Rejected: (owner: *Owner) -&gt; []u16 { return owner.values[:] }
</code></pre>
<p>Call it as <code>Rest(owner.values[:])</code>. Inside the call, views of
<code>owner.values</code> may be read and written freely.</p>
<h2 id="shadowing">Shadowing</h2>
<p>A declaration in an inner block or a <code>for</code> body may reuse an outer name. Its
initializer still reads the outer binding, so <code>x := x + 5</code> adds to the outer
<code>x</code>, and <code>for i: 0..7 { i := i * 10 }</code> keeps counting with the loop's own
<code>i</code>. Two bindings of one name in the same block are rejected.</p>
<h2 id="integer-literals">Integer literals</h2>
<p>Integer literals are decimal, <code>0x</code> hex or <code>0b</code> binary, with <code>_</code> between
digits: <code>1_000_000</code>, <code>0xDEAD_BEEF</code>, <code>0b1010_0101</code>. A <code>u64</code> literal may use the
whole unsigned range, as in <code>0xFFFF_FFFF_FFFF_FFFF</code>. Locals, globals, <code>::</code>
constants, constant tables, array sizes and range bounds accept the same
spellings on every target, and generated C headers spell them in decimal.</p>
<h2 id="standard-library">Standard library</h2>
<p>Import a standard module as <code>#import "std/text"</code>. In a project the pinned
toolchain supplies it. A standalone command takes it from
<code>--module-path std=DIR</code>, a <code>--module-path</code> directory named <code>std</code>, or the
standard modules that came with the compiler: <code>std</code> beside an installed
toolchain (<code>make install-user</code> copies it), otherwise the checkout the
compiler was built from. <code>ZIRAN_STD=DIR</code> names another standard directory.
<code>std/text</code> always means the standard module, even beside a library module
named <code>text</code>. The short spelling <code>#import "text"</code> also works when no module
of your own has that name.
Dependencies from other Git repositories import the same way, as
<code>#import "NAME/Module"</code>; see <a href="packages.html">Packages</a>.</p>
<h3 id="vector-capacity-and-initialized-length">Vector capacity and initialized length</h3>
<p>Import <code>vec</code> to use <code>Vec(T)</code>. <code>VecReserve(values, capacity: s64) -&gt; bool</code>
reserves at least that <strong>total</strong> capacity without changing <code>values.count</code>.
<code>VecResize(values, count: s64) -&gt; bool</code> changes the initialized length: new
entries receive the same default values as uninitialized local declarations
(zero scalars, empty strings, nil views/maps, recursively empty owned vectors).
Shrinking drops removed owned entries and retains capacity. Reused entries
are initialized again on growth; capacity beyond count is never indexable.
Neither operation consumes the vector. Pass mutable storage directly; a live
borrowed view prevents either operation, just as it prevents <code>VecPush</code>.</p>
<pre><code class="language-jai">#import &quot;vec&quot;
pixels: Vec(u8)
if !VecResize(pixels, 4096) { return false }
pixels[0] = 255
</code></pre>
<p>Sizes are <code>s64</code>; negative sizes, size overflow, and failed allocation return
<code>false</code>, preserving the old elements, count and capacity. Zero is valid and
reserving zero allocates nothing. Native C uses one fallible growth allocation;
byte resize initializes its new range in bulk. Other element types use typed
default initialization rather than raw byte clearing of managed values. C,
Go, and portable <code>.zx</code> support both operations from source and saved <code>.zir</code>.
The engine also returns <code>false</code> when its array-storage budget prevents growth.
Go catches recoverable allocation range panics, but physical out-of-memory
failure can terminate the Go runtime. Capacities and allocation limits depend
on the target; a successful capacity request never guarantees future growth.
<code>VecGet</code> and <code>VecClone</code> cannot copy owned elements; mutate them in place or
move an element with <code>VecPop</code>.</p>
<p>A Vec can hold records that own Vecs. <code>VecPush</code> moves such an element in from
a local binding, a call result or a <code>.{...}</code> literal, so the source cannot be
used afterwards. Read and change elements in place: <code>groups[i].parts[j]</code>,
<code>VecPush(groups[i].parts, x)</code>, or <code>for * groups { ... }</code>. <code>for groups</code> and
<code>x := groups[i]</code> would copy owned storage and are rejected. Clearing, popping,
freeing or leaving scope frees the inner Vecs too. A Vec field iterates and
slices in place like a local Vec: <code>for h.items</code>, <code>for * h.parts</code>, <code>for
it.tags</code> inside <code>for * h.parts</code>, and <code>h.items[1:]</code>. While the loop or slice is
live, its elements and the record's other fields stay writable, but pushing
to, freeing or moving that Vec, or a record holding it, is rejected. A record
field that holds Vecs moves out like a Vec field, as in
<code>last := popped.value</code>. <code>Vec(Vec(T))</code> works the
same way. C, Go and portable <code>.zx</code> support this; wasm has no Vec storage.
<code>tests/nested_vec_elements.sh</code> checks it, including a leak check.</p>
<pre><code class="language-zi">Group :: struct { name: string; parts: Vec(string); }
groups: Vec(Group)
group: Group
VecPush(group.parts, &quot;a&quot;)
VecPush(groups, group)
groups[0].parts[0] = &quot;b&quot;
</code></pre>
<p>A global can hold a Vec or <code>Text</code>, alone or in a record. Assigning the
global, or a field of it, frees the old value and takes the new one, as in
<code>collection = CollectionParse(text)</code> or <code>shelf.items = TextCopy(name)</code>. A
declaration, assignment or return that moves a global, as in
<code>taken := collection</code>, takes its storage and leaves the global empty. A call
argument or <code>VecPush</code> element cannot move a global, because that would empty
it as a side effect: pass its address or move it into a local first. A
global cannot be replaced or moved while a view of it is live.
<code>tests/global_owned_storage.sh</code> checks C, saved IR and native and engine bundles.</p>
<p>A field path of a local record, or of a by-value parameter, takes owned
values the same way: <code>shelf.label = TextCopy(name)</code> frees the old label, and
a field moved out, as in <code>taken := shelf.bag.items</code>, can be assigned again.
A whole local still has to be moved before it is replaced. A field cannot be
assigned while a view of it is live, after its binding moved, below a moved
field or through a pointer. <code>tests/local_owned_fields.sh</code> checks these.</p>
<p><code>VecResizeBounded(values, count: s64, maximum_capacity: s64) -&gt; bool</code> uses
<code>VecResize</code>'s initialized-length and owned-element semantics while bounding the
resulting backing capacity. It rejects negative sizes, a count above the
ceiling, or an existing capacity above the ceiling, including on a shrink/no-op.
Rejection or allocation failure leaves storage, length and elements unchanged.
Growth clamps the selected capacity to the ceiling; reuse retains capacity.
A ceiling is not an allocation request, so a large positive ceiling is allowed
when the actual selected allocation fits the target's element/byte limits.
An empty Vec accepts count/ceiling zero without allocation. Future operations
must supply their own ceilings; the bound is not a stored property of the Vec.</p>
<pre><code class="language-zi">scratch: Vec(u32)
maximum_elements: s64 = 1024
if !VecResizeBounded(scratch, 700, maximum_elements) { return false; }
// scratch.count == 700; 700 &lt;= scratch.capacity &lt;= maximum_elements.
</code></pre>
<p>This bounds logical backing element capacity, not allocator size classes,
runtime objects, managed-element allocations, engine validity maps or physical RSS.
During growth old and new backing allocations may be live together. A caller
with a concurrent-live scratch budget must reserve the full possible new
backing allocation in addition to already-live old capacity, then reconcile
against actual capacity after success. Default staging for managed elements
and runtime object overhead require separate accounting. Ordinary Go fatal
physical OOM remains outside recoverable allocation failures.</p>
<h3 id="scoped-temporary-storage">Scoped temporary storage</h3>
<p><code>std/temp</code> provides one explicit temporary byte arena for a frame, request, or
other bounded scope. <code>TempSlice(*arena, count)</code> and <code>TempText(*arena, value)</code>
append initialized scratch, <code>TempMark(*arena)</code> records the current boundary,
and <code>TempReset(*arena, mark)</code> releases everything after it. Finish with
<code>TempEnd(*arena)</code>, normally through <code>defer</code>:</p>
<pre><code class="language-zi">#import &quot;std/temp&quot;
Frame :: () -&gt; s32 {
arena := TempBegin()
defer TempEnd(*arena)
mark := TempMark(*arena)
label_ok := false
{
label := TempText(*arena, &quot;row&quot;)
label_ok = label == &quot;row&quot;
}
if !label_ok { return 1 }
cells_ok := false
{
cells := TempSlice(*arena, 64)
cells_ok = cells.count == 64
}
if !cells_ok { return 1 }
if !TempReset(*arena, mark) { return 2 }
return 0
}
</code></pre>
<p>Slices and text are borrowed views and cannot remain live across a reset under
the normal Vec borrow rules. Raw checked pointers are generation-bound too:
reset-to-mark replaces and releases the old allocation, so a pointer retained
after its view ends traps if used on the engine or native backend instead of
silently naming reused scratch. A negative size, arithmetic overflow,
allocation failure, null arena, or mark outside the current initialized range
fails without changing the arena. A zero-size request returns an empty view.
The module is ordinary checked Ziran and has the same API on C, Go, Wasm,
portable ZX engine, and native execution.</p>
<h3 id="explicit-scoped-context">Explicit scoped context</h3>
<p><code>std/context</code> defines a portable <code>Context</code> record with a capture-free logger,
scope tag, and owned <code>Temp</code> allocator. Libraries accept <code>*Context</code> explicitly;
there is no hidden parameter or process-global current context:</p>
<pre><code class="language-zi">#import &quot;std/context&quot;
#import &quot;std/temp&quot;
Log :: (tag: string, message: string) { print(&quot;%: %\n&quot;, tag, message) }
Serve :: (context: *Context, request: string) -&gt; s32 {
defer ContextLog(context, &quot;done&quot;)
ContextLog(context, &quot;start&quot;)
return request.count
}
Run :: () -&gt; s32 {
context := Context.{.logger = Log, .tag = &quot;http&quot;, .allocator = TempBegin()}
defer ContextEnd(*context)
return Serve(*context, &quot;GET /&quot;)
}
</code></pre>
<p><code>ContextLog</code> does nothing when either the context or its logger is null.
Platform-specific loggers remain in their platform modules; <code>std/context</code>
itself is ordinary checked Ziran on C, Go, Wasm, portable ZX engine, and
native execution. The allocator uses the <code>std/temp</code> API through
<code>context.allocator</code>. Because the context owns that allocator, moving the
record while one of its temporary views is live is rejected by the normal
owned-value rules. <code>ContextEnd(*context)</code> releases its temporary storage.</p>
<h3 id="building-text">Building text</h3>
<p><code>std/format.zi</code> builds text on an owned <code>Vec(u8)</code> builder. <code>Append(*builder,
value)</code> adds a string, integer, bool, or float, and
<code>BuilderPrint(*builder, "% of %\n", done, total)</code> appends a formatted piece:
each <code>%</code> takes the next argument and <code>%%</code> writes one percent. A file that uses
<code>BuilderPrint</code> imports <code>std/format</code> automatically, and <code>std/format</code> makes
<code>Vec</code> visible. <code>BuilderFinish(builder)</code> returns the text. Floats keep up to six
digits after the point, with trailing zeros dropped.</p>
<h3 id="owned-text">Owned text</h3>
<p><code>std/vec</code> defines <code>Text :: struct { bytes: Vec(u8); }</code>, UTF-8 text that owns
its bytes. A file that names <code>Text</code> or <code>Vec(T)</code> without declaring its own
imports <code>std/vec</code> automatically. A <code>Text</code> moves and drops like the <code>Vec</code> it holds: it is freed when
its local, record field or <code>Vec</code> element goes away. <code>TextCopy(value)</code> copies a
string into a new <code>Text</code>, and <code>BuilderAppend(text.bytes, more)</code> grows it.
<code>TextView(text)</code> borrows the <code>Text</code> in place as a <code>string</code>; <code>TextView(it)</code>
also accepts the pointer <code>it</code> of a <code>for *</code> loop. A <code>Text</code> place passed or
stored where a <code>string</code> is expected lends the same view. A view cannot
outlive its <code>Text</code>, so returning a view of a local <code>Text</code> or storing it in a
global is rejected. The <code>Text</code> cannot move or change while a view of it is
live. <code>TextView</code> of a fresh call result is rejected; bind the <code>Text</code> first.</p>
<p>A procedure can return <code>Text</code>, and <code>BuilderFinish(builder)</code> gives a <code>Text</code>
where one is expected, as in <code>return BuilderFinish(out)</code> from a <code>-&gt; Text</code>
procedure. A <code>Text</code> result is kept where its owner takes it: a declared,
assigned or returned <code>Text</code>, a <code>Text</code> parameter or <code>Vec(Text)</code> element, or a
discarded statement, which frees it. Anywhere else, as in
<code>line := Render(...)</code> or an argument for a <code>string</code> parameter, the result
detaches into a <code>string</code> that keeps its bytes for the rest of the program,
as <code>BuilderFinish</code> strings always have, so callers written for a <code>string</code>
result keep working. Write <code>line: Text = Render(...)</code> to free it with <code>line</code>.
A result that is only read is freed when its block closes instead: an
argument to a procedure whose body only reads that <code>string</code> parameter, a
comparison, <code>.count</code>, or <code>BuilderFinish</code> passed the same way, as in
<code>Count(Render(a))</code> or <code>Render(a) == Render(b)</code>, and a local such as
<code>line := Render(...)</code> whose uses only do the same. Reads follow <code>ifx</code> arms,
locals, a procedure that returns its argument when that result is only
read, and a record literal field, as in <code>Draw(Props.{.text = Render(a)})</code>,
whose callee only reads that field of its record parameter. Inside a
callee, a parameter may also be copied into a local <code>[N]string</code> whose
elements are only read, or into a <code>string</code> local that <code>=</code> later points at
other views of parameters or at literals, as in <code>v = s[1:3]</code>, and still
only be read. A callee or local that stores, returns, aliases or defers the
string, or a foreign callee not marked <code>#reads</code>, keeps it. The result is
never computed earlier than written, so one after another call in its
expression, after a global its procedure may change, in a <code>while</code> condition
or <code>for</code> step, or in an <code>ifx</code> arm that gives a string keeps its bytes.
Literals such as <code>-1</code>, other globals and a local's address, as in
<code>BuilderPrint(*out, "%", Render(a))</code>, may come first. A procedure that only
reads through a pointer argument, as in <code>AwardsText(*awards)</code>, is freed
too; one that writes through it stays in place. Each local is its own
binding, so a same-named local in another block does not keep it. An <code>else if</code>
condition, the second operand of <code>&amp;&amp;</code> or <code>||</code>, and an <code>ifx</code> arm that gives
a number or <code>bool</code> run on their own just before the statement, still only
when reached, so a result read there is freed too.</p>
<p>A foreign procedure that only reads its string and byte arguments during
the call says so with <code>#reads</code> before <code>#foreign</code>:</p>
<pre><code>MeasureWidth :: (value: string, font: s32) -&gt; s32 #reads #foreign host_api;
</code></pre>
<p>Text passed to it is then freed like Text passed to a Ziran procedure that
only reads it. Leave the marker off when the host may keep the pointer,
such as a binding that stores it; <code>#reads</code> on a procedure with a Ziran body
is an error, because that body already shows what it reads.
<code>TextDetach(text)</code> detaches explicitly, and <code>TextFromBuilder(bytes)</code> takes a
builder's bytes as a <code>Text</code>.</p>
<p>A procedure type makes the same promise for each procedure stored in it
with <code>#reads</code> after its result:</p>
<pre><code>SelectionPainter :: #type (x: s32, props: TextProps, label: string) -&gt; s32 #reads;
</code></pre>
<p>Each procedure stored in the type, as a slot's value, a record field, an
argument or a global's initializer, must only read its string parameters
and the string fields of its record parameters, including fields of records
they hold by value; one that keeps one is an error naming that parameter or
field path, such as <code>wrapped.data.value</code>. A record copied into a field of a
local record, as in <code>kept.command = command</code>, is followed to that local's
later uses, and <code>=</code> into the field path, or a record on it, later in the
same block replaces the string, so storing the record afterwards keeps
nothing. A pointer to the record, or a store before the replacement or
past it in a loop, keeps the string. Text passed through a value of the
type is then freed like Text passed straight to such a procedure.</p>
<p>The standard text producers return <code>Text</code>: <code>TextReplace</code>, <code>TextJoin</code>, <code>TextLower</code>, <code>TextHex</code>, <code>Float64Repr</code>, <code>JsonWrite</code>, <code>JsonString</code>, <code>JsonKey</code>, <code>JsonQuote</code>, <code>JsonNumberText</code>, <code>JoinPath</code>, <code>ResolvePath</code>, <code>WorkingDirectory</code>, <code>CreateTemporaryDirectory</code>, <code>CopyText</code>, <code>ReadStandardInput</code>, <code>DecodeReplace</code>, <code>Lower</code>, <code>CaseFold</code>, <code>Capitalize</code> and <code>Transform</code>. Existing callers keep
getting a <code>string</code>; <code>json: Text = JsonWrite(...)</code> frees the text with <code>json</code>.</p>
<p><code>std/float_text.zi</code> supplies portable binary64 decimal conversion:
<code>ParseFloat64(text: string) -&gt; (value: float64, ok: bool)</code> accepts a complete
ASCII decimal with optional sign, point and exponent, or <code>inf</code>/<code>Infinity</code> and
<code>nan</code>/<code>NaN</code>. It rejects whitespace and trailing bytes. Rounding is nearest,
ties to even; overflow succeeds as infinity and underflow as signed zero.
<code>Float64Repr(value: float64) -&gt; string</code> returns owned shortest roundtrip text
with Python's <code>repr</code> layout: fixed notation for decimal orders -4 through 15,
otherwise lowercase <code>e</code>, a signed exponent with at least two digits, and <code>.0</code>
on fixed integral values. It preserves negative zero and writes <code>inf</code>, <code>-inf</code>
and <code>nan</code>. <code>Float64ReprInto(value, output: *Vec(u8)) -&gt; bool</code> appends the
same text to caller-owned bytes, reserving before writing and reporting
allocation rejection. Both conversions use bounded exact integer arithmetic in Ziran,
without foreign calls, locale state or a Python runtime. Parsing scans all
input bytes, retaining at most 1100 significant digits plus a sticky flag;
this exceeds the length of every binary64 rounding boundary. Run
<code>build-queue -- sh tests/std_float_text.sh build/bin/ziran</code> for independent
edge/random C/Go/engine tests from source and saved IR.</p>
<h3 id="hash-maps">Hash maps</h3>
<p><code>std/hash_map.zi</code> maps string or integer keys to values on every target and
the portable runner:</p>
<pre><code class="language-jai">#import &quot;std/hash_map&quot;
ages: HashMap(string, s32)
HashMapSet(*ages, &quot;ada&quot;, 36) // insert or replace
age: s32
if HashMapGet(*ages, &quot;ada&quot;, *age) { print(&quot;%\n&quot;, age) }
HashMapRemove(*ages, &quot;ada&quot;) // returns whether the key was present
HashMapFree(*ages)
</code></pre>
<p><code>HashMapHas</code> tests a key and <code>ages.count</code> is the number of entries. The table
doubles when half its slots are in use. Values may be records; keys are
<code>string</code>, <code>s64</code>, <code>u64</code>, or <code>u32</code> (and narrower unsigned integers). The Go
target's native <code>Map(K, V)</code> from <code>std/map_go</code> is separate and keeps its
<code>MapSet</code>/<code>MapGet</code> operations.</p>
<h3 id="text-and-utf-8">Text and UTF-8</h3>
<p><code>std/text.zi</code> supplies ASCII case folding, prefix matching, and substring
matching over immutable UTF-8 strings. Non-ASCII bytes compare unchanged. These
functions use only portable Ziran operations, so the same source builds for C,
Go, and <code>.zx</code>. Add <code>--module-path std</code> when importing it from an app.</p>
<p>For full Unicode behavior, import <code>std/unicode</code>. <code>CaseFold(text: string)</code>,
<code>Lower(text: string)</code> and <code>Capitalize(text: string)</code> return strings using
Unicode 17.0 full default mappings, including expansions and contextual Greek
final sigma. Capitalization titlecases the first scalar and lowercases the
rest, as Python's <code>str.capitalize</code> does. <code>IsWord(codepoint: u32) -&gt; bool</code>
matches Python Unicode regex <code>\w</code>; <code>IsDecimal(codepoint: u32) -&gt; bool</code>
matches <code>\d</code> using only General_Category Nd. <code>IsSpace(codepoint: u32) -&gt; bool</code> and
<code>IsWhitespace(text: string) -&gt; bool</code> use Python's Unicode whitespace rules.
<code>IsPrintable(codepoint: u32) -&gt; bool</code> accepts Unicode L/M/N/P/S categories
and ASCII space, excluding other separators, controls, format characters,
private-use and unassigned values under Unicode 17.0.
<code>SplitWhitespace(text: string) -&gt; Vec(string)</code> collapses those whitespace runs
and omits empty fields, like <code>str.split()</code> without a separator. Its pieces
borrow the input. All operations run unchanged on C, Go and the portable engine,
without a host Unicode library. See <a href="unicode.html">Unicode</a> for exact semantics,
the native table generator and conformance tests.</p>
<p><code>NFCInto(text: string, output: *Vec(u8)) -&gt; bool</code> and <code>LowerInto</code> use reusable
caller-owned buffers: they replace previous bytes, reject malformed UTF-8 and
empty the output on failure. NFC performs canonical Unicode 17 decomposition,
ordering and composition, including Hangul; compatibility normalization is
excluded. <code>IsLetter</code> and <code>IsNumber</code> match exact General_Category L and N;
<code>IsWhiteSpace</code> matches Unicode White_Space, excluding <code>IsSpace</code>'s extra
U+001C..U+001F controls. See <a href="unicode.html">Unicode</a> for ownership and conformance.</p>
<p><code>std/string_range.zi</code> provides <code>Substring(source, start, length)</code> over borrowed
bytes, using Ziran's checked <code>source[low:high]</code> string range syntax. Choose
UTF-8 codepoint boundaries when the result must remain valid text.</p>
<p><code>std/utf8.zi</code> advances through UTF-8 scalar boundaries and counts codepoints.
Invalid bytes advance one byte, which keeps a scanner moving while preserving
valid multibyte sequences.
<code>Copy(source, destination)</code> writes valid UTF-8 unchanged and replaces each
malformed lead byte (following <code>Decode</code>'s consumption rule) with U+FFFD. It is
bounded and allocation-free, leaves separate source storage unchanged,
requires destination bytes not to overlap the source, and stops without
splitting a source sequence or replacement when capacity runs out. Its result
reports the written byte count and whether all input was consumed; embedded
NUL remains data.</p>
<p><code>DecodeReplace(source: []u8) -&gt; string</code> returns independently stored valid
UTF-8 with Python <code>errors='replace'</code> consumption: one replacement for each
maximal valid prefix of a malformed sequence. Thus <code>E2 82</code> becomes one U+FFFD
and <code>E1 80 41</code> becomes U+FFFD + <code>A</code>; forbidden prefixes such as <code>ED A0 80</code>
produce three replacements. It preserves valid UTF-8 and embedded NUL.
<code>Decode</code> and <code>Copy</code> keep their documented consume-one-lead-byte behavior.</p>
<h3 id="generic-values">Generic values</h3>
<p><code>std/option.zi</code> and <code>std/result.zi</code> define generic records. Import a
template and create a concrete type with <code>Number :: Option(s32)</code> or
<code>Outcome :: Result(s32, string)</code>. An <code>Option</code> has <code>has_value</code> and <code>value</code>
fields; a <code>Result</code> has <code>is_ok</code>, <code>value</code>, and <code>error</code> fields. Check the status
field explicitly before reading the associated value.</p>
<p><code>std/pair.zi</code> defines a generic record. Import it and write
<code>PairNumberText :: Pair(s32, string)</code> to create a concrete record
with <code>first: s32</code> and <code>second: string</code> fields.</p>
<p>A polymorphic procedure binds its type parameter through a direct <code>$T</code>, a
slice <code>[]$T</code>, a fixed array <code>[N]$T</code>, or a pointer <code>*$T</code> parameter: <code>Sum :: (values: []$T) -&gt; T</code>
specializes for whatever element type the caller passes. A generic record
parameter binds its arguments too: <code>Add :: (bag: *Bag($K), item: K)</code> called
with a <code>*Bag(string)</code> binds <code>K</code> to <code>string</code>.</p>
<p><code>Copy :: (values: [3]$T) -&gt; [3]T { return values; }</code> infers <code>T</code> while
requiring exactly three elements. The capacity may be a compile-time constant
or expression from the procedure's module; it is not inferred from the caller.
Zero-capacity arrays retain their declared element type. Array parameters keep
ordinary value semantics, so changing a parameter does not change the caller's
array. Nested-array element types work natively; the portable linker rejects
nested-array returns that its runtime cannot represent yet.</p>
<h3 id="sorting-and-queues">Sorting and queues</h3>
<p><code>std/sort.zi</code> sorts any slice whose elements support <code>&lt;</code> in place with
<code>Sort(values[:])</code>, and searches a sorted slice with <code>LowerBound</code> and
<code>BinarySearch</code>. Sorting allocates nothing and is not stable.
<code>SortText(texts[:])</code> orders strings by unsigned UTF-8 bytes, including embedded
NUL and prefixes, independently of the system locale. It also allocates nothing.</p>
<p><code>std/queue.zi</code> is an allocation-free bounded byte FIFO. Queue state is passed
and returned by value, and every operation receives the caller-owned backing
storage explicitly. Full pushes and empty pops are rejected without unwinding
the queue; partial byte pops report the number removed.</p>
<h3 id="toml-manifests">TOML manifests</h3>
<p><code>std/toml_document.zi</code> parses TOML 1.0 directly in Ziran on C, Go and the
portable engine. It shares its parser with the package manifest reader. Quoted
keys and strings (including escapes, literal and multiline strings), dotted
keys, tables, inline tables, arrays and arrays of tables retain their meaning.
Duplicate definitions, malformed values, invalid UTF-8 and trailing input
reject the whole document, including errors in fields a caller does not query.</p>
<pre><code class="language-zi">#import &quot;std/toml_document&quot;
document: TomlDocument
if TomlRead(*document, text) {
package := TomlMember(*document, document.root, &quot;package&quot;)
name := TomlString(*document, TomlMember(*document, package, &quot;name&quot;))
dependencies := TomlMember(*document, document.root, &quot;dependencies&quot;)
dependency := TomlFirst(*document, dependencies)
while dependency &gt;= 0 {
alias := TomlKey(*document, dependency)
dependency = TomlNext(*document, dependency)
}
}
</code></pre>
<p><code>TomlRead</code> returns <code>bool</code>; failure clears the tree, sets <code>root = -1</code>, and
reports <code>error</code> and <code>error_at</code> (a byte offset). Its default byte limit is
262144; pass a third <code>max_bytes</code> argument to change it. Nesting is limited
to 128. Keep the input alive while querying the document. Node queries accept
<code>-1</code> for missing values; use <code>TomlKindOf</code> to distinguish an empty string from
another type. <code>TomlCount</code> counts members/elements, <code>TomlBool</code> returns a value
and a success flag, and <code>TomlScalarText</code> returns the validated spelling of a
number, boolean or date/time without converting or rounding it. Run
<code>sh tests/toml_document.sh build/bin/ziran</code> for source, saved IR, C, Go and
portable execution tests.</p>
<h3 id="json-and-zip">JSON and ZIP</h3>
<p><code>std/json_scan.zi</code> supplies allocation-free JSON value skipping, object member
and array element lookup, string spans, and decimal number reading. It validates
the value shape and escapes while scanning; member names match unescaped ASCII
bytes. Callers keep the original input string and use byte offsets returned by
the scanner. Its tests compare source and saved-IR portable bundles, and the
same module is exercised through native C and Go by a downstream client.</p>
<p><code>ArrayRangesReuse</code> accepts value ranges from a successful scan and their
unchanged backing document. It reuses validation only for complete values
whose bytes match at the same array index; other values and the array's
separators are checked normally. Keep the preceding document and ranges alive
until the call returns, use a separate output slice, and consume offsets only
after a nonnegative return. Short output buffers still validate every element.
Run <code>sh tests/json_array_reuse.sh build/bin/ziran</code> for source, saved-IR and
cross-target transition checks, including malformed replies and numeric prefixes.</p>
<p><code>ReadStringValue(text, at, max_bytes)</code> decodes a quoted value into owned bytes
and reports <code>valid</code>, including for empty strings. Its limit counts decoded
bytes, so a long escaped value can fit. Consume the returned <code>value</code> vector
with <code>BuilderFinish</code>, or let normal vector cleanup release it. Ordinary UTF-8
runs append directly, and escaped code points use a five-byte temporary buffer
instead of a maximum-size string buffer. Invalid input or an exceeded limit
returns no decoded bytes.</p>
<p><code>std/json_document.zi</code> reads a whole document into a tree of numbered nodes
that a program queries (<code>JsonMember</code>, <code>JsonElement</code>, <code>JsonFirst</code>/<code>JsonNext</code>,
<code>JsonString</code>, <code>JsonInteger</code>), changes (<code>JsonSet</code> keeps a replaced member in
place, <code>JsonAppend</code>, <code>JsonRemove</code>, <code>JsonCopy</code>) and writes back. <code>JsonWrite</code>
lays the text out as Python's <code>json.dumps</code> does for the same style: indent,
separators, ensure_ascii escapes and sort_keys, so tools can rewrite files that
Python wrote without changing their bytes. Numbers keep the text they were read
with by default. <code>JsonPythonStyle(indent, ascii, sort_keys, true)</code> opts into
binary64 float canonicalization (<code>JsonStyle.python_floats</code> for a custom style):
<code>1e3</code> becomes <code>1000.0</code>, <code>-0e0</code> becomes <code>-0.0</code>, and <code>1e-7</code> becomes <code>1e-07</code>.
Only tokens containing a point or exponent are converted. Integer tokens,
including arbitrary-precision integers and <code>-0</code>, keep their original spelling;
the stored node text is never changed. Float overflow writes <code>Infinity</code> or
<code>-Infinity</code>, as Python's default JSON encoder does. Run
<code>sh tests/std_json_document.sh build/bin/ziran</code> for tree operations and default
layout, and <code>sh tests/std_float_text.sh build/bin/ziran</code> for canonical floats.</p>
<p>Documents own decoded escape buffers and generated integer text; normal
document cleanup releases them. <code>JsonReset</code> releases those buffers and clears
the tree, retaining vector capacity for reuse. Unescaped input, <code>JsonNewString</code>
and <code>JsonNewNumber</code> remain borrowed. Consume their views before changing that
storage. <code>JsonSetCopy</code> acts like <code>JsonSet</code> but owns a copy of its key; ordinary
<code>JsonSet</code> borrows its key. <code>JsonNewStringCopy</code> owns a copy of its value;
<code>JsonNewString</code> and <code>JsonNewNumber</code> continue to borrow. <code>JsonCopy</code> deep-copies
text and keys into the target, so the source may
be reset or dropped first, including when copying within one document.
Read member names with <code>JsonKey</code> or <code>JsonKeyInto</code>: a node's raw <code>key</code> field is
internal, and <code>JsonCopy</code> and <code>JsonSetCopy</code> leave it empty.
<code>JsonString</code>, <code>JsonKey</code> and <code>JsonNumberText</code> still return independent owned
strings. <code>JsonStringInto(document, node, output)</code>, <code>JsonKeyInto</code> and
<code>JsonNumberTextInto</code> instead append to caller-owned <code>Vec(u8)</code> storage and return
false on allocation failure or a missing/wrong-kind node. <code>JsonWriteInto</code> and
<code>JsonQuoteInto</code> also return false on allocation failure; discard partial output
on failure. Their output must not alias the document's input or owned buffers.
<code>JsonWrite</code> and <code>JsonQuote</code> detach owned strings.</p>
<p>For private data, pass <code>JsonRead(document, text, erase, context)</code> or register
<code>JsonSetEraser(document, erase, context)</code> before constructing a document. The
crypto-independent callback <code>(context: *void, bytes: []u8) -&gt; void</code> must overwrite
the supplied mutable bytes. It runs before owned decoded/copied/generated text,
discarded keys and internal text temporaries are freed, including failed reads.
Explicitly <code>defer { JsonReset(*document) }</code> before a private document leaves
scope; normal implicit vector destruction cannot call the registered eraser.
The caller owns erasure of borrowed input and Into output, and starts output
empty/wiped or reserves its full lifetime maximum before storing private bytes.
Use Into accessors rather than detached string returns for private data.
The parser and writer reserve before copying private bytes, so their own growth
does not relocate plaintext into allocations the eraser cannot reach.</p>
<p><code>std/zip.zi</code> reads classic ZIP directories from caller-owned bytes, verifies
stored entries with CRC-32, and writes stored archives into caller-owned output.
It rejects split, encrypted, and malformed archives, and duplicate requested
entries. ZIP64 archives are unsupported.
It runs in portable bundles. <code>std/zip_linux.zi</code> adds raw DEFLATE extraction
through the system zlib library for 64-bit Linux native C builds; link those
builds with <code>-lz</code>. The caller supplies file I/O, memory limits, and which entry names
are meaningful to the application.
<code>std/gzip_linux.zi</code> compresses and decompresses a single gzip stream into
caller-owned, disjoint byte buffers. <code>GzipDecompress</code> requires the expected
uncompressed length and rejects expansion beyond that length, bad checksums,
truncation and trailing streams. Native C builds link zlib (<code>-lz</code>); Emscripten
builds use <code>-sUSE_ZLIB=1</code>. Run <code>make gzip-test</code> for independent GNU gzip
interoperability and malformed-input tests.
<code>std/image.zi</code> holds RGBA pictures (<code>Image</code>: width, height and straight-alpha
pixels, rows top to bottom) and does what build tools did with Pillow:
<code>ResizeNearest</code>, <code>ResizeBox</code>, <code>ResizeBicubic</code> and <code>ResizeLanczos</code> give Pillow's exact pixels
(filtered resizing premultiplies alpha as Pillow does), <code>AlphaComposite</code> is
<code>Image.alpha_composite</code>, and <code>PasteImage</code>, <code>RotateLeft</code>, <code>DropAlpha</code> and
<code>QuantizeImage</code> (median cut with Floyd–Steinberg dithering) complete it.
<code>Thumbnail(image: *Image, max_width: s32, max_height: s32,
reducing_gap: float64 = 2.0) -&gt; Image</code> returns an owned bicubic thumbnail,
preserving aspect ratio with Pillow's floor/ceil choice and never enlarging.
<code>ResizeBicubic(image: *Image, width: s32, height: s32,
reducing_gap: float64 = 0.0) -&gt; Image</code> also permits enlargement. Both keep the
source unchanged and return an empty image for invalid images or nonpositive
sizes. Gap <code>0</code> means Pillow's <code>None</code>; other gaps must be finite and at least
<code>1</code> when resizing (an unchanged thumbnail returns before checking the gap).
Like Pillow's RGBA path, they resample premultiplied bytes without an
integer reduction step, regardless of gap. Unchanged sizes preserve all bytes,
including RGB under zero alpha; neither operation applies EXIF orientation.
<code>ResizeBicubicInto(image: *Image, width: s32, height: s32, output: *Image) -&gt; bool</code>
provides the same default bicubic pixels with checked allocation and dimension
arithmetic. Output owns its pixels and can be reused; it must not alias the
source or borrow its pixel storage. Failure empties output and releases partial
buffers; null output or identical source/output records fail unchanged. The
source remains unchanged. Run <code>sh tests/image_resize_fallible.sh build/bin/ziran</code>
for portable parity, native allocation faults and sanitizer lifetime tests.
Run <code>make -f Makefile -f tests/native_image_thumbnail.mk image-thumbnail-test</code>
for 40 frozen Pillow 12.3.0 bitmap oracles through native C source/saved IR,
plus Go and portable source/saved-IR assertions (no Python dependency).
<code>std/resample.zi</code> makes the same box, bicubic and Lanczos bytes for native
programs that resize repeatedly, such as a UI drawing a picture at its
on-screen size: <code>ResampleAxisInto</code> computes one axis's weights once, and
<code>ResampleRowHorizontal</code>/<code>ResampleRowVertical</code> then write rows without
allocating. <code>ResamplePlanInto</code> plans a whole premultiplied picture or a
fractional source box as Pillow's <code>Image.resize(box=...)</code> does, and its two
passes split into row ranges for worker threads. SSE2 and AVX2 on x86-64 and
NEON on AArch64 and ARMv7 run the rows with the scalar loops' exact bytes,
chosen once per CPU. A WebAssembly module built with <code>-msimd128</code> runs SIMD128
ones, so a web host loads it where <code>WebAssembly.validate</code> accepts SIMD and a
build without it elsewhere. Other targets, <code>ZIRAN_NO_ASM</code>
and <code>.zx</code> use the scalar loops. Filtering is on the stored bytes, as in
Pillow, not in linear light. Run <code>sh tests/lanczos_isa_bitexact.sh
build/bin/ziran</code> (with <code>ANDROID_NDK_HOME</code> and qemu-user for AArch64 and
ARMv7, or <code>ARMV7_ADB_SERIAL</code> for an ARMv7 device; <code>WASM_RUN</code>, a command that
runs an Emscripten <code>.js</code> such as <code>node</code>, or <code>WASI_RUN</code>, one that runs a
standalone <code>.wasm</code> such as <code>wasmtime run</code>, with <code>EMCC</code> for WebAssembly) to
compare every kernel with the scalar loops and those with std/image.
<code>std/png_linux.zi</code> reads every standard PNG into an <code>Image</code> and writes RGBA,
RGB and palette files; <code>std/jpeg.zi</code> writes baseline JPEGs at an IJG quality;
<code>std/zlib_linux.zi</code> compresses and decompresses whole zlib, gzip or raw
deflate streams into growing vectors. The PNG and zlib modules link <code>-lz</code>.
Run <code>sh tests/std_image_linux.sh build/bin/ziran</code>, which also compares with
Pillow when it is installed.
<code>std/vorbis.zi</code> reads what an Ogg Vorbis stream in memory declares without
decoding it: <code>VorbisProbe(bytes, *audio)</code> checks that the bytes are whole
pages of one stream with a Vorbis identification header and gives its
channels, rate and length, so a program can bound a stream before any
decoder allocates for it. It needs no library.
<code>std/vorbis_linux.zi</code> decodes one whole Ogg Vorbis stream held in memory
into interleaved signed 16-bit little-endian PCM over the platform
libvorbisfile: <code>VorbisDecode(bytes, *pcm, max_frames, *audio)</code> probes first,
reports the channels, rate and frame count, and refuses truncated or chained
streams, trailing bytes, damaged pages and anything longer than <code>max_frames</code>. Its
records mirror the Xiph headers, and a guard after the decoder state is
checked on every call. Only programs that import it link
<code>-l:libvorbisfile.so.3</code> (or <code>-lvorbisfile</code> with the development package).
<code>tests/vorbis_linux.sh</code> needs ffmpeg with libvorbis; with the Vorbis
development headers (or <code>VORBIS_INCLUDE</code>) it also compares the record sizes
with the C compiler's.</p>
<p>The reusable <code>audio</code> package, maintained in <code>ziranlang/packages/audio</code>, adds
Opus and quality sinc conversion without a GUI or audio-device dependency.
<code>audio/opus</code> exposes bounded Ogg decoding and single-owner encoder/decoder
states with caller-owned scratch. <code>audio/pipeline</code> adds whole-buffer encoding
with automatic sinc resampling. The Ogg decoder applies
pre-skip, header gain and final trim; <code>DecoderRewind</code> resets a validated
immutable input without rescanning it. <code>audio/resample</code> wraps libsamplerate's
best-quality sinc, including 44.1–48 kHz conversion and incremental processing.
<code>audio/ogg</code> inspection and <code>audio/wav</code> PCM16/float32 input with PCM16 output
also run in portable bundles. Native codec/sinc calls require the C target;
portable bundles reject those FFI calls explicitly. Native consumers declare
<code>links = ["opus", "samplerate", "m"]</code> in their root package manifest.
The package's <code>audio</code> CLI provides <code>encode</code>, <code>decode</code>, <code>inspect</code>, <code>transcode</code>
and <code>resample</code>, with bitrate, VBR, constrained VBR and named bandwidth caps.
Its README documents ownership, frame/byte limits, supported formats and
tested targets. Existing Vorbis modules remain independent.</p>
<p><code>std/zip_file_linux.zi</code> writes stored ZIP entries directly to a caller-owned
file from borrowed byte slices, including mapped files. The caller controls
file creation and publication. Its Ziran test checks the output with Info-ZIP's
reader as well as Ziran's reader.</p>
<p><code>std/zstd_go.zi</code> provides single-owner reusable Zstandard encoders and bounded
stream decoding for the Go target. The consuming Go module supplies
<code>github.com/klauspost/compress</code> (tested with v1.20.3, requiring Go 1.25 or newer).
<code>NewEncoder(writer, level, window_bytes, literal_entropy)</code> uses one worker;
numeric levels choose the provider's nearest preset. Literal entropy defaults
to true so base64-like data can compress even without repeated strings.
Close an encoder before <code>Reset</code> attaches its next writer. The module does not
pool contexts or retain response buffers itself. <code>DecodeLimited</code> caps returned
bytes and the frame's window, rejects malformed/trailing data, and returns no
partial bytes on failure. It accepts valid concatenated frames within the same
total limit. Native C targets continue to use their transport's negotiated
decoder; this Go module does not provide a portable bundle capability. Run
<code>sh tests/zstd_go.sh build/bin/ziran</code> for source/saved-IR, race, independent
libzstd interoperability and malformed/bounded-input verification.</p>
<h3 id="binary-fields">Binary fields</h3>
<p><code>std/binary.zi</code> reads little-endian numbers from byte text such as file or
asset contents: <code>ReadU16LE</code>, <code>ReadU32LE</code>, <code>ReadS32LE</code> and <code>ReadF32LE</code> take
the text and a byte offset, and a field that does not fit reads as zero.
<code>Float32FromBits</code> and <code>Float64FromBits</code> turn IEEE 754 bit patterns into
values with exact arithmetic, including subnormals, signed zeros, infinities
and NaN, so native targets and portable bundles agree without reinterpreting
memory. Run <code>sh tests/std_binary.sh build/bin/ziran</code>, which also compares the
decoding with the C compiler's over a million random patterns.
<code>std/binary_linux.zi</code> keeps 64-bit fields for native Linux programs.</p>
<h3 id="constant-tables">Constant tables</h3>
<p>A constant array of numbers or booleans is a read-only table:
<code>COS :: s32.[4096, 4095, 4091]</code> or <code>#run s32.[...]</code>, of any length and over
as many lines as it needs. Reading <code>COS[i]</code> reads one table the module shares
(a file-scope <code>static const</code> in C, a package <code>var</code> in Go, built once in the
portable engine) instead of copying the array; copying it into a variable, as in
<code>local: [3]s32 = COS</code>, still makes an independent copy, which Go takes
straight from the shared <code>var</code>, as it does when passing the table by
value. Indexes are
bounds-checked as for any array. A function may read a table, and its
<code>.count</code>, in as many loops as it needs.</p>
<p>A table of rows is a constant table too. Each row names its type, as in
<code>GRID :: [3]s32.[s32.[1, 2, 3], s32.[4, 5, 6]]</code>, and <code>#run</code> can build one
in a procedure that sets <code>g[a][b][c]</code> and returns it. <code>GRID[i][j]</code> reads the
shared table in place without copying the row, and <code>grid: [2][3]s32 = GRID</code>
starts a variable from it.</p>
<p>A file-scope variable may start from a table of any length, named as in
<code>table: [4096]u8 = Lib.BIG</code> or written out. Each target defines the variable
with its values, so nothing fills it when the program starts, and writing it
leaves the table unchanged.</p>
<h3 id="bit-counts-and-byte-swaps">Bit counts and byte swaps</h3>
<p><code>clz(x)</code>, <code>ctz(x)</code> and <code>popcount(x)</code> count leading zero bits, trailing zero
bits and set bits; <code>bswap(x)</code> reverses the bytes. Each takes one <code>u8</code>, <code>u16</code>,
<code>u32</code> or <code>u64</code> and returns that type, and the counts give the width for zero
(<code>clz(cast(u32) 0) == 32</code>). Native C uses the compiler's <code>__builtin_*</code> with a
portable fallback, Go uses <code>math/bits</code>, and the portable engine computes the same
results. A procedure of your own with one of these names is called instead.
Run <code>sh tests/bit_builtins.sh build/bin/ziran</code>.</p>
<h3 id="simd-vectors">SIMD vectors</h3>
<p><code>Simd :: #import "simd"</code> gives fixed-width vectors (<code>u8x16</code>, <code>s8x16</code>,
<code>u16x8</code>, <code>s16x8</code>, <code>u32x4</code>, <code>s32x4</code>, <code>u64x2</code>, <code>s64x2</code>, <code>f32x4</code> and <code>f64x2</code>,
and 256-bit forms such as <code>s16x16</code>) with operations such as <code>Simd.Add</code>,
<code>Simd.Load(s16x8, row, at)</code> and <code>Simd.ByteShuffle</code>; <code>std/simd.zi</code> lists
them all. <code>#import "std/simd"</code> works the same, under any alias. Vectors are
values, used through these operations rather than <code>+</code> or <code>==</code>. Every
operation gives the same bits on every target. Native C uses SSE2 on x86-64,
or SSSE3, SSE4.1 and AVX2 when the build enables them, NEON on AArch64 and
ARMv7, and WebAssembly SIMD128 when a wasm32 build passes <code>-msimd128</code>. Go,
and bundles compute lane by lane.</p>
<p><code>Simd.Load(u8x16, text, at)</code> and <code>Simd.LoadLow(u8x16, text, at)</code> also
read immutable strings directly, including embedded NUL bytes. They check the
entire access against the string length without allocating a byte slice. Other
lane types and stores require their existing slice, array or pointer inputs.</p>
<p>Mark a procedure <code>#target</code> to let native x86-64 C pick its SIMD instructions
when the program runs:</p>
<pre><code class="language-jai">Blend :: (row: []u8, out: []u8) #target {
...
}
</code></pre>
<p>Generated C holds SSSE3, SSE4.1 and AVX2 copies of <code>Blend</code> and calls the
best one the CPU runs, chosen once, so one SSE2 build uses AVX2 where it can.
<code>ZIRAN_SIMD_TIER=1</code> (SSE2) to <code>4</code> (AVX2) in the environment lowers the
choice for testing, and <code>#asm</code> variants needing a vector feature beyond that
tier, such as <code>x86_64+avx2</code> under <code>ZIRAN_SIMD_TIER=3</code>, are passed over. Builds that already enable AVX2, and other targets,
compile the procedure once. Each copy calls its own tier's copy of every
<code>#inline</code> procedure of the module, so helpers run with the caller's
instructions. A <code>#target</code> procedure cannot take or return a
256-bit vector by value, or pass one to another procedure, because AVX2 code
passes those in different registers; use an array or a pointer. It cannot be
<code>#inline</code> or hold <code>#asm</code> variants. Run <code>sh tests/simd.sh build/bin/ziran</code>
and <code>sh tests/simd_target.sh build/bin/ziran</code>. With <code>WASMTIME</code> set to a
wasmtime command, <code>tests/simd.sh</code> also runs its wasm32 modules; with
<code>ANDROID_NDK_HOME</code> it builds AArch64 and ARMv7, and runs them under
<code>QEMU_AARCH64</code> and <code>QEMU_ARM</code> or on the ARMv7 device <code>ARMV7_ADB_SERIAL</code>
names.</p>
<p>Native vectors (<code>u8xN</code>, <code>s8xN</code>, <code>u16xN</code>, <code>s16xN</code>, <code>u32xN</code>, <code>s32xN</code>,
<code>u64xN</code>, <code>s64xN</code>, <code>f32xN</code> and <code>f64xN</code>) are as wide as the code running
them handles well: two 128-bit blocks in a <code>#target</code> procedure's AVX2 copy
and in builds that enable AVX2, one elsewhere, Go and bundles included.
<code>Simd.Lanes(T)</code> and <code>Simd.Blocks(T)</code> give the count, which is a constant
for fixed vectors, so a loop steps by it:</p>
<pre><code class="language-jai">Brighten :: (row: []u8) #target {
i := 0
while i + Simd.Lanes(u8xN) &lt;= row.count {
Simd.Store(row, i, Simd.AddSat(Simd.Load(u8xN, row, i), Simd.Splat(u8xN, 8)))
i += Simd.Lanes(u8xN)
}
}
</code></pre>
<p>They take the operations fixed vectors take. <code>Make</code>, <code>Splat</code> and <code>Shuffle</code>
name one block's lanes, which repeat; <code>Shuffle</code>, <code>ByteShuffle</code>,
<code>AlignBytes</code>, <code>ShiftBytesLeft</code>, <code>ShiftBytesRight</code>, <code>InterleaveLow</code> and
<code>InterleaveHigh</code> work on each block; <code>WidenLow</code>, <code>WidenHigh</code>, <code>MulWideLow</code>,
<code>MulWideHigh</code> and <code>Narrow</code> count lanes across the whole vector; <code>LoadLow</code>
and <code>StoreLow</code> move half of it. <code>Lane</code>, <code>WithLane</code>, <code>Widen</code>, <code>Low</code>, <code>High</code>
and <code>Combine</code> take no native vectors, and native and fixed vectors do not
mix. A native vector is a plain local, parameter or result: no global,
record field, array, pointer, slice, <code>size_of</code> or <code>#foreign</code> signature holds
one, and a <code>#target</code> procedure does not take, return or pass one. Run
<code>sh tests/simd_native.sh build/bin/ziran</code>.</p>
<h3 id="http-and-process-capabilities">HTTP and process capabilities</h3>
<p><code>std/net_http.zi</code> defines an explicit request/response host capability. A
platform adapter supplies transport and TLS; checked Ziran code owns request
construction and response interpretation. A missing host binding is reported
before a portable bundle runs.</p>
<p><code>std/constant_time.zi</code> compares equal-length byte spans without branching on
byte values. Use fixed-size buffers for secret tags so unequal lengths remain
public shape rather than a secret-dependent oracle.</p>
<p><code>std/process.zi</code> defines a line-oriented child-process capability with explicit
arguments, stdin, an optional credential binding, a timeout, and a desktop
isolation request. The host starts the child, yields output lines, and returns
its exit result. Its contract runs from source and saved <code>.zir</code> as a portable
bundle and through native C and Go mocks.</p>
<h3 id="files">Files</h3>
<p><code>#import "std/file"</code> gives one set of file operations on every native C
target: it uses <code>std/file_linux.zi</code> on Linux, Android, the web, and Windows.
The shared operations are <code>OpenRead</code>, <code>OpenWrite</code>,
<code>OpenUpdate</code>, <code>OpenReplace</code>, <code>OpenNew</code>, <code>Read</code>, <code>Write</code>, <code>ReadAt</code>, <code>WriteAt</code>,
<code>FileSize</code>, <code>CloseFile</code>, <code>RemoveFile</code>, <code>RenameNoReplace</code>, <code>PathExists</code>,
<code>DirectoryExists</code>, <code>CreateDirectory</code>, <code>CreatePrivateDirectory</code>, and the
directory cursor. <code>OpenNew(path)</code> exclusively creates a writable file
(0644 restricted by umask); an occupied file or symbolic link fails unchanged.
Check the returned handle's <code>valid</code> field and close successful handles with
<code>CloseFile</code>. Two helpers read and replace whole files:</p>
<pre><code class="language-jai">#import &quot;std/file&quot;
if WriteEntireFile(&quot;notes.txt&quot;, &quot;hello\n&quot;) {
text, ok := ReadEntireFile(&quot;notes.txt&quot;)
}
</code></pre>
<p>The Go target and portable bundles do not have these operations; Go
programs use <code>std/file_go</code>.</p>
<h3 id="browser-byte-snapshots">Browser byte snapshots</h3>
<p><code>std/web</code> provides <code>WebBytes(kind, data, count)</code> for a copied JavaScript typed
array and <code>WebBlobBytes(data, count)</code> for a browser <code>Blob</code> snapshot. The latter
passes a Wasm memory view directly to the Blob constructor within one host
call, avoiding a separate copy of encoded file, media or request-body bytes.
The source may be changed or freed, and Wasm memory may grow, after it returns.
An invalid byte range returns handle <code>0</code>; an empty valid range returns an empty
Blob. Shared heaps require an explicit unshared snapshot because Blob excludes
shared BufferSources. Handles follow the usual <code>WebScope</code>/<code>WebKeep</code> lifetime.
<code>WebBytes</code> continues to return an independent typed-array copy.</p>
<h3 id="native-linux-adapters">Native Linux adapters</h3>
<p>Native Linux C builds can import <code>std/file_linux.zi</code> for positional byte I/O,
<code>std/binary_linux.zi</code> for little-endian numbers, <code>std/date_time_linux.zi</code> for
Unix time, <code>std/random_linux.zi</code> for operating-system secure randomness, and
<code>std/byte_text_linux.zi</code> for borrowed byte-to-text views, and
<code>std/environment_linux.zi</code> for environment values (<code>EnvironmentText</code>,
<code>EnvironmentNumber</code>). <code>std/socket_linux.zi</code>
opens literal-IPv4 TCP sockets with bounded polling, cancellation, and I/O.
<code>std/timer_linux.zi</code> supplies monotonic millisecond timestamps and bounded,
interruptible sleeps; it does not expose wall-clock time.
<code>std/thread_linux.zi</code> runs a procedure on a background thread that the
starting thread can poll for completion without waiting, which suits a frame
loop with a request in flight; it builds on pthreads, including Android's
and Windows winpthreads.
<code>ThreadStart</code> also accepts an optional <code>ThreadNotification</code> containing a
<code>procedure</code> and its <code>argument</code>.
The worker calls that notification once after publishing completion, allowing
an event loop or pipe waiter to wake immediately. The notification must not
join or restart its own thread. Keep the thread and argument storage alive
until <code>ThreadFinished</code> or <code>ThreadWait</code> joins it before consuming results.
macOS has no <code>pthread_tryjoin_np</code>, so there <code>ThreadFinished</code> reports the end
once the notification has returned and then joins, which can wait for the
thread's thread-local destructors.
<code>std/thread_windows.zi</code> provides the same worker interface for native Win64
without winpthreads. It starts through the C runtime, polls the native thread
handle with a zero timeout, and closes that handle only after the thread and
its cleanup finish. Keep its record and arguments at stable addresses until
completion, including while a canceled request is being collected.
<code>tests/thread_windows.sh</code> compiles and links C source and saved IR with
MinGW against the thread completion host.
<code>std/parallel_linux.zi</code> supplies a reusable <code>ParallelPool</code> for independent
half-open ranges. <code>ParallelRun</code> divides a range among persistent workers and
the submitting thread, then waits for every lane before returning. Short ranges
use a subset of the pool instead of becoming serial when more lanes are
configured. Keep the pool at one address, submit from one owner, and call <code>ParallelClose</code> before
releasing it. Callbacks must write only their own range and keep shared inputs
immutable. Four lanes run by default; <code>ZIRAN_PAR_THREADS</code> selects 1–64 lanes.
Native C source builds define the genuine <code>POSIX_THREADS</code> capability
automatically when pthread-compatible threads are available, including
Windows. On <code>_WIN32</code>, the pool uses <code>std/thread_windows.zi</code>, native SRW locks
and condition variables from kernel32; it needs no winpthreads or <code>-pthread</code>.
<code>tests/native_workers_windows.sh</code> compiles and links source and saved IR
with MinGW against the native worker pool. MinGW tests accept <code>MCFGTHREADS</code> as the installation
prefix of an mcfgthread runtime when its <code>lib</code> directory is outside the compiler's
search path. Web selection uses <code>OS == .WEB</code>; <code>PLATFORM_WEB</code> is not a target
selector. Untargeted IR stays portable. Explicit C IR freezes the same
capability selection as source builds. Libraries
can use that capability to parallelize their native adapters by default while
keeping portable output independent of pthreads. This does not parallelize
arbitrary program state or make shared mutable data safe.
The file module can create a private file exclusively, sync its contents, and
publish it through a hard link that fails if the destination already exists.
<code>std/byte_text_linux.zi</code> also borrows caller-owned C strings and byte buffers;
the caller must keep their memory alive. <code>std/mapped_file_linux.zi</code> maps a file
privately for bounded byte parsing without copying it. Its borrowed slice is
valid only until <code>UnmapFile</code>, and writes to that slice do not change the file.
<code>std/process_capture_linux.zi</code> captures a child process without a shell;
<code>std/net_http_linux.zi</code> uses it to send JSON over HTTPS through <code>curl</code>.
<code>std/process_channel_linux.zi</code> keeps an owned child open for bidirectional byte
I/O. <code>StartChannel</code> takes 1 through 32 explicit arguments (each at most 4095
non-NUL bytes) and optionally merges stderr into the channel. Invalid argument
counts fail before creating a socket or child. <code>ChannelSend</code> and <code>ChannelReceive</code> use caller-owned
buffers and bounded waits. A third <code>discard_stderr</code> argument defaults to false;
when true the child sends stderr to <code>/dev/null</code> without mixing it into stdout.
Merging and discarding together are rejected before launch. <code>WaitChannel</code> joins
the child and records its exit
code. <code>CloseChannel</code> closes the stream, waits for the requested grace period,
then terminates only the child's own process group if it is still running.
<code>CancelChannel</code> instead signals the still-owned unreaped child group before
joining, so cancellation also stops descendants retaining stdout after their
parent exits. It closes the endpoint and reaps the direct child; repeating it
after joining is harmless. Do not reap the parent separately while awaiting
stdout, because its unreaped PID proves this process-group ownership.
Keep one owner for each channel and close it before releasing its storage;
failed sends may have delivered a prefix and must not be blindly replayed.</p>
<p>Build and release programs use three more modules. <code>std/process_run_linux.zi</code>
runs a child with any number of arguments, a working directory, environment
changes, and each stream inherited, read from or written to a file, or
captured (<code>RunProcess</code>); <code>StartProcess</code>, <code>PollProcess</code>, <code>WaitProcess</code> and
<code>SignalProcess</code> follow a child left running, and a program that cannot start
reports <code>started = false</code>. <code>std/file_tree_linux.zi</code> creates, lists, copies and
removes folders, reads a path's kind, owner UID (<code>PathInfo.owner_uid</code>), permissions,
size and modification time,
replaces a file atomically, takes <code>flock</code> locks and matches shell wildcards.
<code>PathInfo.modified</code> gives signed seconds since the Unix epoch;
<code>modified_nanoseconds</code> gives its fractional nanoseconds from 0 through 999999999,
not total nanoseconds. Missing paths return zero for both fields. Programs that
combine them into a signed 64-bit timestamp must check multiplication/addition
overflow for their supported date range.
<code>PathStatus(path, false)</code> reports a symbolic link's own metadata. <code>PathStatus</code>
returns zero <code>PathInfo</code> on any failure. Use
<code>PathQuery(path: string, follow_links: bool = true) -&gt; PathQueryResult</code> when
absence must be distinguished from inaccessible paths. The result contains
<code>info: PathInfo</code>, <code>valid: bool</code>, <code>missing: bool</code> and <code>error: s32</code>.
Success sets <code>valid = true</code>, <code>missing = false</code> and <code>error = 0</code>. Failure leaves
zero <code>info</code> and sets <code>valid = false</code>; <code>error</code> is the positive Linux errno and
<code>missing</code> is true only for ENOENT (2) or ENOTDIR (20). EACCES (13), ELOOP (40)
and other errors are not absence. Embedded NUL or paths exceeding 4095 bytes
return EINVAL (22), with <code>missing = false</code>. Empty paths reach the OS and return
ENOENT. Following a dangling symlink reports absence; <code>follow_links = false</code>
queries the link itself. These queries are snapshots; later operations can fail.
<code>ListDirectory(path, names)</code> appends independently owned names to the caller's
<code>Vec(string)</code>. Call <code>FreeDirectoryNames(names)</code> to free every name and the vector
storage and reset it to empty. Empty, repeated and null releases are harmless;
borrowed views expire on release. Do not mix borrowed strings or duplicate
ownership into that vector.
<code>CopySymbolicLink(source, target)</code> copies the link itself, including dangling
and directory links. <code>CopyFileNew(source, target)</code> and <code>CopyTreeNew(source, target)</code>
copy a file or tree exclusively, preserving links and refusing occupied
destinations. Tree destinations require an existing parent; self and descendant
copies are rejected, including through parent aliases. Keep ancestors and source
entries stable during copying. On failure these functions return false and may
leave a partial new destination; they do not delete it. Copy files start with
0600 permissions and directories with 0700 (restricted by umask); source
permission bits are applied after each successful copy. <code>CopyFile</code> still replaces
files and <code>CopyTree</code> still merges into existing directories.
<code>ResolvePath(path)</code> returns the canonical absolute path with symbolic links and
dot components resolved, or empty for a missing or invalid path.
<code>CreateTemporaryDirectory(parent, prefix = "ziran-")</code> atomically creates a unique
child under an existing directory owned by the effective user. It returns the
absolute path or empty on failure. The prefix must be one name component;
six random characters follow it. Permissions are 0700 restricted by umask.
Keep the parent and its ancestors stable during creation, and call <code>RemoveTree</code>
when finished. Run <code>sh tests/std_file_tree_linux.sh build/bin/ziran</code> for C source
and saved-IR query success/errno (including inaccessible parents), ownership,
canonicalization and private-directory tests. The EACCES assertion requires a
non-root user; root runs explicitly report that assertion as skipped.
<code>std/text_tools.zi</code> finds, splits, trims, replaces and joins text, and decodes
bounded hexadecimal into a caller-owned byte vector on any target.
<code>std/stdio_linux.zi</code> writes to standard output or standard error and reads all
of standard input.
Run <code>sh tests/std_tools_linux.sh build/bin/ziran</code> for their checks.</p>
<p>These native adapters keep libc calls out of applications and require glibc
Linux and a <code>curl</code> executable. Portable bundles should use the host capabilities
above instead.</p>
<p>Windows C builds (<code>--define _WIN32</code>) keep the same file and mapping API over
Win32. Paths pass as UTF-8 and are converted to UTF-16. Positional reads and
writes leave the file position unchanged, as on POSIX, and a private mapping
is a copy-on-write view. An open file can itself be renamed or removed, but
unlike POSIX, a rename cannot replace a destination that is still open. The
libcurl HTTP and WebSocket adapters also build there; <code>std/zip_linux.zi</code> needs
a MinGW zlib. <code>tests/std_file_windows.sh</code> compiles and links the file modules with MinGW
when it is installed.</p>
<h3 id="native-go-maps">Native Go maps</h3>
<p>Import <code>map_go</code> to use <code>Map(K, V)</code> with the Go target. Keys must be comparable;
values cannot own <code>Vec</code> storage. A map's zero value is nil. Copies share entries,
while replacing a map binding changes only that binding. Maps can be compared
with <code>null</code>, and their contents are accessed through these operations:</p>
<div class="table-scroll"><table>
<thead>
<tr>
<th>Operation</th>
<th>Behavior</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>MapInit(values)</code></td>
<td>Allocate an empty map if the binding is nil</td>
</tr>
<tr>
<td><code>MapSet(values, key, value)</code></td>
<td>Insert or replace; allocate nil storage first</td>
</tr>
<tr>
<td><code>MapGet(values, key)</code></td>
<td>Read an entry, or return the value type's zero value</td>
</tr>
<tr>
<td><code>MapLookup(values, key)</code></td>
<td>Return <code>Option(V)</code>; import <code>option</code> to use this operation</td>
</tr>
<tr>
<td><code>MapContains(values, key)</code></td>
<td>Test key presence, including entries with zero values</td>
</tr>
<tr>
<td><code>MapDelete(values, key)</code></td>
<td>Remove an entry; missing keys are harmless</td>
</tr>
<tr>
<td><code>MapClear(values)</code></td>
<td>Remove every entry while preserving allocated storage</td>
</tr>
<tr>
<td><code>MapCount(values)</code></td>
<td>Return the entry count as <code>s64</code></td>
</tr>
<tr>
<td><code>MapKeys(values)</code></td>
<td>Return an unordered <code>[]K</code> snapshot</td>
</tr>
</tbody>
</table></div>
<p><code>MapInit</code> and <code>MapSet</code> require a mutable binding or field. Nil maps support
reads, membership checks, deletion and clearing. Map mutation in <code>#parallel</code>
regions is rejected because copies share storage. Other targets and portable
ABIs reject maps; <code>.zir</code> preserves their Go behavior.</p>
<p>Import <code>go_types</code> for the predeclared Go <code>Any</code> and <code>Error</code> interfaces. <code>Any</code>
accepts values that do not own <code>Vec</code> storage, including nested maps for JSON.</p>
<h3 id="native-civil-clocks-and-calendars">Native civil clocks and calendars</h3>
<p>Import <code>date_time_linux</code> for <code>UnixNow()</code>, <code>LocalNow()</code>,
<code>LocalAt(seconds)</code>, and <code>UtcAt(seconds)</code>. <code>LocalAt</code> uses the operating system's
timezone and daylight-saving rules. The shared <code>LocalDateTime</code> record lives
in <code>date_time_types</code>; the hosted <code>date_time</code> module re-exports that same type.
Months and days are one-based, <code>day_of_year</code> is zero-based, and <code>valid</code> reports
whether the provider could obtain a reading. Dates after 2038 retain their full value.</p>
<p>With <code>--define _WIN32</code>, <code>date_time_linux</code> and <code>timer_linux</code> use native Windows
APIs instead of POSIX calls. Windows civil clocks use
FILETIME and the system's timezone rules, with valid dates from 1601 through
9999. Its named-zone query recognizes UTC/GMT; other IANA names return an
invalid offset because these Windows APIs do not expose an IANA database.
Monotonic timestamps use QueryPerformanceCounter.</p>
<p>Import <code>calendar</code> for Gregorian <code>LeapYear</code>, <code>DaysInMonth</code>, <code>DayOfWeek</code>,
<code>DayOfYear</code>, <code>DateTimeValid</code>, and <code>FormatDateTime</code>. <code>DayOfWeek</code> returns zero for
Sunday and minus one for an invalid date. Calendar dates range from year 1 to
9999. <code>FormatDateTime(reading, pattern, output)</code> writes into a caller-owned
byte slice, leaves a NUL terminator, and returns a view of the complete result.
Invalid readings, unsupported tokens, and insufficient space return an empty
view and clear the first output byte. Names are English and independent of
locale. Supported civil tokens are <code>%a</code>, <code>%A</code>, <code>%b</code>, <code>%B</code>, <code>%h</code>, <code>%C</code>, <code>%d</code>,
<code>%e</code>, <code>%F</code>, <code>%D</code>, <code>%H</code>, <code>%I</code>, <code>%j</code>, <code>%k</code>, <code>%m</code>, <code>%M</code>, <code>%p</code>, <code>%P</code>, <code>%r</code>, <code>%R</code>,
<code>%S</code>, <code>%T</code>, <code>%u</code>, <code>%w</code>, <code>%X</code>, <code>%y</code>, <code>%Y</code>, <code>%n</code>, <code>%t</code>, and <code>%%</code>. The calendar
calculations and formatting also run from portable bundles without a clock
host.</p>
<p>Local conditional construction can share an explicitly named ordinary record
type between its arms:</p>
<pre><code class="language-zi">Pair :: struct { value: s32; }
Choose :: (yes: bool) -&gt; Pair {
result := ifx yes then Pair.{value=41} else .{value=42};
return result;
}
</code></pre>
<p>The reverse arm order works too, including nested fields with their checked
record context. At least one arm must explicitly name that record. This does
not search types by their fields, infer public signatures or imports, or infer
owned, foreign, union, enum or procedure types from an unnamed sibling.
Ambiguous constructors and mismatched fields remain errors. The checked source
and saved IR retain the resolved record type; both arms keep their ordinary
lazy runtime evaluation.</p>
<p>For checked, hash-bound source changes see <a href="semantic-edit.html">source edits</a>.
For the opt-in scalar direct-native compiler, lowered-IR dumps and final-byte
source maps, see <a href="https://github.com/ziranlang/ziran/blob/master/ASSEMBLY/README.md">the ASSEMBLY prototype</a>. It is not yet a
replacement for the portable and generated-C runtime paths.
An optional byte-exact transport with source maps is described in
<a href="transport-view.html">compact transport</a>; <code>.zi</code> remains canonical source.</p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>