# Nox documentation Source: https://noxlang.com/docs/ · Repository: https://github.com/mburakmmm/nox-lang --- # Nox documentation **Nox** is a statically typed, ahead-of-time compiled programming language with Python's syntax. It compiles to native code through LLVM, has a small runtime written in Zig, manages memory automatically without a garbage collector and without ownership annotations, and runs tasks in parallel on all your cores. > *Native without the ownership noise.* ```nox class Account: owner: str balance: int def __init__(self, owner: str, balance: int) -> None: self.owner = owner self.balance = balance def deposit(self, amount: int) -> None: self.balance += amount acct: Account = Account("Ada", 100) acct.deposit(50) print(f"{acct.owner} has {acct.balance}") ``` ```output Ada has 150 ``` ## Start here | If you want to… | Read | |---|---| | install Nox | [Installing Nox](https://noxlang.com/docs/install/) | | learn the language | the [Tutorial](https://noxlang.com/docs/tutorial/) | | look something up | the [Language reference](https://noxlang.com/docs/language/) and the [Standard library](https://noxlang.com/docs/stdlib/) | | see what is new | [What's new in Nox 2.1](https://noxlang.com/docs/whatsnew/2.1/), [Nox 2.0](https://noxlang.com/docs/whatsnew/2.0/) and [Migrating from 1.x](https://noxlang.com/docs/whatsnew/migrating/) | | build libraries, frameworks or native extensions | [The three APIs](https://noxlang.com/docs/apis/) | | use the tools | [noxc](https://noxlang.com/docs/tools/noxc/), [Packages](https://noxlang.com/docs/tools/packages/), [Testing](https://noxlang.com/docs/tools/testing/) | | understand how it works or contribute | [Internals](https://noxlang.com/docs/internals/architecture/) | ## What makes Nox different - **Python syntax, mandatory types.** Every variable, parameter and return value has a static type, checked before the program runs — with none of the ceremony of a borrow checker. - **Invisible memory management.** The compiler places values on the stack or frees them at their last use when it can prove it is safe, and falls back silently to reference counting when it cannot; a cycle collector handles the rest. There are no ownership keywords, no lifetimes and no GC pauses. - **Fast by default.** Programs compile to native code through LLVM (QBE is an alternative back end); numeric loops run at C speed. - **Concurrency without colour wars.** Lightweight tasks, typed channels, and a work-stealing scheduler that uses every core — the same source runs correctly on one thread or many. - **Batteries included.** An HTTP server and client with TLS and WebSockets, JSON/TOML/YAML/CSV, SQLite/PostgreSQL/MySQL, regular expressions, cryptography, a router, templates, testing and more. - **A real native boundary.** `extern def` for C, the Nox Native Interface for stable plugins in C/C++/Rust/Zig, a Plugin API with manifests and capability consent, the preview `nox-hpy-host-v1` package profile, and WebAssembly modules. - **From web service to kernel.** The same language compiles a freestanding kernel with a kernel-provided allocator. ## Quick links - [Language tour in one page](https://noxlang.com/docs/language/python-differences/) — if you already know Python - [`nox.http`](https://noxlang.com/docs/stdlib/http/) · [`nox.json`](https://noxlang.com/docs/stdlib/json/) · [`nox.sqlite`](https://noxlang.com/docs/stdlib/sqlite/) · [`nox.thread`](https://noxlang.com/docs/stdlib/thread/) - [How-to guides](https://noxlang.com/docs/howto/): [binary size](https://noxlang.com/docs/howto/binary-size/) · [cross-compiling](https://noxlang.com/docs/howto/cross-compile/) · [embedded C libraries](https://noxlang.com/docs/howto/embedded-c-libraries/) - [Security model](https://noxlang.com/docs/reference/security/) · [Platforms](https://noxlang.com/docs/reference/platforms/) · [FAQ](https://noxlang.com/docs/reference/faq/) - The package registry: [noxpkg](https://noxlang.com/docs/tools/noxpkg/) · The web framework: [Nyx](https://github.com/mburakmmm/nyx) ## For tools and AI assistants The whole documentation is available as plain Markdown: an index at and every page in one file at . Links inside the file are absolute, so it can be fed to a tool as is. ## About this documentation Every code example in these pages is compiled, and every example followed by an `output` block is also run and compared, as part of the project's test process. If something here disagrees with the compiler, that is a bug — please report it at . --- # What's new in 2.2 > **Nox 2.2** collects everything that shipped in the 2.1.x releases on the way to it. Everything here is source compatible with 2.0 and 2.1: no valid program stops compiling, and [NNI v1, the Plugin API and NAPI](https://noxlang.com/docs/apis/stability/) are unchanged. ## Language - **Variadic functions** (`*xs: int`, `**kwargs`, keyword-only parameters and argument unpacking) work as documented in [Functions](https://noxlang.com/docs/language/functions/). `min` and `max` now take three or more arguments. - **A `def` without `-> T` returns `None`.** `def greet(name: str):` is the same as `def greet(name: str) -> None:`. Returning a value from such a function is a type error, and `noxc fmt` keeps whichever form you wrote. - **More builtins:** the three-argument `pow(a, b, m)`, `hex`, `oct` and `bin`, `int(text, base)`, `sum(items, start)`, `enumerate(items, start)`, `min`/`max` with `default=`, and `zip` over three lists ([Builtins](https://noxlang.com/docs/language/builtins/)). ```nox def total(*xs: int) -> int: t: int = 0 for x in xs: t += x return t def greet(name: str): print(f"hello {name}") greet("Ada") print(total(1, 2, 3)) print(max(4, 9, 2)) print(pow(2, 10, 1000)) print(hex(255), oct(8), bin(5)) print(int("ff", 16)) ``` ```output hello Ada 6 9 24 0xff 0o10 0b101 255 ``` ## Performance Every number below was measured against a C reference compiled with `clang -O2` (and CPython where it applies) and is reproducible with `benchmarks/gate.py`; the regression gate runs 39 standard-library and language jobs against a checked-in baseline. | What | Before | Now | |---|---|---| | `f"{a}:{b}"` and `"item" + str(i) + "tail"` chains (300k) | 13.3 ms | 4.4 ms | | `nox.json.parse` (50k objects) | 17.7 ms | 6.3 ms | | `LRUCache` (300k operations) | 790 ms | 11 ms | | `Set.remove` (20 000 elements, remove all) | 3.6 s | 3.9 ms | | `nox.bigint` (`3000!` and decimal output) | 22.8 ms | 2.9 ms | | `nox.time.DateTime` (100k create and format) | 161 ms | 19.6 ms | | `nox.unicode.normalize` (NFC, 20 passes) | 20.1 ms | 8.7 ms | | `nox.fs.read_to_string` | one extra copy | read straight into the string | - **String building.** An f-string, or a `+` chain that contains a string literal, now compiles to a single allocation: plain `int` parts are written straight into the result instead of going through an intermediate string. Evaluation order and results are unchanged. - **Collections.** `Set`, `Counter`, `OrderedDict` and `LRUCache` share a hash index that grows twenty times faster, and `remove` is amortised O(1) with insertion order kept. - **FFI.** A scalar `extern def` call costs the same as the C call it wraps (0.7 ns); a zero-copy list-to-pointer hand-off is within 14% of C. Where Nox is still behind C: the class-based collections (`Set[int]` about 17 times, `Deque` about 22 times, because each call goes through generic hashing and a pending-exception check), `sha512` (C uses the CPU's SHA-512 instructions) and string-heavy code that allocates one reference-counted string per step (4 to 6 times). `benchmarks/RESULTS.md` has the full tables. ## Smaller executables A program that prints one line is now 0.21 MB on macOS, 0.34 MB on Linux and 0.78 MB on Windows; cross-built Linux executables used to be 19 MB. See [Reduce binary size](https://noxlang.com/docs/howto/binary-size/). ## Standard library Six modules wrap well-known C libraries: [`nox.lz4`](https://noxlang.com/docs/stdlib/lz4/), [`nox.xxhash`](https://noxlang.com/docs/stdlib/xxhash/), [`nox.yyjson`](https://noxlang.com/docs/stdlib/yyjson/), [`nox.pcre2`](https://noxlang.com/docs/stdlib/pcre2/) (with JIT), [`nox.brotli`](https://noxlang.com/docs/stdlib/brotli/) and the compression half of [`nox.zstd`](https://noxlang.com/docs/stdlib/zstd/). They are linked only into programs that import them. The existing pure modules are unchanged. [How to use them](https://noxlang.com/docs/howto/embedded-c-libraries/). ## Packages Packages carry a **source label** (`nox`, `c`, `cpp`, `rust`, `go`, `zig` or `mixed`). `noxc publish` checks the label against the files in the repository and the registry shows it as a badge ([noxpkg](https://noxlang.com/docs/tools/noxpkg/)). ## Distribution - Release archives and the Windows installer include `lib/noxclibs.a`, which the C-backed modules above need. Earlier 2.1.x archives do not; `noxc upgrade` fixes that. - iOS and Android reject the C-backed modules at compile time instead of failing in the linker; for `nox.zstd` only the `compress` call is rejected, `decompress` works. ## Networking, security and tooling added in the final 2.1.x releases - **Resolve, validate, connect.** [`nox.dns.resolve(host)`](https://noxlang.com/docs/stdlib/dns/) is a separate, time-bounded lookup, and `nox.http.request(..., connect_ip=ip)` connects to an address you have checked while TLS still verifies the original host name (no DNS-rebinding window). `request(..., ca_file="ca.pem")` verifies HTTPS against only the CAs in that file; verification is never switched off. - **Listen on one interface.** `nox.http.configure(bind_address="127.0.0.1")` binds the server to a single IPv4/IPv6 address (the HTTP/3 UDP listener follows). - **Multi-core servers on macOS and Windows.** `serve_multicore` shares one listening socket there, because `SO_REUSEPORT` does not balance connections on BSD; Linux keeps per-worker sockets. See the [guidance](https://noxlang.com/docs/stdlib/http/) on handlers that do almost no work. - **Authenticated encryption.** [`nox.crypto.aead_seal` / `aead_open`](https://noxlang.com/docs/stdlib/crypto/) (ChaCha20-Poly1305, XChaCha20-Poly1305, AES-GCM). - **Redis.** `Client.set_read_timeout(ms)` (a timeout closes the client; `reconnect()`), and `Client.pipeline(commands)`. - **Windows fixes.** A child started with `nox.process.Command` now inherits the parent's environment (it used to start with none, so a compiled program could not run `noxc run`), and `nox.terminal.write_raw` works on Windows and WebAssembly, including with redirected output. - **Smaller additions.** `nox.os.environ()` / `env_names()`; `nox.sqlite` `execute` runs every statement of a multi-statement string; `noxc publish --help`; `noxc sbom` reports a `bin`-only package as `nox:native=false`; `from m import (...)` over several lines; `and`/`or` narrowing of optional values. ## Known limits carried to 2.3 Nested `async def` (use a module-level `async def` and pass values as parameters), `list[Task[T]]` (use `TaskGroup`), Redis Cluster, a per-client `nox.http` connection pool, a portable shutdown event for Windows and WASM, and PostgreSQL read timeouts on mobile/WASM. The list is tracked in `project/v2-3-yapilacaklar-2026-11.md`. --- # What's new in Nox 2.1 Nox 2.1 keeps every 2.0 promise (the [stability policy](https://noxlang.com/docs/apis/stability/) is unchanged) and adds what the 2.0 line grew into: Nox in the browser and on WebAssembly, a much stronger HTTP stack, real cross-compilation, scripts, and a safer release and standard library. Nothing that compiled on 2.0 stops compiling; the few behaviour changes are listed under [Upgrading](#upgrading). ## Nox runs everywhere WebAssembly does - **WebAssembly targets.** `noxc build --target wasm32-wasi` and `wasm32-freestanding` compile through LLVM, with real fibers (`--asyncify`) and real parallel tasks (`--threads`). Most of the standard library works there, including `nox.http` (client and server), `nox.sqlite`, `nox.postgres`, `nox.mysql`, `nox.websocket`, `nox.process` and a persistent virtual file system. Host capabilities are opt-in and can be denied (`--deny-capability`). See [WebAssembly](https://noxlang.com/docs/tools/wasm/). - **The compiler in the browser.** The front end ships as `noxc-frontend.wasm`; together with a WebAssembly C toolchain it compiles and runs Nox entirely client-side ([Browser compiler](https://noxlang.com/docs/tools/browser-compiler/)). - **The Playground.** [noxlang.com/playground](https://noxlang.com/playground/) (beta) is written in Nox and runs your program in the page; nothing is sent to a server ([Playground](https://noxlang.com/docs/tools/playground/)). ## Cross-compile from any machine `noxc build --target ` now produces `macos-arm64`, `macos-x64`, `linux-x64`, `linux-arm64`, `linux-riscv64` and `windows-x64` programs from any host with `zig`. They go through the LLVM back end by default, so cross-built programs run at `-O2` speed, and a Windows `.exe` built on Linux is run on Windows in CI on every change ([Back ends](https://noxlang.com/docs/tools/backends/)). ## On phones (experimental) The four mobile targets (`ios-arm64`, `ios-simulator-arm64`, `android-arm64`, `android-x64`) now reach nearly the same standard-library coverage as WebAssembly: 45 of the 50 standard-library modules compile for them (WebAssembly: 46), and the five that do not are platform rules (`nox.process`, `nox.native`, `nox.plugin`, `nox.hpy`, `nox.sharedmem`). `nox.postgres` and `nox.mysql` work through drivers written in Zig, because a phone has no `libpq` or `libmysqlclient` (PostgreSQL uses TLS with `sslmode=require`; the MySQL driver has no TLS yet, so use it only on a network you trust). The whole fixture corpus, 468 programs, runs on the iOS simulator and on the Android emulator with identical output, and CI repeats it. The mobile targets stay **experimental**: there is no physical-device lab yet ([Mobile support matrix](https://noxlang.com/docs/internals/mobile-matrix/)). ## Scripts Put `#!/usr/bin/env -S noxc run` on the first line and `chmod +x`: a Nox file runs like a script, arguments included, with the compiled binary cached between runs ([Scripts](https://noxlang.com/docs/tools/noxc/#scripts)). ## A stronger HTTP stack HTTP/2 on the server (TLS ALPN and h2c, trailers, WebSocket over HTTP/2), streaming responses and server-sent events, graceful shutdown with a drain period, connection pooling and proxy support for the client, and `nox.web` for building applications ([HTTP](https://noxlang.com/docs/stdlib/http/), [Web](https://noxlang.com/docs/stdlib/web/)). ## Language Generators and `yield`, `__del__`, real multiple inheritance, and streaming file and HTTP bodies landed during the 2.0 line. See the [language reference](https://noxlang.com/docs/language/). ## Safer by default - **`nox.path.safe_join(root, requested)`** confines an untrusted path under a root, rejecting `..`, symbolic-link escapes and sibling directories ([Path](https://noxlang.com/docs/stdlib/path/#confining-untrusted-paths)). `strip_prefix` now respects component boundaries. - **Signed releases and a bill of materials.** Every archive carries a build-provenance attestation you can check with `gh attestation verify`, and each release ships an SPDX software bill of materials ([Install](https://noxlang.com/docs/install/#verify-where-an-archive-came-from)). A release is published only after every platform archive is uploaded. - **Fuzzing of the parsers that read untrusted bytes**: the HTTP/2 header decoder and the MySQL protocol client join the compiler front end and the WebAssembly parser. - `extern def ... from "path"` now finds a relative library from the project root, so building from a subdirectory works ([FFI](https://noxlang.com/docs/language/ffi/)). ## Tooling and distribution `noxc login`, `whoami`, `publish`; a progress display; `noxc upgrade` that respects package managers. Installers for every platform: Homebrew, AUR (`noxc-bin`), AppImage, Snap and a Windows installer. [noxlang.com](https://noxlang.com/) has a new download page that detects your system, more tutorials, and a registry ([noxpkg](https://noxlang.com/docs/tools/noxpkg/)) with publisher identity. ## Upgrading Run `noxc upgrade` (or your package manager). Behaviour changes: - `noxc run script.nox a b` passes everything after the file to the program. Compiler options go **before** the file (`noxc run --backend qbe script.nox`); `--` is still accepted. - `noxc build --backend llvm --target ` now builds (it used to be an error); `--target` without `--backend` uses LLVM when `zig` is installed. `-g`, `--emit-asm` and freestanding builds stay on QBE. - `nox.path.strip_prefix("/srv/dataevil/x", "/srv/data")` now returns the path unchanged instead of `evil/x`. The full list is in the [changelog](https://github.com/mburakmmm/nox-lang/blob/main/CHANGELOG.md). --- # What's new in Nox 2.0 Nox 2.0 is the first release with a **stability promise** across the language, the standard library and the native interface ([Stability](https://noxlang.com/docs/apis/stability/)). It completes the Python-like language surface, makes both back ends behave identically, introduces the three public APIs, and ships complete documentation. If you are upgrading from 1.x, start with [Migrating from 1.x](https://noxlang.com/docs/whatsnew/migrating/). ## A complete everyday language Python's day-to-day syntax is now covered, with static types: - **Control flow:** `break`/`continue`, chained comparisons (`0 <= i < n`), `in`/`not in`, conditional expressions, `assert`, `for` over ranges with steps, strings, dictionaries and any list expression; custom iteration with `__iter__`. - **Functions:** default and keyword arguments (evaluated left to right as written), lambdas, closures, first-class functions and bound methods, higher-order generics with inference from lambdas, generic classes and generic methods. - **Data:** tuples with unpacking and multiple return, `set[T]` with literals and operators, full list and dictionary APIs, negative indexing, slicing (`xs[1:-1]`, `s[::-1]`), list/dictionary/set comprehensions and generator expressions as call arguments. - **Classes:** single inheritance with `super()`, a complete special-method protocol (`__add__`, `__eq__`, `__lt__`, `__getitem__`, `__contains__`, `__len__`, `__iter__`, `__str__`, `__repr__`, `__bool__`, …), structural protocols, class docstrings. - **Strings:** f-strings with the full format mini-language, `str.format`, triple-quoted strings, dozens of string methods, `str()`/`repr()` of any value, Python-compatible float printing. - **Numbers:** hexadecimal/binary/octal/underscore literals, exact `round(x, n)`, fixed-width integers (`u8`…`i64`) with overflow traps, exact integer `**`. - **Errors:** `except (A, B) as e`, `finally`, `with`, `defer`, `ZeroDivisionError`, readable syntax errors with file, line, column and a caret. - **Concurrency:** tasks, channels, cooperative cancellation, task-local values, a multi-core work-stealing scheduler. ## The same program on both back ends LLVM is now the default back end (about 1.5× the time of C across a mixed benchmark suite), and **both back ends produce identical output**: fixed-width overflow traps on both, plain `int` wraps on both, keyword arguments evaluate in source order on both. A differential test runs the entire corpus on both on every release. `clang` is no longer required: the compiler falls back to `zig cc`, and then to QBE. Windows is supported end to end through `zig cc`. ## Three public APIs - **[NAPI](https://noxlang.com/docs/apis/napi/)** — what framework and library authors may rely on, with a constructor-freeze policy for standard-library classes. - **[NNI v1](https://noxlang.com/docs/apis/nni/)** — a stable C ABI for native extensions in C, C++, Rust and Zig, with opaque generation-counted handles, thread-safe events and an optional shutdown hook. - **[Plugin API](https://noxlang.com/docs/apis/plugin-api/)** — manifests, version negotiation, typed call checking, registration cross-checks and capability consent. ## A larger standard library New or greatly extended: `nox.collections` (stack, queue, deque, counter, ordered map, LRU cache, heap, priority queue), `nox.binary`/`nox.buffer`/`nox.bits` for binary formats, `nox.mem` and typed pointers for systems code, `nox.atomic`, `nox.sharedmem`, `nox.url`, `nox.base64`, `nox.jwt`, `nox.crypto` (SHA-2, HMAC, Argon2id/bcrypt/scrypt), `nox.toml`/`nox.yaml`/`nox.csv`, `nox.sqlite`/`nox.postgres`/`nox.mysql` with `nox.orm`, `nox.websocket` and `nox.tls`, server-side TLS and WebSocket upgrade, a router with query strings and middleware, `nox.validate` with nested schemas, `nox.reflect`, `nox.native`, `nox.plugin`. See the [standard library reference](https://noxlang.com/docs/stdlib/) — every module is documented. ## Tooling and ecosystem - `noxc` gains `check`, `explain`, `expand`, `fmt`, `add`, `delete`, `publish`, `install`, `upgrade`, `test`, `cache prune`; a real formatter; an LSP server; a VS Code extension and a tree-sitter grammar. Diagnostics, standard-library exceptions and status lines are English; `noxc --help` follows the locale. - A central package index, **noxpkg**, with moderated publishing, and signed-commit verification for dependencies. - The **Nyx** web framework and the **Aether** framework are built on Nox 2.x. ## Systems programming Fixed-width integers, `ptr[T]`, volatile access, `@repr("C")`/`@packed` layouts, `@ffi.callback`, `--profile freestanding` with a kernel-provided allocator, multiple target architectures, and a complete demo kernel written in Nox. ## Quality Roughly 1,250 tests across 180 build steps, fuzzing of the front end, concurrency torture suites, an HTTP soak test, differential testing of back ends, and CI on Linux x86-64, Linux aarch64, macOS and Windows. A release is published only after CI is green on the tagged commit. ## Breaking changes The deprecated `nox.json` and `nox.csv` aliases are gone; a few behaviours changed to match Python expectations (float printing, negative indexes, overflow traps, zero division). The complete list, with fixes, is in [Migrating from 1.x](https://noxlang.com/docs/whatsnew/migrating/). ## Known limits in 2.0.0 At 2.0.0, `*args`/`**kwargs` and multiple inheritance were not yet part of the language, and tasks and channels could not be stored in collections (gather results through a channel). The first two have since been added without breaking any existing code; the [language reference](https://noxlang.com/docs/language/python-differences/) lists all current differences from Python. ## Since 2.0.0 The 2.x series keeps its [stability promise](https://noxlang.com/docs/apis/stability/) while it grows. Highlights of the releases after 2.0.0 (the [changelog](https://github.com/mburakmmm/nox-lang/blob/main/CHANGELOG.md) has every one): - **Language:** keyword-only and positional-only parameters, `*args`/`**kwargs` and call-site unpacking; real multiple inheritance; lazy `yield` generators; destructors with `__del__`; generic classes and methods across modules; Go-style `defer`; module-level global state. - **Web:** an **HTTP/2 server** (TLS ALPN and cleartext), streaming responses and server-sent events, graceful shutdown, trailers, an outgoing connection pool, proxy support and `nox.web` (cookies, CORS, rate limiting). - **WebAssembly as a general target:** the standard library — files, SQLite, HTTP client and server, WebSocket, TLS, SMTP, PostgreSQL, MySQL, child processes — compiles to WebAssembly, with network, sockets, processes and servers provided by the host as opt-in *capabilities*; real fibers (`--asyncify`) and real threads (`--threads`). The compiler itself runs in a browser: see the [Playground](https://noxlang.com/docs/tools/playground/). - **Installing and publishing:** a Windows installer, a Homebrew tap, an AppImage, a Snap and an AUR package, a download page ([noxlang.com/download](https://noxlang.com/download/)), progress output for network commands, and `noxc login` with GitHub for publishing to the noxpkg registry — a republish by a package's owner for the same repository goes live without a new approval. - **Hardening:** reserved symbol names, a capability model with `--deny-capability`, allow-lists for network and process access in the WebAssembly host, and a much larger test suite that runs on Linux, macOS and Windows. --- # Migrating from Nox 1.x to 2.0 Nox 2.0 removes the names that were deprecated during 1.x and aligns a handful of behaviours with common Python expectations. The versioning policy ([Versioning](https://noxlang.com/docs/reference/versioning/)) allows removal only in a major release, so this page lists every change you can observe, with the fix. Most programs need no change; the compiler reports removed names as errors. ## 1. Removed names (compile errors) **`nox.json`** — renamed in 1.x to the `parse`/`dump` family, old names removed: | Removed | Use instead | |---|---| | `decode` | `parse` | | `encode` | `dump` | | `encode_pretty` | `dump_pretty` | | `encode_string` | `dump_string` | | `encode_array` | `dump_array` | | `encode_object` | `dump_object` | | `encode_pretty_at` | `dump_pretty_at` | | `encode_pretty_array` | `dump_pretty_array` | | `encode_pretty_object` | `dump_pretty_object` | **`nox.csv`:** | Removed | Use instead | |---|---| | `write` | `dump` | | `write_row` | `dump_row` | The replacements have identical signatures: the fix is a rename. ## 2. Behaviour changes (may silently affect 1.x code) | Area | 1.x | 2.0 | |---|---|---| | Printing a `float` | `printf`-style formatting | Python's `repr`: `0.1`, `2.0`, `1e+16`, `inf`, `nan` | | Negative indexes | undefined | Python semantics: `xs[-1]` is the last element; out of range raises `IndexError` (lists, strings, assignment, `pop`, `del`) | | Fixed-width integer overflow (`u8`, `i32`, …) | LLVM wrapped, QBE trapped | **traps on both back ends**; plain `int` wraps on both | | `int ** int` | computed through a `double` (inexact above 2⁵³, back ends disagreed) | exact integer exponentiation with 64-bit wrap-around; a negative exponent gives `0` (use a `float` base for fractions); `0 ** negative` raises `ZeroDivisionError` | | Integer `//` and `%` by zero | undefined / garbage | raises `ZeroDivisionError` | | Keyword arguments | evaluated in parameter order | evaluated **in the order written**; bound by name afterwards (`spawn` requires side-effecting keyword arguments in parameter order) | | `print(None)`, `print(optional)` | unsupported / printed a pointer | prints `None` | | `print(obj)` and containers | class name only | `__str__`/`__repr__` if defined, otherwise `Name(field=value, …)` structurally, recursively | | `nox.router` | the query string was part of the matched path (`/x?a=1` never matched `/x`) | the query string is stripped before matching and exposed as `Context.query` | | `int(x)` on fixed-width integers and `bool` | not available | available: `int(u8_value)`, `int(True)` | | SQL parameter binding | an out-of-range `bind_*` index silently bound nothing | raises the driver's error; indexes are **zero-based** | | `noxc build -g` | failed on the default (LLVM) back end | selects the QBE back end automatically; `-g` with an explicit `--backend llvm` is an error | | Parser nesting | unbounded | expression depth limited to 200 with a readable error | | Syntax errors | one raw line | `file:line:column`, the source line and a caret | | `HttpRequest(...)` constructor | `peer_addr` was required | `peer_addr: str = ""` (new constructor parameters now always have defaults) | ## 3. New (non-breaking) features worth knowing See [What's new in Nox 2.0](https://noxlang.com/docs/whatsnew/2.0/): hexadecimal/binary/octal/underscore literals, f-string format specs and `str.format`, triple-quoted strings and docstrings, `except (A, B) as e`, chained comparisons, `assert`, generator expressions (eager), `set[T]`, `__iter__`, generic methods and classes, `nox.native` and `nox.plugin`, many new standard-library modules. ## 4. Known limits that may matter when porting Class-level attributes, annotated `self.x: T = v`, empty `[]`/`{}` literals nested inside other literals, and `list[Task[T]]` are not supported (`*args`/`**kwargs` and multiple inheritance, which were missing in 2.0.0, have been available since 2.0.x); a protocol cannot be an element type (`list[Protocol]`); `set` elements are `int`, `float`, `bool` or `str`; generator expressions are evaluated eagerly. See [Differences from Python](https://noxlang.com/docs/language/python-differences/). ## 5. Checklist 1. Rebuild with `noxc check` on every entry file; fix removed-name errors (section 1). 2. Search your code for `float` printing in expected output (tests, golden files) — the text may differ (`2.0`, not `2`). 3. Search for `**` on integers and for fixed-width arithmetic that relied on wrap-around: use `int` and mask (`& 0xFFFFFFFF`) to wrap deliberately. 4. If you matched routes with query strings in a custom way, simplify: use `Context.query`. 5. If you supply `HttpRequest` objects in tests, nothing changes; if you subclass or wrap `nox.http`, re-read [`nox.http`](https://noxlang.com/docs/stdlib/http/). 6. Pin Nox 2.x in CI. --- # Installing Nox Nox ships as a single archive per platform containing `noxc` (the compiler and tool), `noxlsp` (the language server), the runtime objects, the standard library, the bundled `qbe` back end (Linux, macOS) and the header `include/nox_nni.h`. Prefer a picker that detects your system and shows every option? Use the [download page](https://noxlang.com/download/). Just want to try the language first? Open the [Playground](https://noxlang.com/playground/) — nothing to install. ## Requirements - **To compile and run programs:** a C toolchain for linking (`cc`) — Xcode Command Line Tools on macOS, `build-essential`/`gcc` on Linux, MinGW-w64 or Zig on Windows — and, for the default LLVM back end, **`clang` or `zig`** on `PATH`. With neither, Nox falls back to the bundled QBE back end automatically. - **To build Nox from source:** [Zig](https://ziglang.org) 0.16. ## macOS and Linux ```sh curl -fsSL https://noxlang.com/install.sh | sh ``` The script downloads the latest release for your platform (macOS arm64, Linux x86-64, Linux arm64) and unpacks it under `~/.nox-lang`. Add its `bin` directory to your `PATH`: ```sh export PATH="$HOME/.nox-lang/bin:$PATH" noxc --version ``` Environment variables for the installer: `NOX_INSTALL_DIR` (install root) and `NOX_VERSION` (a specific tag such as `v2.0.0` instead of the latest). ## Arch Linux (AUR) ```sh yay -S noxc-bin # or any AUR helper ``` *The package is being published to the AUR. Until it appears there, build it from this repository (it downloads the release archive):* ```sh git clone https://github.com/mburakmmm/nox-lang && cd nox-lang python3 scripts/update_aur_package.py --tag v --outdir /tmp/noxc-bin cd /tmp/noxc-bin && makepkg -si ``` `noxc-bin` installs the prebuilt release (x86-64 and aarch64) under `/usr/lib/noxc` with `noxc` and `noxlsp` in `/usr/bin`, and needs `gcc` to link (`clang` or `zig` are optional). Update it through your AUR helper; `noxc upgrade` refuses to run on a pacman install and tells you so. ## Snap (Linux) ```sh sudo snap install noxc --classic ``` *The Snap Store listing is awaiting approval of the classic confinement. Until it is live, install the `.snap` attached to a [release](https://github.com/mburakmmm/nox-lang/releases):* `sudo snap install --dangerous --classic noxc__amd64.snap`. The snap uses *classic* confinement because `noxc` has to run your system's C toolchain and write wherever your project lives. `noxc` and `noxlsp` are available as `noxc` and `noxc.noxlsp`. Update with `sudo snap refresh noxc` (snaps also refresh themselves); `noxc upgrade` refuses to run on a snap install. ## AppImage (Linux) Download `noxc--x86_64.AppImage` (or `aarch64`) from the [releases](https://github.com/mburakmmm/nox-lang/releases), then: ```sh chmod +x noxc-*.AppImage ./noxc-*.AppImage run hello.nox # arguments go to noxc ``` One file, no installation, any distribution (it needs FUSE, or run it with `--appimage-extract-and-run`). Name it or link it as `noxc` to put it on your `PATH`; invoked under the name `noxlsp` it starts the language server instead. Update by downloading the new file (`noxc upgrade` refuses to run from an AppImage). ## Homebrew (macOS and Linux) ```sh brew tap mburakmmm/nox brew install noxc ``` This installs `noxc` and `noxlsp` and puts the bundled `qbe` where `noxc` finds it. Apple Silicon macOS, Linux x86-64 and Linux arm64 are supported (there is no Intel macOS build). Update with `brew upgrade noxc`; `noxc upgrade` refuses to run on a Homebrew install and tells you so. ## Windows **Installer (recommended).** Download `nox-lang-v-windows-x64-setup.exe` from the [GitHub releases](https://github.com/mburakmmm/nox-lang/releases) and run it. It installs for your user by default (no administrator rights, under `%LOCALAPPDATA%\Programs\Nox`; the first page offers "install for all users" instead), can add Nox to your `PATH`, and registers an uninstaller in *Settings → Apps*. Uninstalling removes only the `PATH` entry it added. Silent install for scripts: `nox-lang-v-windows-x64-setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART` (add `/DIR="C:\tools\nox"` to choose the folder, `/MERGETASKS="!addpath"` to skip the `PATH` change). The installer is not code-signed yet, so Windows SmartScreen may show a warning the first time: choose *More info → Run anyway*, or verify the `.sha256` file next to the download. **Script.** ```powershell irm https://noxlang.com/install.ps1 | iex ``` This installs `noxc.exe` and friends under `%USERPROFILE%\.nox-lang` (override with `NOX_INSTALL_DIR`) and checks for a C toolchain. Install [Zig](https://ziglang.org/download/) (`winget install zig.zig`) so Nox can use `zig cc` to link — this is also the default LLVM path on Windows. ## From a release archive Download `nox-lang--.tar.gz` (or `.zip` on Windows) and its `.sha256` file from the [GitHub releases](https://github.com/mburakmmm/nox-lang/releases), verify the checksum, unpack, and put `bin/` on your `PATH`. The archive's layout is `bin/`, `lib/` (runtime objects and `lib/nox/stdlib`) and `include/`. ### Verify where an archive came from The `.sha256` file only proves the download is intact. Each release archive also carries a signed **build provenance attestation** (GitHub/Sigstore, keyless) that records which workflow run and commit produced it. With the [GitHub CLI](https://cli.github.com): ```sh gh attestation verify nox-lang--.tar.gz --repo mburakmmm/nox-lang ``` Every release also ships `nox-lang--sbom.spdx.json`, an SPDX 2.3 software bill of materials listing what goes into the archive (Nox, SQLite, QBE, the Zig standard library), and that file is attested the same way. ## From source ```sh git clone https://github.com/mburakmmm/nox-lang cd nox-lang zig build # builds into zig-out/ zig-out/bin/noxc --version zig build test --summary all # optional: the full test suite ``` ## Updating ```sh noxc upgrade --check # is there a newer release? noxc upgrade # update in place (checksum verified; installs managed by Homebrew use `brew upgrade noxc`) noxc upgrade v2.1.0 # a specific version ``` ## Check your installation ```sh printf 'print("hello from nox")\n' > hello.nox noxc run hello.nox ``` Next: the [tutorial](https://noxlang.com/docs/tutorial/). ## Troubleshooting | Symptom | Fix | |---|---| | `noxc: command not found` | add the install `bin/` directory to `PATH` | | a note that neither clang nor zig was found and QBE is used | install `clang` (Xcode CLT / `apt install clang`) or `zig` for the faster LLVM back end; the program still compiles | | linking fails with `cc` not found | install a C toolchain (`xcode-select --install`, `apt install build-essential`) | | `libsqlite3` / `libpq` / `libmysqlclient` errors at run time | those libraries are loaded on first use; install the one you need | | Windows: build errors about MinGW | install Zig and re-run; or install MinGW-w64 and ensure `cc` is on `PATH` | --- # Editor support ## Visual Studio Code The `vscode-nox` extension (in the repository's `editors/vscode-nox`) provides: - syntax highlighting (TextMate grammar), including `nox` fences in Markdown; - a file icon for `.nox` in icon themes that show language icons (the default Seti theme does; Minimal and None do not); - indentation folding, Enter-to-indent after `:`, and snippets (`def`, `class`, `for`, `while`, `if`, `try`, `protocol`); - the language server: diagnostics, completion, hover, go to definition (including imports), references, rename, outline, signature help, semantic tokens, parameter-name hints and formatting ([language server](https://noxlang.com/docs/tools/lsp/)); - a Testing view for `*_test.nox` files (`noxc test`) and a **Run test** CodeLens on `def test_`; - command-palette actions **Nox: Run File**, **Nox: Check File** and **Nox: Test** (`noxc` in an integrated terminal); - debugging through CodeLLDB using `noxc build -g` ([Debugging](https://noxlang.com/docs/tools/debugging/)). **Nox: Debug File** adds the launch configuration; install CodeLLDB first. Build and try it from a checkout: ```sh cd editors/vscode-nox npm install npm run compile # open this folder in VS Code and press F5 to launch an Extension Development Host npx @vscode/vsce package ``` `vsce package` writes `noxlang-.vsix` in this directory. Install it with **Extensions: Install from VSIX...**, or upload that file on the [Marketplace management page](https://marketplace.visualstudio.com/manage) under the publisher `nox-lang` (the `publisher` field in `package.json` must match). The language client is bundled into the package. `noxlsp` is not: the extension looks on `PATH`, then in `~/.nox-lang/bin` (`%USERPROFILE%\.nox-lang\bin` on Windows). Set **`nox.languageServerPath`** to skip that search. If the binary is missing, the error offers a link to the install page. ## Any LSP-capable editor Configure your editor's LSP client to launch `noxlsp` (stdio) for `*.nox` files — for example in Neovim with `vim.lsp.start({ name = "noxlsp", cmd = { "noxlsp" }, root_dir = vim.fn.getcwd() })` for the `nox` filetype, or in Helix/Emacs/Sublime with their LSP configuration. You get the same diagnostics, completion, hover, definition and formatting. ## Tree-sitter `editors/tree-sitter-nox` is a Tree-sitter grammar for Nox (highlighting, folding, structural selection). It covers nearly the whole syntax; the compiler's own parser remains the single source of truth. ```sh cd editors/tree-sitter-nox npm install npm run generate # grammar.js -> src/parser.c npm test # corpus tests ``` ## Formatting `noxc fmt file.nox` formats a file; editors get the same result through the language server ([Formatter](https://noxlang.com/docs/tools/formatter/)). --- # Tutorial This tutorial teaches Nox by building up small, complete programs. It assumes you can read a little Python or any similar language; it does not assume you know anything about types, compilers or memory management. Every code block compiles, and every block followed by its output was run to produce it. | Chapter | You will learn | |---|---| | [1. Hello, Nox](https://noxlang.com/docs/tutorial/01-hello/) | install check, `noxc run`, `noxc build`, projects | | [2. Values and types](https://noxlang.com/docs/tutorial/02-values-and-types/) | `int`, `float`, `str`, `bool`, annotations, f-strings, conversions | | [3. Control flow](https://noxlang.com/docs/tutorial/03-control-flow/) | `if`, `while`, `for`, `range`, `break`/`continue` | | [4. Functions](https://noxlang.com/docs/tutorial/04-functions/) | parameters, defaults, keyword arguments, closures, lambdas | | [5. Collections](https://noxlang.com/docs/tutorial/05-collections/) | lists, dictionaries, sets, tuples, comprehensions | | [6. Classes](https://noxlang.com/docs/tutorial/06-classes/) | classes, inheritance, special methods, protocols, generics | | [7. Errors](https://noxlang.com/docs/tutorial/07-errors/) | exceptions, `finally`, `with`, `defer` | | [8. Modules and packages](https://noxlang.com/docs/tutorial/08-modules-and-packages/) | multi-file projects, `nox.json`, dependencies | | [9. Concurrency](https://noxlang.com/docs/tutorial/09-concurrency/) | tasks, channels, fan-out/fan-in | | [10. A small web service](https://noxlang.com/docs/tutorial/10-a-small-web-service/) | HTTP server, routing, JSON | | [11. Files and JSON](https://noxlang.com/docs/tutorial/11-files-and-json/) | reading and writing files, directories, parsing and producing JSON | | [12. Testing](https://noxlang.com/docs/tutorial/12-testing/) | `noxc test`, assertions, `TestSuite`, testing handlers | | [13. Generics and protocols](https://noxlang.com/docs/tutorial/13-generics-and-protocols/) | one function or container for many types, shape-based interfaces | | [14. Databases](https://noxlang.com/docs/tutorial/14-databases/) | SQLite, prepared statements, transactions, PostgreSQL and MySQL | | [15. Command-line tools](https://noxlang.com/docs/tutorial/15-command-line-tools/) | arguments, environment, input, exit codes, running programs | | [16. WebAssembly and the browser](https://noxlang.com/docs/tutorial/16-webassembly/) | targets, capabilities, running in a page, the Playground | | [17. Publishing a package](https://noxlang.com/docs/tutorial/17-publishing/) | `nox.json`, tags, `noxc login`, `noxc publish` | | [18. Next steps](https://noxlang.com/docs/tutorial/18-next-steps/) | where to go from here | | [Recipes](https://noxlang.com/docs/tutorial/recipes/) | short answers: word counts, grouping, tables, retries, tasks | ## Conventions Commands you type in a terminal are shown in `sh` blocks. Nox source is shown in `nox` blocks; when a block is followed by an `output` block, that is exactly what the program prints. Compiler error messages are English; branch on the error kind and the exit status, not on the wording. If you want to experiment as you read, save a block as `hello.nox` and run `noxc run hello.nox` (see [Install](https://noxlang.com/docs/install/) if `noxc` is not available yet) — or paste it into the [Playground](https://noxlang.com/playground/) and run it in your browser without installing anything. --- # 1. Hello, Nox ## Run a file Create `hello.nox`: ```nox print("Hello, Nox!") ``` ```output Hello, Nox! ``` Run it: ```sh noxc run hello.nox ``` `noxc` type-checks the file, compiles it to a native executable, and runs it. The statements at the top level of the file *are* the program — there is no `main` function to write. ## Build an executable ```sh noxc build -o hello hello.nox ./hello ``` `noxc build` produces a standalone binary with the Nox runtime linked in. It starts instantly, has no dependencies on a Nox installation, and can be copied to another machine of the same platform. ## Check without compiling ```sh noxc check hello.nox ``` `check` runs only the front end (parsing and type checking), so it is the fastest way to see errors while you edit. ## Start a project ```sh noxc init demo cd demo noxc run main.nox ``` `noxc init` creates a directory with a `nox.json` manifest and a `main.nox`. A project is what you need once you have more than one file or want to use third-party packages (chapter 8). ## Comments and layout Nox uses Python's layout: blocks are indented (with spaces), `#` starts a comment, and one statement goes on each line. ```nox # a comment total: int = 1 + 2 # a trailing comment print(total) ``` ```output 3 ``` ## A taste of what is different Unlike Python, every variable has a **type**, written after the name when it is first created. The compiler checks types before the program runs — a misspelled name or a `str` where an `int` is expected is reported immediately, not discovered in production. ```nox price: int = 20 tax: int = price // 5 print(price + tax) ``` ```output 24 ``` The next chapter explains the types. --- # 2. Values and types ## The basic types ```nox age: int = 36 height: float = 1.82 name: str = "Ada" active: bool = True print(age, height, name, active) ``` ```output 36 1.82 Ada True ``` | Type | Examples | |---|---| | `int` | `0`, `-7`, `1_000_000`, `0xFF` (64-bit, wraps on overflow) | | `float` | `3.14`, `1e-3` | | `str` | `"text"`, `'text'`, `"""multi-line"""` | | `bool` | `True`, `False` | | `None` | `None` — "no value"; see [optionals](https://noxlang.com/docs/language/types/#optional-types) | A variable is created by its first assignment, which carries the type. Later assignments do not repeat it: ```nox counter: int = 0 counter = counter + 1 counter += 1 print(counter) ``` ```output 2 ``` Assigning a value of the wrong type is a compile error — `counter = "one"` would be rejected before the program runs. ## Arithmetic ```nox print(7 + 2, 7 - 2, 7 * 2, 7 / 2, 7 // 2, 7 % 2, 7 ** 2) print(-7 // 2, -7 % 2) ``` ```output 9 5 14 3.5 3 1 49 -4 1 ``` `/` always gives a `float`; `//` and `%` round toward minus infinity, like Python. Mixing an `int` and a `float` gives a `float`. ## Strings ```nox first: str = "Ada" last: str = "Lovelace" full: str = first + " " + last print(full, len(full), full.upper(), full[0], full[-1]) print(full.split(" "), "Love" in full, full.replace("a", "4")) ``` ```output Ada Lovelace 12 ADA LOVELACE A e ['Ada', 'Lovelace'] True Ad4 Lovel4ce ``` Strings are immutable and indexed by character (code point), so non-English text works as you expect. ### f-strings Put an expression in braces inside an `f"..."` string. A format specification after a colon controls the layout: ```nox item: str = "tea" price: float = 3.5 qty: int = 4 print(f"{item}: {qty} x {price} = {qty * price}") print(f"{price:8.2f}|{qty:03d}|{item:>6}|{1234567:,}") ``` ```output tea: 4 x 3.5 = 14.0 3.50|004| tea|1,234,567 ``` ## Converting between types Conversions are always explicit: ```nox print(int("42") + 1, float("2.5") * 2, str(7) + "!", int(3.9), float(3), bool(0)) ``` ```output 43 5.0 7! 3 3.0 False ``` `int("abc")` raises `ValueError` (chapter 7). The only implicit conversion is `int → float` when a `float` is expected. ## Reading input ```nox line: str = input() print("you typed:", line) ``` `input()` reads one line from standard input. ## Conditions are `bool`s Nox does not treat `0`, `""` or `[]` as false. A condition must be a `bool`, produced by a comparison: ```nox n: int = 0 if n == 0: print("zero") items: list[int] = [] if len(items) == 0: print("empty") ``` ```output zero empty ``` ## Numbers that must not overflow `int` wraps around at 64 bits. For code that must never overflow silently there are fixed-width types such as `u8` and `i32` that stop the program instead — see [Numbers](https://noxlang.com/docs/language/numbers/). --- # 3. Control flow ## `if` ```nox temperature: int = 23 if temperature > 30: print("hot") elif temperature > 15: print("pleasant") else: print("cold") ``` ```output pleasant ``` Combine conditions with `and`, `or`, `not`; chained comparisons work as in Python: ```nox x: int = 5 if 0 < x < 10 and not x == 7: print("in range") label: str = "even" if x % 2 == 0 else "odd" print(label) ``` ```output in range odd ``` ## `while` ```nox n: int = 1 while n < 100: n = n * 3 print(n) ``` ```output 243 ``` ## `for` and `range` `range(stop)`, `range(start, stop)` and `range(start, stop, step)` produce integers: ```nox for i in range(3): print(i) for i in range(10, 0, -4): print(i) ``` ```output 0 1 2 10 6 2 ``` A `for` loop also walks the characters of a string, the elements of a list and the keys of a dictionary: ```nox for ch in "héy": print(ch) for word in ["red", "green"]: print(word.upper()) ``` ```output h é y RED GREEN ``` ## `break` and `continue` ```nox numbers: list[int] = [4, -1, 7, 200, 3] total: int = 0 for n in numbers: if n < 0: continue # skip negatives if n > 100: break # stop at the first big value total += n print(total) ``` ```output 11 ``` ## Variables live in the whole function A variable created inside an `if` or a loop is visible after it, because Nox has function scope, not block scope: ```nox for i in range(3): last: int = i * i print(last) ``` ```output 4 ``` ## A complete example: FizzBuzz ```nox for n in range(1, 16): if n % 15 == 0: print("FizzBuzz") elif n % 3 == 0: print("Fizz") elif n % 5 == 0: print("Buzz") else: print(n) ``` ```output 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ``` --- # 4. Functions ## Defining and calling ```nox def area(width: int, height: int) -> int: return width * height def greet(name: str) -> None: print("Hello,", name) greet("Ada") print(area(3, 4)) ``` ```output Hello, Ada 12 ``` Parameters and the return value are typed; `-> None` means the function returns nothing. A function that promises a value must return one on every path through its body — the compiler checks this. ## Default values and keyword arguments ```nox def connect(host: str, port: int = 8080, secure: bool = False) -> str: scheme: str = "https" if secure else "http" return scheme + "://" + host + ":" + str(port) print(connect("example.com")) print(connect("example.com", secure=True)) print(connect(port=9000, host="localhost")) ``` ```output http://example.com:8080 https://example.com:8080 http://localhost:9000 ``` Defaults are constant literals and come last. Arguments are evaluated in the order you write them. ## Returning several values ```nox def divide(a: int, b: int) -> tuple[int, int]: return a // b, a % b q, r = divide(17, 5) print(q, r) ``` ```output 3 2 ``` ## Functions are values A function has a type such as `(int) -> int`, and can be stored, passed and returned: ```nox def double(n: int) -> int: return n * 2 def apply_twice(f: (int) -> int, x: int) -> int: return f(f(x)) print(apply_twice(double, 5)) print(apply_twice(lambda n: n + 3, 5)) ``` ```output 20 11 ``` A **lambda** takes its types from where it is used — here the parameter type `(int) -> int`. ## Closures A nested function can read the variables around it, and stays valid after the outer function returns: ```nox def make_counter_step(step: int) -> (int) -> int: def advance(current: int) -> int: return current + step return advance by_five: (int) -> int = make_counter_step(5) print(by_five(10), by_five(by_five(0))) ``` ```output 15 10 ``` ## Recursion ```nox def factorial(n: int) -> int: if n <= 1: return 1 return n * factorial(n - 1) print(factorial(10), factorial(20)) ``` ```output 3628800 2432902008176640000 ``` `int` is 64-bit: `factorial(21)` would overflow and wrap. The `nox.mathx` module and fixed-width types give other options when that matters. ## Built-ins you will use constantly `len`, `sum`, `min`, `max`, `sorted`, `abs`, `round`, `range`, `enumerate`, `zip` — see [Built-in functions](https://noxlang.com/docs/language/builtins/). ```nox scores: list[int] = [72, 95, 88] print(len(scores), sum(scores), min(scores), max(scores), sorted(scores)) print(round(sum(scores) / len(scores), 1)) ``` ```output 3 255 72 95 [72, 88, 95] 85.0 ``` --- # 5. Collections ## Lists A `list[T]` holds elements of one type and grows as needed: ```nox fruits: list[str] = ["apple", "banana"] fruits.append("cherry") fruits.insert(0, "avocado") print(fruits, len(fruits), fruits[0], fruits[-1]) print(fruits[1:3], "banana" in fruits, fruits.index("cherry")) fruits.remove("banana") last: str = fruits.pop() print(fruits, last) ``` ```output ['avocado', 'apple', 'banana', 'cherry'] 4 avocado cherry ['apple', 'banana'] True 3 ['avocado', 'apple'] cherry ``` Indexes may be negative; an index out of range raises `IndexError`. Lists support `+`, `*`, `sort()`, `reverse()`, `extend()`, `copy()` and `clear()`: ```nox a: list[int] = [3, 1, 2] a.sort() b: list[int] = a + [10, 20] print(a, b, a * 2, sorted(b, reverse=True)) ``` ```output [1, 2, 3] [1, 2, 3, 10, 20] [1, 2, 3, 1, 2, 3] [20, 10, 3, 2, 1] ``` An empty list gets its type from the annotation: `names: list[str] = []`. ## Dictionaries A `dict[K, V]` maps keys to values and remembers insertion order: ```nox ages: dict[str, int] = {"ada": 36, "alan": 41} ages["grace"] = 85 print(ages, len(ages), ages["ada"], "alan" in ages) print(ages.get("bob", 0), ages.get("ada")) for name in ages: print(name, ages[name]) for name, age in ages.items(): print(name, "is", age) del ages["alan"] print(ages.keys(), ages.values()) ``` ```output {'ada': 36, 'alan': 41, 'grace': 85} 3 36 True 0 36 ada 36 alan 41 grace 85 ada is 36 alan is 41 grace is 85 ['ada', 'grace'] [36, 85] ``` `ages["missing"]` raises `KeyError`; `get` returns a default (or `None` when you give none). Keys are `int`, `float`, `bool` or `str`. ## Sets ```nox a: set[int] = {1, 2, 3} b: set[int] = {3, 4} a.add(9) print(a, 2 in a, len(a), a | b, a & b, a - b) ``` ```output {1, 2, 3, 9} True 4 {1, 2, 3, 9, 4} {3} {1, 2, 9} ``` Sets hold unique `int`, `float`, `bool` or `str` elements and keep insertion order. ## Tuples A tuple is a fixed group of values that may have different types. It is how functions return several values: ```nox point: tuple[int, int] = (3, 4) x, y = point person: tuple[str, int] = ("Ada", 36) print(point, x + y, person[0], person[1], point == (3, 4)) ``` ```output (3, 4) 7 Ada 36 True ``` ## Comprehensions Build collections from other collections in one expression: ```nox squares: list[int] = [n * n for n in range(6)] evens: list[int] = [n for n in range(10) if n % 2 == 0] lengths: dict[str, int] = {w: len(w) for w in ["a", "bb", "ccc"]} letters: set[str] = {c for c in "hello"} pairs: list[int] = [a * b for a in [1, 2] for b in [3, 4]] print(squares, evens, lengths, letters, pairs) ``` ```output [0, 1, 4, 9, 16, 25] [0, 2, 4, 6, 8] {'a': 1, 'bb': 2, 'ccc': 3} {'h', 'e', 'l', 'o'} [3, 4, 6, 8] ``` ## Sorting and searching ```nox words: list[str] = ["pear", "fig", "banana"] print(sorted(words), sorted(words, key=lambda w: len(w))) print(max(words, key=lambda w: len(w)), sum(len(w) for w in words)) for i, w in enumerate(words): print(i, w) print(zip([1, 2], ["a", "b"])) ``` ```output ['banana', 'fig', 'pear'] ['fig', 'pear', 'banana'] banana 13 0 pear 1 fig 2 banana [(1, 'a'), (2, 'b')] ``` Collections are **reference values**: `b: list[int] = a` makes both names refer to the same list, exactly as in Python, so an `append` (or `extend`/`insert`) through one name is seen through every other name — also when the list has to grow, and also when the list is a function parameter, a class field or an element of another list. Use `a.copy()` or `list(a)` to duplicate it. --- # 6. Classes ## A first class ```nox class Account: owner: str balance: int def __init__(self, owner: str, balance: int) -> None: self.owner = owner self.balance = balance def deposit(self, amount: int) -> None: self.balance += amount def describe(self) -> str: return self.owner + " has " + str(self.balance) acct: Account = Account("Ada", 100) acct.deposit(50) print(acct.describe()) print(acct) ``` ```output Ada has 150 Account(owner='Ada', balance=150) ``` A class declares its fields (`owner: str`) and a constructor `__init__`. `self` does not need a type annotation. Printing an object shows its fields unless you define `__str__`. ## Special methods Define methods with the usual Python names to give operators meaning: ```nox class Vec: x: int y: int def __init__(self, x: int, y: int) -> None: self.x = x self.y = y def __add__(self, other: Vec) -> Vec: return Vec(self.x + other.x, self.y + other.y) def __eq__(self, other: Vec) -> bool: return self.x == other.x and self.y == other.y def __str__(self) -> str: return "(" + str(self.x) + ", " + str(self.y) + ")" a: Vec = Vec(1, 2) b: Vec = Vec(3, 4) print(a + b, a == b, a == Vec(1, 2), [a, b]) ``` ```output (4, 6) False True [(1, 2), (3, 4)] ``` ## Inheritance ```nox class Animal: name: str def __init__(self, name: str) -> None: self.name = name def speak(self) -> str: return self.name + " makes a sound" class Dog(Animal): def speak(self) -> str: return self.name + " barks" class Cat(Animal): def speak(self) -> str: return self.name + " meows" pets: list[Animal] = [Animal("generic"), Dog("Rex"), Cat("Tom")] for pet in pets: print(pet.speak()) ``` ```output generic makes a sound Rex barks Tom meows ``` A subclass may use a base-class value wherever the base class is expected; the right `speak` runs. Nox has single inheritance. ## Protocols: structural interfaces A protocol lists the methods something must have. Any class with those methods fits — no declaration needed: ```nox protocol Shape: def area(self) -> float: pass class Square: side: float def __init__(self, side: float) -> None: self.side = side def area(self) -> float: return self.side * self.side class Circle: radius: float def __init__(self, radius: float) -> None: self.radius = radius def area(self) -> float: return 3.14159 * self.radius * self.radius def report(shape: Shape) -> None: print("area:", shape.area()) report(Square(2.0)) report(Circle(1.0)) ``` ```output area: 4.0 area: 3.14159 ``` ## Generics A function or class can work over any type, written with square brackets: ```nox class Box[T]: item: T def __init__(self, item: T) -> None: self.item = item def get(self) -> T: return self.item def first[T](xs: list[T]) -> T: return xs[0] print(Box[int](5).get(), Box[str]("hi").get(), first([10, 20]), first(["a", "b"])) ``` ```output 5 hi 10 a ``` Each use is compiled into a specialised version, so generic code is as fast as hand-written code. ## References, not copies ```nox class Cell: value: int def __init__(self, value: int) -> None: self.value = value a: Cell = Cell(1) b: Cell = a b.value = 99 print(a.value, a == Cell(99)) ``` ```output 99 True ``` Assigning an object copies the reference; both names now see the change. `==` compares fields unless you define `__eq__`. You never free memory yourself — the compiler does it ([Memory](https://noxlang.com/docs/language/memory/)). --- # 7. Errors ## Raising and catching ```nox def parse_age(text: str) -> int: age: int = int(text) if age < 0: raise ValueError("age cannot be negative") return age for text in ["42", "-5", "abc"]: try: print(parse_age(text)) except ValueError as e: print("bad input:", text) ``` ```output 42 bad input: -5 bad input: abc ``` `int("abc")` and the explicit `raise` both produce a `ValueError`, caught by one `except`. Built-in exceptions include `ValueError`, `IndexError`, `KeyError` and `ZeroDivisionError`. ## Your own exceptions ```nox class InsufficientFunds(Exception): needed: int def __init__(self, message: str, needed: int) -> None: super().__init__(message) self.needed = needed def withdraw(balance: int, amount: int) -> int: if amount > balance: raise InsufficientFunds("not enough money", amount - balance) return balance - amount try: print(withdraw(100, 30)) print(withdraw(100, 130)) except InsufficientFunds as e: print(e.message, "- short by", e.needed) ``` ```output 70 not enough money - short by 30 ``` `except Base:` also catches subclasses, so catch the most specific class first. Every exception has `message` and `line` (the line of the `raise`). ## `finally` A `finally` block always runs — after success, after a caught error, and when the function returns early: ```nox def read_config(ok: bool) -> str: try: if not ok: raise ValueError("bad config") return "config loaded" finally: print("cleanup") print(read_config(True)) try: read_config(False) except ValueError as e: print("failed:", e.message) ``` ```output cleanup config loaded cleanup failed: bad config ``` ## `with`: guaranteed cleanup Classes with `__enter__` and `__exit__` work with `with`, which runs `__exit__` however the block ends: ```nox class Connection: name: str def __init__(self, name: str) -> None: self.name = name def __enter__(self) -> Connection: print("open", self.name) return self def __exit__(self) -> None: print("close", self.name) with Connection("db") as conn: print("querying", conn.name) ``` ```output open db querying db close db ``` ## `defer` `defer` schedules a call for when the function exits, last-in first-out — handy for cleanup next to the code that needs it: ```nox def cleanup(what: str) -> None: print("closing", what) def process() -> None: defer cleanup("file") defer cleanup("socket") print("working") process() ``` ```output working closing socket closing file ``` ## When an error is not caught An exception that nobody catches ends the program with exit status 1 and a message naming the exception class and the source line. Errors cost nothing when they do not happen: Nox implements them as ordinary return values, not stack unwinding ([Exceptions](https://noxlang.com/docs/language/exceptions/)). --- # 8. Modules and packages ## Splitting a program into files Every `.nox` file is a module. A project is a directory with a `nox.json`: ```text geometry/ ├── nox.json ├── main.nox ├── mathutil.nox ├── mathutil_test.nox └── shapes/ └── rect.nox ``` ```json { "name": "geometry", "version": "0.1.0", "entry": "main.nox" } ``` `shapes/rect.nox` defines a class, `mathutil.nox` a constant and a function: ```nox-fragment # shapes/rect.nox class Rect: w: int h: int def __init__(self, w: int, h: int) -> None: self.w = w self.h = h def area(self) -> int: return self.w * self.h ``` ```nox-fragment # mathutil.nox SCALE: int = 10 def scaled(n: int) -> int: return n * SCALE ``` `main.nox` imports them: ```nox-fragment # main.nox import mathutil from shapes.rect import Rect from mathutil import SCALE r: Rect = Rect(3, 4) print(r.area(), mathutil.scaled(5), SCALE) ``` ```sh noxc run main.nox ``` ```text 12 50 10 ``` - `import mathutil` loads `mathutil.nox` from the project root; call its functions as `mathutil.scaled(5)`. - `from shapes.rect import Rect` loads `shapes/rect.nox` and brings `Rect` into scope directly. - A module's constants are read with `from mathutil import SCALE`. - All the files compile together into one program, and the statements at the top level of `main.nox` are what runs. ## Using the standard library Standard-library modules live under `nox.`: `import nox.strings`, `from nox.math import sqrt`, `import nox.json`. The full list is the [standard library reference](https://noxlang.com/docs/stdlib/). ```nox import nox.time from nox.math import sqrt, pi print(sqrt(16.0), pi() > 3.14, nox.time.now_ms() > 0) ``` ```output 4.0 True True ``` ## Tests `noxc test` finds every `*_test.nox` file under the current directory and runs it. A test file is an ordinary program that fails (raises) when an expectation is wrong: ```nox-fragment # mathutil_test.nox import nox.test import mathutil nox.test.assert_eq_int(mathutil.scaled(2), 20, "scaled(2)") nox.test.assert_true(mathutil.scaled(0) == 0, "scaled(0)") print("mathutil ok") ``` ```sh noxc test ``` ## Third-party packages Packages are ordinary Nox projects in a Git repository. Add one with `noxc add`, which records it in `nox.json`: ```sh noxc search http # search the central index noxc add nyx # add a package by name (the index knows its repository) noxc fetch # download dependencies; pins exact commits in nox.lock ``` ```json { "name": "geometry", "entry": "main.nox", "requires": [ { "alias": "nyx", "repo": "github.com/mburakmmm/nyx", "ref": "v0.21.0" } ] } ``` ```nox-fragment import nyx.app # module "app" of the package aliased "nyx" ``` `nox.lock` pins every dependency to an exact commit, so builds are reproducible; commit it to your repository. See [Packages](https://noxlang.com/docs/tools/packages/) for the full workflow, including `noxc update`, global installs and publishing your own package. A package that contains `extern def` declarations runs native code — read [Security](https://noxlang.com/docs/reference/security/) before adding dependencies you do not trust. --- # 9. Concurrency Nox runs work in lightweight **tasks**. You start one with `spawn`, wait for its result with `await`, and let tasks talk through typed **channels**. ## Tasks ```nox import nox.time async def fetch_square(n: int) -> int: nox.time.sleep_ms(10) return n * n a: Task[int] = spawn fetch_square(6) b: Task[int] = spawn fetch_square(7) print(await a + await b) ``` ```output 85 ``` `async def` declares a function that can run as a task. `spawn f(x)` starts it and returns immediately with a `Task[int]` (the type is the function's return type); `await task` waits for the result. Both tasks above run at the same time — on the default backend, on different threads of a worker pool. ## Errors travel through `await` ```nox async def risky(n: int) -> int: if n < 0: raise ValueError("negative") return n async def run() -> None: t: Task[int] = spawn risky(-1) try: print(await t) except ValueError as e: print("task failed:", e.message) main_task: Task[None] = spawn run() await main_task ``` ```output task failed: negative ``` ## Channels A `Channel[T](capacity)` is a typed queue between tasks. `await ch.send(v)` waits while the queue is full; `await ch.recv()` waits while it is empty: ```nox async def producer(ch: Channel[int], n: int) -> None: for i in range(n): await ch.send(i * 10) async def consumer(ch: Channel[int], n: int) -> int: total: int = 0 for i in range(n): total += await ch.recv() return total async def run() -> None: ch: Channel[int] = Channel[int](2) p: Task[None] = spawn producer(ch, 5) c: Task[int] = spawn consumer(ch, 5) await p print("sum:", await c) t: Task[None] = spawn run() await t ``` ```output sum: 100 ``` ## Fan-out, fan-in To start many workers and gather their results, hand every worker the same channel: ```nox async def worker(results: Channel[int], n: int) -> None: await results.send(n * n) async def run() -> None: results: Channel[int] = Channel[int](8) for i in range(8): spawn worker(results, i) total: int = 0 for i in range(8): total += await results.recv() print("total:", total) t: Task[None] = spawn run() await t ``` ```output total: 140 ``` `spawn f(x)` on its own line starts a task and discards the handle ("fire and forget"). Results arrive in the order workers finish, not the order they started. ## Cancelling `task.cancel()` asks a task to stop; the task receives `CancelledError` the next time it awaits another task. It is cooperative — a task stuck in pure computation is not interrupted. ## What to remember - Tasks cost very little; start as many as you have concurrent jobs. - Share data between tasks by sending it through channels, not through global variables. - The same program behaves correctly whether tasks run on one thread or many: the default (LLVM) backend runs them in parallel, the QBE backend interleaves them on one thread. Details: [Concurrency](https://noxlang.com/docs/language/concurrency/). --- # 10. A small web service Nox's standard library includes an HTTP server (`nox.http`), a path router (`nox.router`) and a JSON module (`nox.json`). This chapter builds a tiny to-do API with them. ## Hello, HTTP ```nox import nox.http from nox.http import HttpRequest, HttpResponse from nox.router import Router, Context router: Router = Router() def hello(ctx: Context) -> HttpResponse: return HttpResponse(200, "hello from nox\n", {"Content-Type": "text/plain"}) router.get("/", hello) def handle(req: HttpRequest) -> HttpResponse: return router.dispatch(req) nox.http.serve(8080, handle) ``` Run it with `noxc run server.nox` and open `http://localhost:8080/`. `nox.http.serve(port, handler)` accepts connections forever and calls `handler` for each request (an optional third argument caps the number of connections served, `0` meaning unlimited). A `Router` maps method and path to handler functions; `:name` segments capture path parameters. ## Path parameters and JSON ```nox import nox.http import nox.json from nox.http import HttpRequest, HttpResponse from nox.json import JsonWriter from nox.router import Router, Context todos: list[str] = ["write docs", "ship 2.0"] router: Router = Router() def json_response(status: int, body: str) -> HttpResponse: return HttpResponse(status, body, {"Content-Type": "application/json"}) def list_todos(ctx: Context) -> HttpResponse: w: JsonWriter = JsonWriter() w.begin_array() for t in todos: w.write_string(t) w.end_array() return json_response(200, w.build()) def show_todo(ctx: Context) -> HttpResponse: i: int = int(ctx.param("id")) if i < 0 or i >= len(todos): return json_response(404, "{\"error\":\"not found\"}") w: JsonWriter = JsonWriter() w.begin_object() w.write_key("id") w.write_int(i) w.write_key("title") w.write_string(todos[i]) w.end_object() return json_response(200, w.build()) def add_todo(ctx: Context) -> HttpResponse: title: str = ctx.request.body if title == "": return json_response(400, "{\"error\":\"empty body\"}") todos.append(title) return json_response(201, "{\"id\":" + str(len(todos) - 1) + "}") router.get("/todos", list_todos) router.get("/todos/:id", show_todo) router.post("/todos", add_todo) def handle(req: HttpRequest) -> HttpResponse: return router.dispatch(req) nox.http.serve(8080, handle) ``` Try it: ```sh curl localhost:8080/todos # ["write docs","ship 2.0"] curl localhost:8080/todos/1 # {"id":1,"title":"ship 2.0"} curl -X POST -d 'try nox' localhost:8080/todos # {"id":2} ``` Notes: - `ctx.param("id")` returns a path parameter as a `str`; `ctx.request` is the underlying `HttpRequest` (`method`, `target`, `body`, `headers`). - `JsonWriter` builds JSON incrementally and `build()` returns the text. To *parse* JSON use `nox.json.parse` ([JSON](https://noxlang.com/docs/stdlib/json/)). - `todos` is module-level state. `serve` runs a single thread, so it is shared safely; with `serve_multicore` each worker has its own copy, so keep shared state in a database or use `nox.atomic` / `nox.sharedmem`. ## Middleware `Router.use(...)` wraps every handler — for logging, authentication or timing: ```nox import nox.http import nox.time from nox.http import HttpRequest, HttpResponse from nox.router import Router, Context router: Router = Router() def logging(ctx: Context, nxt: (Context) -> HttpResponse) -> HttpResponse: start: int = nox.time.now_ms() resp: HttpResponse = nxt(ctx) print(ctx.request.method, ctx.request.target, resp.status, nox.time.now_ms() - start, "ms") return resp def ping(ctx: Context) -> HttpResponse: return HttpResponse(200, "pong", {"Content-Type": "text/plain"}) router.use(logging) router.get("/ping", ping) def handle(req: HttpRequest) -> HttpResponse: return router.dispatch(req) nox.http.serve(8080, handle) ``` ## Going further - **Scale across cores:** `nox.http.serve_multicore(port, handler, threads, max_connections)` runs a pool of worker threads ([HTTP](https://noxlang.com/docs/stdlib/http/)). - **TLS and WebSockets:** `serve_tls`, `serve_ws` and the `nox.websocket` module. - **Databases:** `nox.sqlite`, `nox.postgres`, `nox.mysql` and the `nox.orm` layer. - **Validation:** `nox.validate` checks request bodies against a schema. - **A framework:** [Nyx](https://github.com/mburakmmm/nyx) is a batteries-included web framework written in Nox — this very website runs on it. --- # 11. Files and JSON Most real programs read something from disk and write something back. This chapter covers text files, directories and JSON — the three things you will reach for first. Everything here lives in two modules: [`nox.fs`](https://noxlang.com/docs/stdlib/fs/) and [`nox.json`](https://noxlang.com/docs/stdlib/json/). ## Reading and writing text A file is read or written as one `str`. `write_string` creates the file or truncates it; `append_string` adds to the end; `read_to_string` returns the whole content: ```nox import nox.fs path: str = "/tmp/nox_tutorial_notes.txt" nox.fs.write_string(path, "first line\nsecond line\n") nox.fs.append_string(path, "third line\n") text: str = nox.fs.read_to_string(path) print(len(text), "bytes") lines: list[str] = text.split("\n") for line in lines: if len(line) > 0: print("-", line) nox.fs.remove_file(path) print(nox.fs.exists(path)) ``` ```output 34 bytes - first line - second line - third line False ``` `split("\n")` leaves an empty string after the final newline, which is why the loop skips empty lines. Paths are plain strings; use [`nox.path`](https://noxlang.com/docs/stdlib/path/) to join and take them apart without worrying about separators. ## When something goes wrong Every file operation that can fail raises `FsError`. Catch it where you can do something useful about it: ```nox import nox.fs from nox.fs import FsError def load(path: str) -> str: try: return nox.fs.read_to_string(path) except FsError as e: print("could not read", path) return "" print(len(load("/tmp/nox_tutorial_definitely_missing.txt"))) ``` ```output could not read /tmp/nox_tutorial_definitely_missing.txt 0 ``` ## Directories `create_dir_all` is `mkdir -p`; `read_dir` returns the *names* of the entries in no particular order, so sort them if the order matters; `remove_dir_all` cleans up: ```nox import nox.fs root: str = "/tmp/nox_tutorial_dir" nox.fs.create_dir_all(root + "/sub/deeper") nox.fs.write_string(root + "/b.txt", "bee") nox.fs.write_string(root + "/a.txt", "ay") for name in sorted(nox.fs.read_dir(root)): kind: str = "file" if nox.fs.is_dir(root + "/" + name): kind = "dir" print(name, kind) nox.fs.remove_dir_all(root) print(nox.fs.exists(root)) ``` ```output a.txt file b.txt file sub dir False ``` > **Untrusted paths.** `nox.fs` hands paths to the operating system unchecked. If a path comes from a user or a network request, confine it to a > directory you choose before you open it (see [Security](https://noxlang.com/docs/reference/security/)). ## Parsing JSON `nox.json.parse` turns text into a tree of `JsonValue` nodes. You ask a node what it is, then read it with a typed accessor — there is no implicit conversion, in keeping with the rest of the language: ```nox import nox.json from nox.json import JsonError text: str = "{\"name\": \"Ada\", \"langs\": [\"nox\", \"python\"], \"age\": 36}" doc: JsonValue = nox.json.parse(text) for i in range(nox.json.object_len(doc)): key: str = nox.json.object_key(doc, i) value: JsonValue = nox.json.object_value(doc, i) if nox.json.is_string(value): print(key, "=", nox.json.as_string(value)) elif nox.json.is_number(value): print(key, "=", int(nox.json.as_number(value))) elif nox.json.is_array(value): print(key, "has", nox.json.array_len(value), "items") try: nox.json.parse("{oops") except JsonError as e: print("invalid JSON") ``` ```output name = Ada langs has 2 items age = 36 invalid JSON ``` Objects keep their keys **in document order**, and there is no lookup by name — you loop over the entries. For small documents that is all you need; for anything you look up often, copy the entries into a `dict[str, str]` once. ## Writing JSON Two styles. `JsonWriter` builds text piece by piece and is the one to use when you produce JSON from your own data: ```nox from nox.json import JsonWriter w: JsonWriter = JsonWriter() w.begin_object() w.write_key("title") w.write_string("Nox tutorial") w.write_key("chapter") w.write_int(11) w.write_key("topics") w.begin_array() w.write_string("files") w.write_string("json") w.end_array() w.end_object() print(w.build()) ``` ```output {"title":"Nox tutorial","chapter":11,"topics":["files","json"]} ``` The other style is to `parse` text and `dump` or `dump_pretty` the tree again — handy for reformatting: ```nox import nox.json doc: JsonValue = nox.json.parse("{\"a\":1,\"b\":[true,null]}") print(nox.json.dump_pretty(doc, 2)) ``` ```output { "a": 1, "b": [ true, null ] } ``` ## Putting it together: a tiny settings file Read a JSON settings file if it exists, fall back to defaults otherwise, and save it back: ```nox import nox.fs import nox.json from nox.fs import FsError from nox.json import JsonWriter, JsonError class Settings: name: str volume: int def __init__(self, name: str, volume: int) -> None: self.name = name self.volume = volume def load_settings(path: str) -> Settings: result: Settings = Settings("default", 5) try: doc: JsonValue = nox.json.parse(nox.fs.read_to_string(path)) for i in range(nox.json.object_len(doc)): key: str = nox.json.object_key(doc, i) value: JsonValue = nox.json.object_value(doc, i) if key == "name" and nox.json.is_string(value): result.name = nox.json.as_string(value) if key == "volume" and nox.json.is_number(value): result.volume = int(nox.json.as_number(value)) except FsError as e: print("no settings file yet") except JsonError as e: print("settings file is damaged") return result def save_settings(path: str, s: Settings) -> None: w: JsonWriter = JsonWriter() w.begin_object() w.write_key("name") w.write_string(s.name) w.write_key("volume") w.write_int(s.volume) w.end_object() nox.fs.write_string_atomic(path, w.build()) path: str = "/tmp/nox_tutorial_settings.json" settings: Settings = load_settings(path) print(settings.name, settings.volume) settings.volume = 9 save_settings(path, settings) again: Settings = load_settings(path) print(again.name, again.volume) nox.fs.remove_file(path) ``` ```output no settings file yet default 5 default 9 ``` `write_string_atomic` writes to a temporary file and renames it over the target, so a crash half-way never leaves a truncated settings file behind. Next: [12. Testing](https://noxlang.com/docs/tutorial/12-testing/). --- # 12. Testing Nox has testing built in. A test is just a program that **fails by raising an exception**; `noxc test` runs every file named `*_test.nox` and reports which ones passed. There is no framework to install and no special syntax to learn. ## A first test Put the code under test in a module and the test next to it, inside a project (a directory with a `nox.json`, as in [chapter 8](https://noxlang.com/docs/tutorial/08-modules-and-packages/); `noxc init` creates one). Suppose `textutil.nox` contains a function that turns a title into a URL slug: ```nox-fragment # textutil.nox def slugify(title: str) -> str: out: str = "" for ch in title.lower(): if ch.isalnum(): out += ch elif len(out) > 0 and out[len(out) - 1] != "-": out += "-" while len(out) > 0 and out[len(out) - 1] == "-": out = out[:len(out) - 1] return out ``` and `textutil_test.nox` checks it with the assertions from [`nox.test`](https://noxlang.com/docs/stdlib/test/): ```nox-fragment # textutil_test.nox import nox.test from textutil import slugify nox.test.assert_eq_str(slugify("Hello, World!"), "hello-world", "punctuation") nox.test.assert_eq_str(slugify(" Nox 2.0 "), "nox-2-0", "spaces and digits") nox.test.assert_eq_str(slugify("!!!"), "", "nothing left") print("slugify ok") ``` Run all tests from the project root, or only those whose file name matches a word: ```sh noxc test noxc test textutil ``` ```text PASSED: /path/to/textutil_test.nox 1 passed, 0 failed (1 total) ``` The exit status is the contract: `0` when every file passes, `1` otherwise — so `noxc test` drops straight into a CI job. ## What a failure looks like An assertion that fails raises an exception that names the check, which is why every assertion takes a message. Here a deliberately wrong expectation is caught so that you can see the message: ```nox import nox.test def double(n: int) -> int: return n * 2 try: nox.test.assert_eq_int(double(2), 5, "double(2)") except Exception as e: print("caught:", e.message) ``` ```output caught: double(2): expected 5, got 4 ``` In a real test file you do not catch it: the exception ends the program with status 1 and `noxc test` marks the file `FAILED`, printing the message. ## Testing that something raises There is no `assert_raises`; a `try`/`except` says the same thing and reads clearly: ```nox import nox.test def parse_port(text: str) -> int: port: int = int(text) if port < 1 or port > 65535: raise ValueError("port out of range") return port nox.test.assert_eq_int(parse_port("8080"), 8080, "valid port") raised: bool = False try: parse_port("70000") except ValueError as e: raised = True nox.test.assert_true(raised, "70000 is rejected") print("both checks passed") ``` ```output both checks passed ``` ## Keep going after a failure: `TestSuite` Assertions stop at the first failure. When you want every check to run — and a report at the end — collect them in a `TestSuite`: ```nox import nox.test from nox.test import TestSuite def clamp(x: int, low: int, high: int) -> int: if x < low: return low if x > high: return high return x suite: TestSuite = TestSuite("clamp") suite.check_eq_int("below", clamp(-5, 0, 10), 0) suite.check_eq_int("inside", clamp(7, 0, 10), 7) suite.check_eq_int("above", clamp(99, 0, 10), 10) suite.check_true("bounds ordered", 0 < 10) print(suite.total_count(), "checks, all passed:", suite.all_passed()) ``` ```output 4 checks, all passed: True ``` `nox.test.write_junit_xml(suite, "test-results.xml")` writes the results in the JUnit format that CI systems display. ## Testing a web handler without a server A handler is an ordinary function from `HttpRequest` to `HttpResponse`, so you can call it directly — no port, no network: ```nox import nox.test from nox.http import HttpRequest, HttpResponse def handle(req: HttpRequest) -> HttpResponse: if req.target == "/health": return HttpResponse(200, "ok", {}) return HttpResponse(404, "not found", {}) ok: HttpResponse = handle(HttpRequest("GET", "/health", "", {}, "")) missing: HttpResponse = handle(HttpRequest("GET", "/nope", "", {}, "")) nox.test.assert_eq_int(ok.status, 200, "health status") nox.test.assert_eq_int(missing.status, 404, "unknown path") print("handler ok") ``` ```output handler ok ``` ## Habits that pay off - **One behaviour per check, with a message** that says what you were testing: `"punctuation"` beats `"test 3"`. - **Test the edges** — empty input, one element, the largest value, the error path — not only the happy case. - **Keep tests independent.** Create files under `/tmp` with a name of your own and delete them at the end, as the previous chapter did. - **Run `noxc test` before every commit.** It is fast because each test file is compiled and run as its own small program. Next: [13. Generics and protocols](https://noxlang.com/docs/tutorial/13-generics-and-protocols/). --- # 13. Generics and protocols Types are mandatory in Nox, which raises a fair question: how do you write a function once that works for `int`, `str` and your own classes? Nox gives you two tools, and both are resolved at compile time — there is no `Any`, no boxing and no run-time cost. This chapter builds up both with small, useful examples; the [language reference](https://noxlang.com/docs/language/protocols-generics/) has every detail. ## A function that works for any type Put the type parameter in square brackets after the name, then use it like any other type. The compiler infers it from the call: ```nox def last[T](xs: list[T]) -> T: return xs[len(xs) - 1] def count_if[T](xs: list[T], keep: (T) -> bool) -> int: n: int = 0 for x in xs: if keep(x): n += 1 return n print(last([10, 20, 30]), last(["a", "b"])) print(count_if([1, 5, 8, 12], lambda v: v > 4)) print(count_if(["fig", "apple", "kiwi"], lambda w: len(w) == 4)) ``` ```output 30 b 3 1 ``` `last` is compiled twice — once for `int`, once for `str` — each a plain direct function. Nothing is decided at run time. ## A container that works for any type A class can take type parameters too. Here is a tiny stack, used with two different element types: ```nox class Stack[T]: items: list[T] def __init__(self) -> None: self.items = [] def push(self, item: T) -> None: self.items.append(item) def pop(self) -> T: return self.items.pop() def is_empty(self) -> bool: return len(self.items) == 0 def balanced(text: str) -> bool: open_stack: Stack[str] = Stack[str]() for ch in text: if ch == "(" or ch == "[": open_stack.push(ch) elif ch == ")" or ch == "]": if open_stack.is_empty(): return False top: str = open_stack.pop() if (top == "(" and ch != ")") or (top == "[" and ch != "]"): return False return open_stack.is_empty() numbers: Stack[int] = Stack[int]() numbers.push(1) numbers.push(2) print(numbers.pop(), numbers.pop(), numbers.is_empty()) print(balanced("(a[b]c)"), balanced("(]"), balanced("((")) ``` ```output 2 1 True True False False ``` `Stack[int]` and `Stack[str]` are separate classes, each with its own compiled methods — and a `Stack[int]` can never receive a string, because the compiler checks every call. ## Shape instead of ancestry: protocols Generics say "any type, same code". A **protocol** says "any type with these methods". It is the Nox answer to Python's duck typing, but checked at compile time: a class satisfies a protocol just by having the methods — it never has to say so. ```nox protocol Scorer: def score(self, word: str) -> int: pass class LengthScorer: def score(self, word: str) -> int: return len(word) class VowelScorer: def score(self, word: str) -> int: n: int = 0 for ch in word: if ch in "aeiou": n += 1 return n def best(words: list[str], scorer: Scorer) -> str: winner: str = words[0] for w in words: if scorer.score(w) > scorer.score(winner): winner = w return winner words: list[str] = ["sky", "banana", "queue", "strengths"] print(best(words, LengthScorer())) print(best(words, VowelScorer())) ``` ```output strengths queue ``` Neither scorer mentions `Scorer`. If you pass a class that lacks `score`, the compiler stops with a message naming the missing method. ## Different classes in one list A protocol can also be the type of a variable, a field or a list element. That is how one list holds objects of *different* classes: ```nox protocol Greeter: def greet(self) -> str: pass class English: def greet(self) -> str: return "hello" class Turkish: def greet(self) -> str: return "merhaba" class Pirate: name: str def __init__(self, name: str) -> None: self.name = name def greet(self) -> str: return "ahoy, " + self.name crowd: list[Greeter] = [English(), Turkish(), Pirate("Nox")] for g in crowd: print(g.greet()) ``` ```output hello merhaba ahoy, Nox ``` ## Which one should I use? | You want… | Use | |---|---| | the same algorithm over many element types | a generic function (`def f[T](...)`) | | a container or wrapper parameterised by what it holds | a generic class (`class Box[T]`) | | to accept "anything that can do X" as an argument | a protocol parameter (`scorer: Scorer`) | | a list of unrelated classes that share behaviour | a list of protocol type (`list[Greeter]`), or a common base class if they are related | The compiler picks the cheapest representation for you: a protocol *parameter* is compiled once per concrete class with direct calls, and only a value *stored* as a protocol carries a small method table. You never write anything different. Next: [14. Databases](https://noxlang.com/docs/tutorial/14-databases/). --- # 14. Databases Nox ships drivers for SQLite, PostgreSQL and MySQL/MariaDB. They share one shape — open a connection, run SQL, read rows — so what you learn with SQLite carries straight over. This chapter uses SQLite because it needs no server: a database is a file (or, for experiments, just memory). ## Open, create, insert ```nox import nox.sqlite from nox.sqlite import Connection db: Connection = nox.sqlite.open(":memory:") db.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, year INTEGER, rating REAL)") db.execute("INSERT INTO books (title, year, rating) VALUES ('Dune', 1965, 4.5)") print("inserted row", db.last_insert_rowid()) print("rows changed", db.changes()) db.close() ``` ```output inserted row 1 rows changed 1 ``` `":memory:"` is a private database that disappears when the connection closes; pass a path such as `"library.db"` and the data stays on disk. `execute` runs a statement and returns the number of rows it changed. ## Never build SQL from user input Joining strings into SQL is how injection bugs happen. Use a **prepared statement**: write `?` where a value goes and bind the value separately. The driver sends it as data, never as SQL, so quotes in the value cannot change the query: ```nox import nox.sqlite from nox.sqlite import Connection from nox.db import Statement db: Connection = nox.sqlite.open(":memory:") db.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, year INTEGER, rating REAL)") insert: Statement = db.prepare("INSERT INTO books (title, year, rating) VALUES (?, ?, ?)") insert.bind_str(0, "Dune") insert.bind_int(1, 1965) insert.bind_float(2, 4.5) insert.execute() tricky: Statement = db.prepare("INSERT INTO books (title, year, rating) VALUES (?, ?, ?)") tricky.bind_str(0, "Robert'); DROP TABLE books;--") tricky.bind_int(1, 2007) tricky.bind_null(2) tricky.execute() count: int = db.query("SELECT COUNT(*) FROM books")[0].get_int(0) print("books still there:", count) db.close() ``` ```output books still there: 2 ``` Placeholders are numbered from **zero** (`bind_str(0, …)` fills the first `?`), and there is a `bind_*` for each type plus `bind_null`. ## Reading rows `query` returns a list of `Row`. Read each column by position with the typed getter that matches it, and ask `is_null` before reading a column that may be `NULL`: ```nox import nox.sqlite from nox.sqlite import Connection from nox.db import Row, Statement db: Connection = nox.sqlite.open(":memory:") db.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, year INTEGER, rating REAL)") db.execute("INSERT INTO books (title, year, rating) VALUES ('Dune', 1965, 4.5)") db.execute("INSERT INTO books (title, year, rating) VALUES ('Neuromancer', 1984, NULL)") db.execute("INSERT INTO books (title, year, rating) VALUES ('Snow Crash', 1992, 4.0)") rows: list[Row] = db.query("SELECT id, title, year, rating FROM books ORDER BY year") for r in rows: rating: str = "unrated" if not r.is_null(3): rating = str(r.get_float(3)) print(r.get_int(0), r.get_str(1), r.get_int(2), rating) newer: Statement = db.prepare("SELECT title FROM books WHERE year > ? ORDER BY title") newer.bind_int(0, 1980) for r in newer.query(): print("after 1980:", r.get_str(0)) db.close() ``` ```output 1 Dune 1965 4.5 2 Neuromancer 1984 unrated 3 Snow Crash 1992 4.0 after 1980: Neuromancer after 1980: Snow Crash ``` ## Errors A syntax error, a constraint violation, a locked database or a missing file raises `SqliteError` with SQLite's own message. Catch it where you can react: ```nox import nox.sqlite from nox.sqlite import Connection, SqliteError db: Connection = nox.sqlite.open(":memory:") db.execute("CREATE TABLE users (name TEXT PRIMARY KEY)") db.execute("INSERT INTO users VALUES ('ada')") try: db.execute("INSERT INTO users VALUES ('ada')") except SqliteError as e: print("duplicate user rejected") db.close() ``` ```output duplicate user rejected ``` ## Transactions Group related writes so they happen together or not at all with plain SQL: ```nox import nox.sqlite from nox.sqlite import Connection, SqliteError def transfer(db: Connection, source: int, target: int, amount: int) -> bool: db.execute("BEGIN") try: db.execute("UPDATE accounts SET balance = balance - " + str(amount) + " WHERE id = " + str(source)) db.execute("UPDATE accounts SET balance = balance + " + str(amount) + " WHERE id = " + str(target)) db.execute("COMMIT") return True except SqliteError as e: db.execute("ROLLBACK") return False db: Connection = nox.sqlite.open(":memory:") db.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER CHECK (balance >= 0))") db.execute("INSERT INTO accounts VALUES (1, 100)") db.execute("INSERT INTO accounts VALUES (2, 0)") print(transfer(db, 1, 2, 30)) print(transfer(db, 1, 2, 500)) for r in db.query("SELECT id, balance FROM accounts ORDER BY id"): print(r.get_int(0), r.get_int(1)) db.close() ``` ```output True False 1 70 2 30 ``` The second transfer would overdraw account 1, the `CHECK` constraint fails, and `ROLLBACK` undoes the first `UPDATE` too. (The amounts here are integers formatted into the SQL, which is safe; for anything that came from outside, bind it instead.) ## PostgreSQL and MySQL The other drivers have the same `execute`, `query` and `prepare`. Only the way you connect differs: ```text import nox.postgres conn: Connection = nox.postgres.open("host=127.0.0.1 port=5432 user=app password=secret dbname=app") import nox.mysql conn: Connection = nox.mysql.open_url("mysql://app:secret@127.0.0.1:3306/app") ``` On a native build the drivers load `libpq` / `libmysqlclient` the first time you connect, so a program that never opens a database needs neither. When you compile to WebAssembly the same modules work through a host-provided network capability instead — see the [WebAssembly guide](https://noxlang.com/docs/tools/wasm/#postgresql). For object mapping on top of these drivers there is [`nox.orm`](https://noxlang.com/docs/stdlib/orm/). Next: [15. Command-line tools](https://noxlang.com/docs/tutorial/15-command-line-tools/). --- # 15. Command-line tools Nox compiles to a single native executable with no runtime to install, which makes it a pleasant language for command-line tools: they start instantly and you can hand the binary to someone else. This chapter builds the pieces every tool needs — arguments, environment variables, input, exit codes and running other programs. ## Arguments and environment `nox.os.arg_count()` counts the command-line arguments **including** the program name at index 0, so the first real argument is `arg(1)`. Environment variables come from `getenv`, which raises `OsError` if the variable is not set: ```nox import nox.os from nox.os import OsError def env_or(name: str, fallback: str) -> str: try: return nox.os.getenv(name) except OsError as e: return fallback print("arguments (including the program name):", nox.os.arg_count()) print(env_or("NOX_TUTORIAL_GREETING", "hello")) nox.os.set_var("NOX_TUTORIAL_GREETING", "salut") print(env_or("NOX_TUTORIAL_GREETING", "hello")) ``` ```output arguments (including the program name): 1 hello salut ``` Run a program with arguments by putting them after `--` for `noxc run`, or simply after the executable name once you have built it: ```sh noxc run greet.nox -- Ada Turing noxc build -o greet greet.nox && ./greet Ada Turing ``` ## Parsing flags by hand There is no argument-parsing framework to learn: a loop over the arguments is usually all you need. Keep the parsing in a function that takes a plain `list[str]` — that way you can test it, as in [chapter 12](https://noxlang.com/docs/tutorial/12-testing/), without launching the program: ```nox class Options: verbose: bool count: int names: list[str] def __init__(self) -> None: self.verbose = False self.count = 1 self.names = [] def parse_options(args: list[str]) -> Options: opts: Options = Options() i: int = 0 while i < len(args): arg: str = args[i] if arg == "-v" or arg == "--verbose": opts.verbose = True elif arg == "-n" or arg == "--count": i += 1 opts.count = int(args[i]) else: opts.names.append(arg) i += 1 return opts opts: Options = parse_options(["-v", "--count", "2", "Ada", "Turing"]) for round in range(opts.count): for name in opts.names: if opts.verbose: print("round", round + 1, "- hello,", name) else: print("hello,", name) ``` ```output round 1 - hello, Ada round 1 - hello, Turing round 2 - hello, Ada round 2 - hello, Turing ``` In the real program you would build the list from `nox.os.arg(1)` up to `arg_count() - 1`. ## Reading input `input()` (no arguments — print your own prompt) reads one line from standard input. It is how an interactive tool talks to the person at the keyboard, and what lets your program sit at the end of a pipe: ```nox-fragment print("Your name?") name: str = input() print("hello,", name) ``` ```sh echo "Ada" | ./greet ``` ## Exit codes and messages A command-line tool communicates success or failure through its **exit status**: `0` is success, anything else is an error that scripts can test. An uncaught exception exits with `1`; to choose the code yourself, call `nox.os.exit`. Send diagnostics to the log or console modules rather than mixing them into your program's real output: ```nox-fragment import nox.os import nox.console def main_logic() -> int: if nox.os.arg_count() < 2: nox.console.error("usage: greet ") return 2 print("hello,", nox.os.arg(1)) return 0 nox.os.exit(main_logic()) ``` `exit` ends the process immediately without running pending `defer`s or `finally` blocks, so close what you opened first. ## Running other programs `nox.process` runs an external program and captures its output. There is no shell involved, so arguments are never re-interpreted — a space or a quote in an argument is just a character: ```nox from nox.process import Command, Output, ProcessError out: Output = Command("echo").arg("two words").arg("and 'quotes'").run() print(out.status, out.stdout.strip()) failing: Output = Command("sh").arg("-c").arg("exit 3").run() print("exit status", failing.status, "success:", failing.success()) try: Command("no-such-program-xyz").run() except ProcessError as e: print("could not start it") ``` ```output 0 two words and 'quotes' exit status 3 success: False could not start it ``` A program that exits non-zero is not an error — inspect `status`. `ProcessError` means it could not be run at all. `set_timeout(ms)` stops a program that hangs. ## Putting it together A complete, tiny tool — `wordcount.nox` — that counts the lines and words in the files named on the command line: ```nox-fragment import nox.os import nox.fs from nox.fs import FsError def count_words(text: str) -> int: n: int = 0 for line in text.split("\n"): for word in line.split(" "): if len(word) > 0: n += 1 return n status: int = 0 for i in range(1, nox.os.arg_count()): path: str = nox.os.arg(i) try: text: str = nox.fs.read_to_string(path) print(len(text.split("\n")) - 1, "lines,", count_words(text), "words:", path) except FsError as e: print("wordcount: cannot read", path) status = 1 nox.os.exit(status) ``` ```sh noxc build -o wordcount wordcount.nox ./wordcount notes.txt missing.txt echo $? ``` Next: [16. WebAssembly and the browser](https://noxlang.com/docs/tutorial/16-webassembly/). --- # 16. WebAssembly and the browser The same Nox program that compiles to a native executable also compiles to **WebAssembly** — a compact binary format that runs in browsers, in Node, and in standalone runtimes such as Wasmtime. The compiler itself runs as WebAssembly too, which is how the [Playground](https://noxlang.com/playground/) can compile your code inside a browser tab with nothing sent to a server. ## Your first `.wasm` Take any program — this one only uses features that work everywhere: ```nox def collatz(n: int) -> int: steps: int = 0 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 steps += 1 return steps for start in [6, 7, 27]: print("collatz(" + str(start) + ") takes", collatz(start), "steps") ``` ```output collatz(6) takes 8 steps collatz(7) takes 16 steps collatz(27) takes 111 steps ``` Build it for WebAssembly instead of your own machine by naming a **target**: ```sh noxc build --target wasm32-wasi collatz.nox -o collatz.wasm wasmtime collatz.wasm # or any other WASI runtime noxc run --target wasm32-wasi collatz.nox # build and run in one step ``` `wasm32-wasi` produces a WASI command, the portable format for command-line programs: any WASI runtime can run it. `noxc run` picks `wasmtime` or `wasmer` if you have one and falls back to Node. Linking WebAssembly needs `zig` on your `PATH`. ## Two flavours | Target | What it is | Use it for | |---|---|---| | `wasm32-wasi` | a WASI command; the file system is whatever the runtime lets the module see | servers-side runtimes, command-line tools, plugins for other programs | | `wasm32-freestanding` | no operating system at all; the module talks to its **host** through a handful of imports | browsers, embedded interpreters, your own host program | On `wasm32-freestanding` the file system is a private, in-memory one that lives inside the module — nothing touches a real disk — which is exactly what you want when you run code you did not write. ## What the host decides A WebAssembly module cannot open a socket, start a process or read your files on its own. Anything beyond computation is a **capability** that whoever runs the module chooses to grant, and all of them are off by default: | Capability | What it enables | How the Node host grants it | |---|---|---| | network | `nox.http` client, WebSocket | `--allow-net` | | processes | `nox.process` | `--allow-process` | | a server | `nox.http.serve` | `--allow-serve` | ```sh noxc run --target wasm32-freestanding-asyncify --allow-net fetch_example.nox ``` You can tighten it further — for example, `--net-allow=api.example.com:443` lets the program reach one server and nothing else. If you are *compiling* code you do not trust, ban a capability before it even builds: ```sh noxc build --target wasm32-freestanding --deny-capability network,process,fs prog.nox -o prog.wasm ``` A program that then imports `nox.http` is rejected with a clear message instead of failing later. The [WebAssembly guide](https://noxlang.com/docs/tools/wasm/) lists every capability and limit. ## Tasks, fibers and threads By default `spawn` and `await` work on WebAssembly through a simple nested-run scheme, which is fine for most programs but cannot untangle every pattern. Two flags give you the real thing: - `--asyncify` — real fibers on a single thread, so channels and `await` behave exactly like the native scheduler (this also unlocks the network and server capabilities, which have to *pause* a task while the host does I/O); - `--threads` — real parallelism across worker threads. ## Running in a browser page A page needs a `wasm32-freestanding` module (`noxc build --target wasm32-freestanding collatz.nox -o collatz.wasm`), a few lines of JavaScript, and `wasm_host.mjs` (it is in the `compiler/` directory of the repository and in the `nox-web-compiler` bundle attached to each release): ```js import { runNox } from './wasm_host.mjs'; const bytes = await (await fetch('collatz.wasm')).arrayBuffer(); await runNox(bytes, { write: (fd, chunk) => { console.log(new TextDecoder().decode(chunk)); return chunk.length; }, read: () => 0, clockMs: (kind) => (kind === 0 ? Date.now() : performance.now()), randomFill: (bytes) => crypto.getRandomValues(bytes), sleepMs: () => {}, }); ``` The host is a plain object with five functions — that is the entire surface a module sees. ## Compile in the browser, too Because the compiler is WebAssembly as well, a page can accept Nox source, compile it and run the result locally. That is exactly what the [Playground](https://noxlang.com/playground/) does: open it, pick an example, edit, press Ctrl+Enter. The first run downloads the compiler (about 25 MB, cached afterwards); every later run compiles in a fraction of a second. The pieces are documented in [The Nox compiler in the browser](https://noxlang.com/docs/tools/browser-compiler/) if you want to embed them in your own page — a docs site with runnable examples, for instance. Next: [17. Publishing a package](https://noxlang.com/docs/tutorial/17-publishing/). --- # 17. Publishing a package A Nox package is just a Git repository with a `nox.json`. There is no build server and no upload step: the **noxpkg** registry keeps a small index — name, repository, description, tags — and `noxc` fetches the code straight from your repository. Sharing something takes five minutes. ## 1. Make it a package Create a project and give it something worth importing. Here is a tiny library, `textkit`, with one useful function: ```sh noxc init textkit cd textkit ``` ```nox-fragment # textkit.nox def title_case(text: str) -> str: words: list[str] = text.split(" ") out: list[str] = [] for w in words: if len(w) > 0: out.append(w[0].upper() + w[1:].lower()) return " ".join(out) ``` Package code is imported by the **alias** its users choose, followed by the module name: after `noxc add textkit`, a user writes `import textkit.textkit` (alias `textkit`, module `textkit`). Keep one module per file and give the public ones clear names. Edit `nox.json` so the metadata is honest: ```json { "name": "textkit", "version": "0.1.0", "entry": "main.nox" } ``` ## 2. Test it A library with no tests is a promise without evidence. Add `textkit_test.nox` as in [chapter 12](https://noxlang.com/docs/tutorial/12-testing/) and run: ```sh noxc test ``` ## 3. Push it to Git ```sh git init && git add -A && git commit -m "textkit 0.1.0" git tag v0.1.0 git remote add origin git@github.com:you/textkit.git git push origin main --tags ``` Tags are how your users will pin a version: `noxc add textkit --ref v0.1.0`. Pick a tag for every release you want people to be able to rely on. ## 4. Sign in and publish You need an account on the registry, and it uses your GitHub identity — no new password. Sign in once: ```sh noxc login ``` `noxc` shows a short code, opens GitHub's device page in your browser and waits while you approve. The registry sees only your public GitHub profile, and your GitHub credentials never reach `noxc`. A token for the registry is saved in `~/.nox/credentials`, readable only by you. Then announce the package: ```sh noxc publish github.com/you/textkit --ref v0.1.0 --description "Small text helpers" --tags text,strings ``` ```text submitted: textkit (id=…) as @you — awaiting approval ``` ## What happens next - The **name belongs to you** from this moment — nobody else can publish `textkit`. - A new package is **reviewed by an administrator** before it appears in the index. Approval means "the metadata looks legitimate", not "the code is safe". - When you publish a new version of a package you already own — same name, same repository — it goes **live straight away**; you see `published` instead of `submitted`. Sending the same submission twice never creates a second queue entry. - Moving the package to a different repository goes through review again. Once it is listed, anyone can find and add it: ```sh noxc search text noxc add textkit ``` ## Good citizenship - **Pin and lock.** Users pin your tags; you pin yours. Commit `nox.lock`. - **Say what your code can do.** If it uses `extern def`, spawns processes or touches the network, say so in the description — a dependency runs with the full authority of the program that imports it ([Security](https://noxlang.com/docs/reference/security/)). - **Keep the API small and the changes honest.** Follow semantic versioning — a breaking change gets a new major version ([Nox's own policy](https://noxlang.com/docs/reference/versioning/) is a good model). - **Sign your commits** if you can; dependants can then require it with `"require_signed_commit": true`. Full details are in [Packages and dependencies](https://noxlang.com/docs/tools/packages/) and [noxpkg](https://noxlang.com/docs/tools/noxpkg/). Next: [18. Next steps](https://noxlang.com/docs/tutorial/18-next-steps/). --- # 18. Next steps You now know the shape of Nox: static types with Python's syntax, functions and classes, collections, errors, modules, tasks and a web server. Where to go from here depends on what you want to build. ## Read the reference - The [language reference](https://noxlang.com/docs/language/) is complete and precise: numbers and overflow, strings and formatting, classes and protocols, generics, exceptions, concurrency and memory. - The [standard library reference](https://noxlang.com/docs/stdlib/) documents every module and function. - [Differences from Python](https://noxlang.com/docs/language/python-differences/) is the quick checklist if you are porting code. ## Build something - **Command-line tools:** `nox.os` (arguments, environment), `nox.fs`, `nox.path`, `nox.process`, `nox.console`, `nox.log`. - **Web services:** `nox.http`, `nox.router`, `nox.json`, `nox.validate`, `nox.template`, databases, and the Nyx framework. - **Data processing:** `nox.collections`, `nox.regex`, `nox.csv`, `nox.yaml`, `nox.toml`, `nox.binary`. - **Systems work:** fixed-width integers, `ptr[T]`, `lowlevel`, [freestanding builds](https://noxlang.com/docs/tools/freestanding/) for kernels, and [`extern def`](https://noxlang.com/docs/language/ffi/) to call C. ## Extend Nox itself Nox has three stable ways to connect with the outside world, described in [The three APIs](https://noxlang.com/docs/apis/): - the **Nox API** — what library and framework authors can rely on in Nox source code; - the **Nox Native Interface** — a C ABI for native extensions in C, C++, Rust or Zig; - the **Plugin API** — manifests, versioning and capability consent on top of NNI. ## Tools [`noxc`](https://noxlang.com/docs/tools/noxc/) does everything: `check`, `build`, `run`, `test`, `fmt`, `init`, `add`, `fetch`, `publish`, `upgrade`. There is an LSP server and editor support ([Editors](https://noxlang.com/docs/install/editors/)), and a package registry at [noxpkg](https://noxlang.com/docs/tools/noxpkg/). ## Get involved The compiler and runtime are written in Zig and open source. [Contributing](https://noxlang.com/docs/internals/contributing/) explains the layout, the test suites and how a change reaches a release; [Architecture](https://noxlang.com/docs/internals/architecture/) describes how the compiler works. --- # Recipes Short, complete answers to questions that come up all the time. Every program here compiles, and every output block is what it prints. They deliberately use only a few lines of the standard library each, so you can paste one into the [Playground](https://noxlang.com/playground/) and change it. ## Count how often each word appears ```nox text: str = "the quick brown fox jumps over the lazy dog the end" counts: dict[str, int] = {} for word in text.split(" "): if word in counts: counts[word] += 1 else: counts[word] = 1 pairs: list[tuple[str, int]] = [] for word in counts: pairs.append((word, counts[word])) ranked: list[tuple[str, int]] = sorted(pairs, key=lambda p: -p[1]) print(ranked[0]) print(len(counts), "distinct words") ``` ```output ('the', 3) 9 distinct words ``` ## Remove duplicates but keep the order A `set` remembers what you have seen; the list keeps the order: ```nox def unique(xs: list[int]) -> list[int]: seen: set[int] = set() out: list[int] = [] for x in xs: if x not in seen: seen.add(x) out.append(x) return out print(unique([3, 1, 3, 2, 1, 4, 2])) ``` ```output [3, 1, 2, 4] ``` ## Group records by a key ```nox class Sale: region: str amount: int def __init__(self, region: str, amount: int) -> None: self.region = region self.amount = amount sales: list[Sale] = [Sale("north", 120), Sale("south", 80), Sale("north", 45), Sale("east", 60), Sale("south", 20)] totals: dict[str, int] = {} for s in sales: if s.region in totals: totals[s.region] += s.amount else: totals[s.region] = s.amount for region in sorted(list(totals.keys())): print(region, totals[region]) ``` ```output east 60 north 165 south 100 ``` ## Print a neat table f-strings take the full format mini-language — width, alignment, precision: ```nox rows: list[tuple[str, int, float]] = [("apples", 12, 0.5), ("watermelons", 3, 4.25), ("figs", 140, 0.125)] print(f"{'item':<12}{'qty':>5}{'price':>8}") for name, qty, price in rows: print(f"{name:<12}{qty:>5}{price:>8.2f}") ``` ```output item qty price apples 12 0.50 watermelons 3 4.25 figs 140 0.12 ``` (`0.125` prints as `0.12`: formatting rounds half to even, like Python.) ## Memoise an expensive function A dictionary makes an exponential recursion linear: ```nox memo: dict[int, int] = {} def fib(n: int) -> int: if n < 2: return n if n in memo: return memo[n] value: int = fib(n - 1) + fib(n - 2) memo[n] = value return value print(fib(50), fib(80)) ``` ```output 12586269025 23416728348467685 ``` ## Retry something that might fail ```nox class Flaky(Exception): pass def unreliable(attempt: int) -> str: if attempt < 3: raise Flaky("not yet") return "ok" def call_with_retry(limit: int) -> str: for attempt in range(1, limit + 1): try: return "succeeded on try " + str(attempt) + ": " + unreliable(attempt) except Flaky as e: print("try", attempt, "failed:", e.message) return "gave up" print(call_with_retry(5)) print(call_with_retry(2)) ``` ```output try 1 failed: not yet try 2 failed: not yet succeeded on try 3: ok try 1 failed: not yet try 2 failed: not yet gave up ``` ## Time a piece of code ```nox import nox.time start: int = nox.time.now_ms() total: int = 0 for i in range(2000000): total += i % 7 elapsed: int = nox.time.now_ms() - start print("sum", total) print("finished quickly:", elapsed < 1000) ``` ```output sum 5999995 finished quickly: True ``` Print the elapsed time itself when you are measuring — it is left out of the output above only because it differs from one machine to the next. ## Read a CSV-like text For real CSV with quoting, use [`nox.csv`](https://noxlang.com/docs/stdlib/csv/); for simple comma-separated lines `split` is enough: ```nox data: str = "name,age,city\nAda,36,London\nAlan,41,Wilmslow\nGrace,85,New York" lines: list[str] = data.split("\n") header: list[str] = lines[0].split(",") print(header) total_age: int = 0 for line in lines[1:]: cells: list[str] = line.split(",") total_age += int(cells[1]) print(cells[0], "lives in", cells[2]) print("average age", total_age // (len(lines) - 1)) ``` ```output ['name', 'age', 'city'] Ada lives in London Alan lives in Wilmslow Grace lives in New York average age 54 ``` ## A state machine with an enum-like class ```nox class Light: state: str def __init__(self) -> None: self.state = "red" def next(self) -> None: if self.state == "red": self.state = "green" elif self.state == "green": self.state = "yellow" else: self.state = "red" light: Light = Light() for step in range(5): print(step, light.state) light.next() ``` ```output 0 red 1 green 2 yellow 3 red 4 green ``` ## Run many things at once `spawn` starts a task and the work runs on whatever core is free. Tasks cannot be stored in a list, so collect the results through a channel — each worker sends its answer, and the main task receives exactly as many as it started: ```nox async def square_sum(n: int, results: Channel[int]) -> None: total: int = 0 for i in range(n): total += i * i await results.send(total) async def main_task() -> None: results: Channel[int] = Channel[int](3) for n in [10, 100, 1000]: spawn square_sum(n, results) sums: list[int] = [] for k in range(3): sums.append(await results.recv()) print(sorted(sums)) t: Task[None] = spawn main_task() await t ``` ```output [285, 328350, 332833500] ``` Results arrive in whatever order the workers finish, which is why the program sorts them before printing. --- # The Nox language reference This part of the documentation describes the Nox language *as it is in 2.0*: its syntax, its static semantics and its runtime behaviour. It is a reference, not a tutorial — if you are new, start with the [tutorial](https://noxlang.com/docs/tutorial/). Nox is a **statically typed, ahead-of-time compiled** language with Python-like syntax. There is no interpreter and no garbage collector. A program is type-checked as a whole, lowered to one typed intermediate representation and handed to a backend (LLVM by default, QBE as an alternative — see [Backends](https://noxlang.com/docs/tools/backends/)) that links it statically with a small runtime written in Zig. ## How to read this reference Each page covers one area and states rules in the same shape: what the construct is, how it is written, what the compiler checks, and what happens at run time. Every complete `nox` code block in these pages is compiled — and, when an `output` block follows it, executed and compared — by the documentation test (`scripts/check_docs.py`), so the examples are current. | Page | What it defines | |---|---| | [Lexical structure](https://noxlang.com/docs/language/lexical/) | Lines, indentation, tokens, literals, comments, keywords | | [Types](https://noxlang.com/docs/language/types/) | The type system: scalars, collections, optionals, function and generic types | | [Numbers](https://noxlang.com/docs/language/numbers/) | Integer and floating-point semantics, overflow, division, conversions | | [Strings](https://noxlang.com/docs/language/strings/) | `str` semantics, methods, f-strings and the format mini-language | | [Expressions](https://noxlang.com/docs/language/expressions/) | Operators, precedence, comparisons, slicing, comprehensions, lambdas | | [Statements](https://noxlang.com/docs/language/statements/) | Assignment, control flow, `assert`, `del`, scoping | | [Functions](https://noxlang.com/docs/language/functions/) | Parameters, defaults, keyword arguments, closures, first-class functions | | [Classes](https://noxlang.com/docs/language/classes/) | Fields, methods, special methods, inheritance and mixins | | [Enums and `match`](https://noxlang.com/docs/language/enums/) | Variants that carry data (tagged unions), `match`, exhaustiveness checking | | [Protocols and generics](https://noxlang.com/docs/language/protocols-generics/) | Structural protocols, generic functions/classes/methods | | [Exceptions](https://noxlang.com/docs/language/exceptions/) | `raise`/`try`/`except`/`finally`, `with`, `defer`, the error model | | [Concurrency](https://noxlang.com/docs/language/concurrency/) | `async`/`spawn`/`await`, tasks, channels, threads, the scheduler | | [Memory](https://noxlang.com/docs/language/memory/) | What the compiler does for you; `lowlevel` | | [Modules](https://noxlang.com/docs/language/modules/) | `import`, packages, entry point, module-level state | | [Decorators and reflection](https://noxlang.com/docs/language/decorators/) | Metadata decorators and `nox.reflect` | | [Foreign functions](https://noxlang.com/docs/language/ffi/) | `extern def`, `ptr`, callbacks, the trust boundary | | [Built-in functions](https://noxlang.com/docs/language/builtins/) | The prelude: everything available without an import | | [Grammar](https://noxlang.com/docs/language/grammar/) | A compact grammar of the whole language | | [Differences from Python](https://noxlang.com/docs/language/python-differences/) | What Python code needs to change to be Nox code | ## Design principles Four rules shape every part of the language, and knowing them makes the rest predictable: 1. **Types are mandatory and static.** Every variable, parameter and return value has a type; there is no `Any`, no implicit dynamic fallback, and `lowlevel` code is type-checked exactly like everything else. 2. **Ownership is invisible.** There are no ownership keywords, borrow markers or lifetimes. The compiler picks the cheapest safe memory strategy automatically ([Memory](https://noxlang.com/docs/language/memory/)). 3. **Errors are values on the return path.** Exceptions are ordinary classes propagated through an implicit error-return chain — no stack unwinding, no landing pads ([Exceptions](https://noxlang.com/docs/language/exceptions/)). 4. **One program, one compilation unit.** All modules of a program compile together, so there is no separate-compilation ABI to worry about inside a program ([Modules](https://noxlang.com/docs/language/modules/)). ## A first look ```nox class Counter: count: int def __init__(self, start: int) -> None: self.count = start def bump(self) -> int: self.count += 1 return self.count def total(xs: list[int]) -> int: t: int = 0 for x in xs: t += x return t c: Counter = Counter(10) c.bump() print(c.bump(), total([1, 2, 3])) ``` ```output 12 6 ``` --- # Lexical structure A Nox source file is UTF-8 text with the extension `.nox`. The lexer turns it into a stream of tokens; indentation produces explicit `INDENT`/`DEDENT` tokens exactly as in Python. ## Lines and indentation A *logical line* normally ends at the end of a physical line. A logical line continues onto the next physical line when: - it ends with a backslash `\`, or - an opening bracket `(`, `[` or `{` has not been closed yet. ```nox total: int = 1 + \ 2 values: list[int] = [ 10, 20, 30, ] print(total, values) ``` ```output 3 [10, 20, 30] ``` Blocks are formed by indentation. The body of a `def`, `class`, `if`, `elif`, `else`, `while`, `for`, `try`, `except`, `finally`, `with` or `lowlevel` statement is an indented block on the following lines. Rules: - Indent with **spaces**. A tab in the indentation is a syntax error ("indentation with tab; use spaces"). - All lines of one block must use the same indentation; a dedent must return to the indentation of an enclosing block, or the compiler reports *inconsistent indentation*. - Blank lines and comment-only lines are ignored for indentation purposes. - A compound statement's body may **not** be written on the same line (`if x: print(x)` is a syntax error) — there are no one-line compound statements, and there are no semicolons: one statement per logical line. ## Comments and docstrings A comment starts with `#` and runs to the end of the line. A comment may follow code on the same line. A triple-quoted string (`"""..."""` or `'''...'''`) that is the first statement of a class body is the class's *docstring*; the formatter and `nox.reflect` keep it. In any other position a triple-quoted string is just a multi-line `str` literal (and a bare string expression statement is allowed and ignored). ```nox class Point: """A point on the plane.""" x: int y: int def __init__(self, x: int, y: int) -> None: self.x = x self.y = y p: Point = Point(3, 4) # trailing comment print(p.x + p.y) ``` ```output 7 ``` ## Identifiers An identifier is a letter or `_` followed by letters, digits or `_`. Letters are Unicode letters in the XID_Start/XID_Continue sense (as in Python): `größe`, `Öğrenci` and `名前` are valid names. Identifiers are compared by code point (there is no NFKC normalization) and are case sensitive. ```nox größe: int = 3 名前: str = "x" print(größe, 名前) ``` ```output 3 x ``` A leading double underscore names a *special method* when used as a method name (`__init__`, `__add__`, …; see [Classes](https://noxlang.com/docs/language/classes/)). Names beginning with `__nox_` are reserved for the compiler's prelude and are not part of the language surface. ### Reserved words The following words are keywords and cannot be used as identifiers: ```text and as async await break class continue def defer del elif else except extern False finally for from if import in is lambda lowlevel None not or pass protocol raise retains return spawn True try while with with_rt ``` `assert` is a *soft* keyword: it starts an assertion only when it begins a statement and is followed by an expression. `self` is an ordinary name, conventionally the first parameter of a method. A top-level function may not be called `main` (the compiler synthesises the program entry point under that name). ## Literals ### Integers Decimal (`42`, `1_000_000`), hexadecimal (`0xFF`), binary (`0b1010`) and octal (`0o17`) literals. Underscores may separate digits. A literal has type `int`; it converts to a fixed-width integer type where one is expected and the value fits (see [Numbers](https://noxlang.com/docs/language/numbers/)). `noxc fmt` rewrites non-decimal literals as decimal. ```nox print(255 == 0xFF, 0b101, 0o17, 9_000) ``` ```output True 5 15 9000 ``` ### Floating-point numbers `3.14`, `1e-3`, `2.5E+10`, `1_0.5`. An exponent always makes the literal a `float`. See [Numbers](https://noxlang.com/docs/language/numbers/) for how floats are printed. ### Booleans and `None` `True`, `False` (type `bool`) and `None`. ### Strings String literals use single quotes, double quotes, or triple quotes (which may span lines). The escape sequences are: | Escape | Meaning | |---|---| | `\n`, `\t`, `\r` | newline, tab, carriage return | | `\\`, `\"`, `\'` | backslash, double quote, single quote | | `\xHH` | the ASCII character `00`–`7F` (two hex digits; `\x80`–`\xFF` is an error because a `str` holds valid UTF-8) | | `\uXXXX`, `\UXXXXXXXX` | the code point U+XXXX / U+XXXXXXXX (exactly four / eight hex digits; surrogates and values above 10FFFF are errors) | An unrecognised escape keeps the character after the backslash (`"\q"` is `"q"`). There are no raw strings, and adjacent literals are not concatenated implicitly — write `"a" + "b"`. Prefixing a literal with `f` makes an *f-string* (see [Strings](https://noxlang.com/docs/language/strings/#f-strings)). ```nox print("tab:\there", 'quote: \'', "café") print("""first second""") ``` ```output tab: here quote: ' café first second ``` ## Operators and delimiters ```text + - * / // % ** arithmetic & | ^ ~ << >> bitwise == != < <= > >= comparison = := += -= *= /= //= %= **= &= |= ^= <<= >>= assignment ( ) [ ] { } , : . -> delimiters ``` See [Expressions](https://noxlang.com/docs/language/expressions/) for precedence and [Statements](https://noxlang.com/docs/language/statements/) for assignment forms. --- # Types Every Nox value has a static type known at compile time. Types are written in annotations and are **mandatory** on variable declarations, parameters and return values. There is no `Any` and no implicit dynamic fallback — not even inside [`lowlevel`](https://noxlang.com/docs/language/memory/#lowlevel-blocks) blocks. ## Declaring variables A name is introduced by its first assignment, which must carry the type: ```nox count: int = 0 name: str = "nox" ratio: float = 0.5 ready: bool = True count = count + 1 # later assignments omit the annotation print(count, name, ratio, ready) ``` ```output 1 nox 0.5 True ``` ### Inferred local declarations (`:=`) Inside a function or method you may leave the type off and let the compiler take it from the value with `name := expression`. The result is exactly the same as writing the type yourself — the type is still static and fixed for the scope: ```nox def total(xs: list[int]) -> int: n := len(xs) # int scale := 1.5 # float label := f"{n} items" # str s := 0 for x in xs: s = s + x print(label, scale * s) return s total([1, 2, 3]) ``` ```output 3 items 9.0 ``` Rules: `:=` is for function and method locals only (module-level names, class fields and parameters still carry their type). The right-hand side must carry its own type, so `x := None`, `xs := []` and `d := {}` are errors — write `xs: list[int] = []` there. A call that returns `None` cannot be assigned. `x := find(k)` gives the optional type `T | None` and must be narrowed before use. A variable captured by `nonlocal` needs an explicit type on its first declaration. Style rule of thumb: use `:=` when the right-hand side already shows the type (`Node(...)`, `len(xs)`, a literal) and write the annotation when it does not. Assigning a value of the wrong type is a compile error. Re-declaring a name in the same scope with a *different* type is a compile error too (this includes reusing a loop variable name for loops over different element types). The one implicit conversion is `int → float` on assignment and in mixed arithmetic. ## Type aliases `type Name = ` gives a type a second name. It is a module-level statement; every use of the alias is replaced by the type it stands for before type checking, so an alias and its target are the same type: ```nox type Scores = dict[str, list[int]] type Id = int def best(s: Scores, who: str) -> Id: top: Id = 0 for v in s[who]: if v > top: top = v return top print(best({"ann": [3, 9, 4]}, "ann")) ``` ```output 9 ``` Aliases are **module scoped**. An alias defined in an imported module is reached as `module.Name` (also through `import module as m`) or with `from module import Name`, and two modules may define aliases of the same name without clashing. If the module has an `__all__` list, an alias that is not listed there cannot be used from outside. Aliases may refer to each other in a chain of any length; a real cycle (`type A = list[A]`, or `A` → `B` → `A`) is an error that names the chain. Aliases may refer to one another (a cycle is an error), may be used before their definition, and cannot share a name with a class or function. Generic aliases (`type Pair[T] = …`) and aliases inside functions are not supported, and an alias is not exported from its module (import the target type instead). ## The scalar types | Type | Values | Notes | |---|---|---| | `int` | signed 64-bit integer | wraps on overflow ([Numbers](https://noxlang.com/docs/language/numbers/)) | | `float` | IEEE-754 double | printed like Python's `repr` | | `bool` | `True`, `False` | never converts to or from `int` implicitly | | `str` | immutable UTF-8 text | indexed by code point ([Strings](https://noxlang.com/docs/language/strings/)) | | `None` | the single value `None` | the type of "no value"; also the return type of procedures | ### Fixed-width integers For byte-level work, binary formats and `lowlevel` code there are ten more integer types: `i8 i16 i32 i64 isize` and `u8 u16 u32 u64 usize`. They never mix implicitly — with each other, with `int` or with `float`. Convert explicitly with the type name used as a function: `u8(200)`, `int(b)`. **Overflow of `+`, `-` and `*` on a fixed-width integer terminates the program** with a message, identically on both backends; plain `int` wraps. `list[u8]` and friends are stored byte-packed. ```nox b: u8 = u8(200) c: u8 = u8(55) print(int(b) + int(c), b + c) ``` ```output 255 255 ``` ## Collection types | Type | Written as | Literal | |---|---|---| | list | `list[T]` | `[1, 2, 3]` | | dictionary | `dict[K, V]` | `{"a": 1}` | | set | `set[T]` | `{1, 2, 3}` (and `set()` for the empty set) | | tuple | `tuple[A, B, ...]` | `(1, "x")` | - A `list[T]` is a growable array; elements may be of any single type, including other lists and classes. - A `dict[K, V]` keeps **insertion order**. Keys are `int`, `float`, `bool` or `str`; values are `int`, `float`, `bool`, `str`, a class, a `list[T]` or a `dict`. - A `set[T]` holds unique elements of type `int`, `float`, `bool` or `str` and iterates in insertion order. - A tuple is an immutable value with a fixed number of elements of possibly different types; it cannot be a dictionary key and cannot be iterated. The empty literals `[]` and `{}` take their type from the surrounding context (an annotated declaration, a parameter, a return type): ```nox names: list[str] = [] table: dict[str, int] = {} names.append("ada") table["ada"] = 1 pair: tuple[str, int] = ("ada", 1) unique: set[int] = {3, 1, 3} print(names, table, pair, len(unique)) ``` ```output ['ada'] {'ada': 1} ('ada', 1) 2 ``` The same holds for empty literals nested inside a literal whose type is known: `grid: list[list[int]] = [[], [1, 2]]` and `index: dict[str, list[int]] = {"a": []}` are accepted. The type also flows into these places: - assignment to an optional variable: `found: list[str] | None = None` then `found = []`; - the element of a comprehension whose result type is known: `rows: list[list[int]] = [[] for i in range(3)]`, `table: dict[str, list[int]] = {k: [] for k in keys}`; - the argument of `append`, `insert` and `extend` on a typed list: `grid.append([])`; - the right operand of `+` / `+=` on lists: `grid += [[]]`; - both branches of a conditional expression: `r: list[int] = [] if empty else [1]`; - the default of `get`: `table.get("k", [])`. An empty literal with no surrounding type (`len([])`) is still an error: declare the type first. See [Expressions](https://noxlang.com/docs/language/expressions/) and [Built-in functions](https://noxlang.com/docs/language/builtins/) for the operations on collections. ## Class and protocol types Every `class` declares a type of the same name; every `protocol` declares a structural interface type (see [Classes](https://noxlang.com/docs/language/classes/) and [Protocols and generics](https://noxlang.com/docs/language/protocols-generics/)). Class instances are reference values: assigning one to another variable shares the object. ## Optional types `T | None` means "a `T` or `None`". It is available for `str`, `list`, `dict`, classes and the scalar types: ```nox def first_word(text: str) -> str | None: if text == "": return None return text.split(" ")[0] w: str | None = first_word("hello world") if w is not None: print(w.upper()) ``` ```output HELLO ``` Use `x is None` / `x is not None` (or `== None` / `!= None`) to test. After such a test the optional is **narrowed** to `T` inside the matching branch, through `and`/`or`/`not`, and after a guard whose branch always exits: ```nox def length_or_zero(s: str | None) -> int: if s is None: return 0 return len(s) print(length_or_zero(None), length_or_zero("abc")) ``` ```output 0 3 ``` A field can be narrowed too, as long as the optional holds a class, list, dict or `str` (`n.next != None`, `a.b.c is None`): inside the branch (and after a guard that exits) `n.next` is a plain `T`. The narrowing is dropped as soon as the compiler can no longer prove it: an assignment to the field or to any name on its path (`n.next = x`, `n = other`), a call to your own function or method (it might clear the field), or an `await`. Scalar optionals (`int | None`) are not narrowed through a field; copy the field into a local first. Using an un-narrowed optional where a plain `T` is needed is a compile error. `print(x)` shows `None` or the value; `str(x)` and f-strings need a narrowed value. A scalar optional (`int | None`) is boxed internally — this is invisible to the program. ## Function types A function type is written `(P1, P2) -> R`. Top-level functions, nested functions, lambdas and bound closures are values of function type and can be stored, passed and returned ([Functions](https://noxlang.com/docs/language/functions/)): ```nox def apply(f: (int) -> int, x: int) -> int: return f(x) def double(n: int) -> int: return n * 2 print(apply(double, 21), apply(lambda n: n + 1, 41)) ``` ```output 42 42 ``` ## Generic types User code can declare generic functions, methods and classes with type parameters in square brackets (`def first[T](xs: list[T]) -> T`, `class Box[T]`). Each use is specialised at compile time (monomorphisation); nothing is boxed or erased. The built-in generic types are `Task[T]`, `Channel[T]`, `ThreadHandle[T]` and `ThreadChannel[T]` ([Concurrency](https://noxlang.com/docs/language/concurrency/)), and `ptr[T]` ([Foreign functions](https://noxlang.com/docs/language/ffi/)). See [Protocols and generics](https://noxlang.com/docs/language/protocols-generics/). ## Pointers `ptr` is an opaque machine pointer and `ptr[T]` a typed one; they exist for foreign-function interfaces and `lowlevel` code and are covered in [Foreign functions](https://noxlang.com/docs/language/ffi/). Ordinary Nox code never needs them. ## Type compatibility summary - Types are **nominal** for classes and **structural** for protocols. - There is no subtyping among the built-in types; `int` and `float` mix in arithmetic (result `float`), everything else is an explicit conversion: `float(x)`, `int(x)`, `str(x)`, `bool(x)`, `list(x)`. - A subclass instance can be used where its base class is expected (single inheritance). - Two function types are compatible when their parameter and return types are identical. --- # Numbers Nox has three numeric families: the 64-bit signed integer `int`, the IEEE-754 double `float`, and the ten fixed-width integer types. `bool` is a separate type and never behaves as a number. ## `int` `int` is a signed 64-bit two's-complement integer. Arithmetic on plain `int` **wraps around** on overflow, identically on both backends: ```nox big: int = 9223372036854775807 print(big + 1) print(3 ** 40) ``` ```output -9223372036854775808 -6289078614652622815 ``` To wrap deliberately at another width, compute in `int` and mask: `(x * 31 + c) & 0xFFFFFFFF`. ### Arithmetic operators | Operator | Meaning | Result type | |---|---|---| | `a + b`, `a - b`, `a * b` | addition, subtraction, multiplication | `int` (or `float` if either side is `float`) | | `a / b` | true division | **always `float`** | | `a // b` | floor division (rounds toward −∞) | `int` / `float` | | `a % b` | remainder with the **sign of the divisor** | `int` / `float` | | `a ** b` | exponentiation | `int` for two `int`s, otherwise `float` | | `-a`, `+a` | negation, identity | same as operand | ```nox print(7 // 2, -7 // 2, 7 % 3, -7 % 3, 7 % -3, 7 / 2) print(5.0 // 2.0, -5.0 // 2.0, 5.5 % 2.0, -5.5 % 2.0) ``` ```output 3 -4 1 2 -2 3.5 2.0 -3.0 1.5 0.5 ``` **Integer power** `int ** int` is exact integer arithmetic (square-and-multiply with the same wrap-around as `*`), not a floating-point `pow`. A negative exponent yields the truncated reciprocal, which is `0` unless the base is `1` or `-1`; `0 ** negative` raises `ZeroDivisionError`. Use floats for fractional results: `2.0 ** -1` is `0.5`. ```nox print(2 ** 10, (-2) ** 3, 2 ** -1, 2.0 ** -1, 2 ** 0.5) ``` ```output 1024 -8 0 0.5 1.4142135623730951 ``` ### Division by zero Integer `//` and `%` with a zero divisor raise `ZeroDivisionError` (catchable like any exception). Floating-point `/`, `//` and `%` follow IEEE-754 and never raise: they produce `inf`, `-inf` or `nan`. ```nox x: float = 1.0 / 0.0 print(x, -x, x - x) try: print(1 // 0) except ZeroDivisionError as e: print("caught:", e.message) ``` ```output inf -inf nan caught: sifira bolme ``` ### Bitwise operators `&`, `|`, `^`, `~`, `<<`, `>>` work on `int` and on fixed-width integers. `>>` is an arithmetic shift for signed values. A shift count outside `[0, width)` raises `ValueError`. ```nox print(1 << 4, 256 >> 2, 6 & 3, 6 | 3, 6 ^ 3, ~5) ``` ```output 16 64 2 7 5 -6 ``` ## `float` `float` is an IEEE-754 binary64. Mixed `int`/`float` arithmetic promotes the integer to `float`; `int → float` is also implicit on assignment (`x: float = 3`). Comparisons between `int` and `float` compare mathematically. ### Printing floats Printing follows Python's `repr`: the **shortest digit string that round-trips**, always with a `.0` for whole values, switching to scientific notation outside `1e-4 <= |x| < 1e16`, and `inf`, `-inf`, `nan` for the special values. `print`, `str(x)`, f-strings and the printing of containers all agree. ```nox print(0.1 + 0.2, 1e16, 1.5e-7, 100.0, 1 / 3, 2.5, -0.0) ``` ```output 0.30000000000000004 1e+16 1.5e-07 100.0 0.3333333333333333 2.5 -0.0 ``` ## Conversions Everything except `int → float` is explicit. The conversion functions are spelled like the types: | Call | From | Behaviour | |---|---|---| | `int(x)` | `float` | truncates toward zero (`int(-3.9) == -3`) | | `int(x)` | `str` | parses a decimal integer; a bad string raises `ValueError` | | `int(x)` | `bool` | `0` or `1` | | `int(x)` | fixed-width integer | widens; a `u64`/`usize` above `9223372036854775807` terminates the program | | `float(x)` | `int`, `bool`, fixed-width, `str` | exact where representable; a bad `str` raises `ValueError` | | `str(x)` | `int`, `float`, `bool`, `str`, containers, classes | the same text `print` shows | | `bool(x)` | `bool`, `int`, `float`, `str`, `list`, `dict`, classes | truthiness (zero, empty, `__bool__`) | | `u8(x)`, `i32(x)`, … | `int`, `float`, other fixed-width | range-checked narrowing/widening | ```nox print(int(3.9), int(-3.9), int("42"), float("2.5"), float(3), str(3.0), int(True)) ``` ```output 3 -3 42 2.5 3.0 3.0 1 ``` ## Rounding and the numeric built-ins `round(x)` rounds half to even and returns an `int` (`round(2.5) == 2`, `round(3.5) == 4`). `round(x, n)` returns a `float` and rounds the *exact binary value* like Python, so `round(2.675, 2)` is `2.67`. `abs`, `min`, `max`, `sum` and `divmod` are described in [Built-in functions](https://noxlang.com/docs/language/builtins/); `nox.math` ([stdlib](https://noxlang.com/docs/stdlib/math/)) has the transcendental functions. ```nox print(round(2.5), round(3.5), round(-2.5), round(2.675, 2), round(3.14159, 3)) print(abs(-3), abs(-2.5), min(1, 2), max(1.5, 2.0), divmod(17, 5)) ``` ```output 2 4 -2 2.67 3.142 3 2.5 1 2.0 (3, 2) ``` ## Fixed-width integers `i8 i16 i32 i64 isize` and `u8 u16 u32 u64 usize` exist for byte-level code, binary formats and `lowlevel`. Their rules differ deliberately from `int`: - They **never mix implicitly** — with each other, with `int`, or with `float`. `u8 + i32` and `u8 + int` are compile errors. - A literal fits implicitly where the value is in range: `b: u8 = 200` is fine, `b: u8 = 300` is a compile error. - So does a **constant**: a module-level `NAME: int = ` that is never reassigned anywhere in the program, and any expression built only from literals and such names with `+ - * | & ^ << >> ~` (`FLAG_A | FLAG_B`), is accepted where a fixed-width integer is expected when its value is in range (`x: i32 = FLAG_A | FLAG_B`, `f(FLAG_A)` for an `i32` parameter). A value that does not fit is a compile error naming the constant value; a variable that is ever reassigned is not a constant. This is what lets the `#define` flags that [`noxc bindgen`](https://noxlang.com/docs/tools/bindgen/) writes be passed to C functions without `i32(...)`. - Conversion is explicit and **range-checked on every backend**: `u8(300)` terminates the program, `u8(-1)` too. - **Overflow of `+`, `-` and `*` terminates the program** with a message (`'u8' integer overflow`), on both backends. Plain `int` wraps; fixed-width does not. - `usize`/`isize` are as wide as the pointer (64 bits on all supported targets). - `%`, `//` and `**` are not defined on fixed-width values; convert with `int(x)` first. Unary `-` on an unsigned type is a compile error. - Comparisons use the signedness of the type. - `list[u8]` and the other fixed-width list types are stored byte-packed. ```nox a: u8 = 200 b: u8 = 55 total: u8 = a + b print(total, int(total) // 7, u8(int(total) % 2)) ``` ```output 255 36 1 ``` `sizeof(T)`, `alignof(T)` and `offsetof(T, "field")` query sizes; `@repr("C")` and `@packed` choose class layouts (see [Foreign functions](https://noxlang.com/docs/language/ffi/)). ## Booleans `bool` has the two values `True` and `False`. It does not participate in arithmetic (`True + 1` is a compile error) — convert with `int(b)` when a number is needed. `and`, `or` and `not` operate on `bool` and short-circuit; conditions in `if`, `while`, `assert` and the ternary must be `bool` (there is no implicit truthiness except through `bool(x)`). --- # Strings `str` is an immutable sequence of Unicode code points stored as UTF-8. Strings are reference-counted heap values, but because they are immutable they behave like plain values. ## Indexing, length and slicing `len(s)`, `s[i]` and slices count **code points**, not bytes, so non-ASCII text behaves intuitively. `s[i]` is a one-character `str`. Negative indexes count from the end and an index out of range raises `IndexError`. For ASCII-only strings (the common case) the runtime tracks that fact and `len` and `s[i]` are O(1). ```nox s: str = "héllo" print(len(s), s[1], s[-1], s[1:3], s[::-1]) for ch in "añb": print(ch) ``` ```output 5 é o él olléh a ñ b ``` Slices `s[a:b]`, `s[:b]`, `s[a:]`, `s[:]`, `s[a:b:step]` follow Python: bounds clamp, negative bounds count from the end, and a step of zero raises `ValueError` (a literal zero step is a compile error). A slice is a value — assigning to one is not supported, and strings cannot be modified in place. ## Operators | Expression | Meaning | |---|---| | `a + b` | concatenation | | `s * n`, `n * s` | repetition (`n <= 0` gives `""`) | | `a == b`, `a != b` | equality | | `a < b`, `a <= b`, `a > b`, `a >= b` | lexicographic comparison by code point | | `x in s`, `x not in s` | substring test (the empty string is in every string) | ```nox print("ab" * 3, "ab" < "b", "a" in "cat", "x" not in "cat", "ab" + "cd") ``` ```output ababab True True True abcd ``` ## Methods All methods return new strings. Case mapping and character classes follow Unicode (the same results as Python's `str`; Unicode 17): `"Straße".upper()` is `"STRASSE"`, `"ΟΔΟΣ".lower()` ends in the final sigma `ς`, `"é".isalpha()` is `True`. Not included: normalization (NFC/NFD), locale-specific mappings (Turkish `i`) and text shaping. Positions are code points. | Method | Result | |---|---| | `upper()`, `lower()`, `capitalize()`, `title()`, `swapcase()`, `casefold()` | case conversions | | `strip([chars])`, `lstrip([chars])`, `rstrip([chars])` | trim whitespace, or any of `chars` | | `split([sep])` | split on `sep`, or on runs of whitespace when omitted | | `rsplit(sep[, maxsplit])`, `splitlines()` | split from the right / at line breaks | | `sep.join(parts)` | join a `list[str]` | | `replace(a, b)` | replace every occurrence | | `startswith(p)`, `endswith(p)` | prefix / suffix tests | | `removeprefix(p)`, `removesuffix(p)` | strip a prefix / suffix if present | | `find(sub)`, `rfind(sub)` | first / last code-point index, or `-1` | | `index(sub)`, `rindex(sub)` | like `find`, but raise `ValueError` when absent | | `count(sub)` | non-overlapping occurrences | | `partition(sep)`, `rpartition(sep)` | a 3-tuple `(before, sep, after)` | | `isdigit()`, `isdecimal()`, `isnumeric()`, `isalpha()`, `isalnum()`, `isspace()`, `isupper()`, `islower()` | character-class tests | | `ljust(w[, c])`, `rjust(w[, c])`, `center(w[, c])`, `zfill(w)` | padding | ```nox t: str = "Hello, World" print(t.upper(), t.lower(), t.title(), t.swapcase()) print(t.split(", "), "a b c".split(), "-".join(["x", "y", "z"])) print(t.replace("l", "L"), t.startswith("He"), t.endswith("ld")) print(t.find("o"), t.find("zz"), t.index("W"), t.count("l"), t.rfind("o")) print("7".zfill(3), "ab".ljust(5, "."), "ab".center(6, "*")) print("pre_fix".removeprefix("pre_"), "a=b=c".partition("="), "xxhixx".strip("x")) ``` ```output HELLO, WORLD hello, world Hello, World hELLO, wORLD ['Hello', 'World'] ['a', 'b', 'c'] x-y-z HeLLo, WorLd True True 4 -1 7 3 8 007 ab... **ab** fix ('a', '=', 'b=c') hi ``` The module [`nox.strings`](https://noxlang.com/docs/stdlib/strings/) offers the same operations as functions plus a few extras (`reverse`, `repeat`, …). `chr(cp)` and `ord(s)` convert between code points and one-character strings. ## Converting to and from `str` `str(x)` renders an `int`, `float`, `bool` or `str`, and — new in 2.0 — lists, dictionaries, tuples, sets and class instances, with exactly the text `print` would show. A class with `__str__` uses it. `int(s)` and `float(s)` parse and raise `ValueError` on bad input. `repr`-style output is what containers show for their elements (`['a']`, not `[a]`). ```nox class Pt: x: int y: int def __init__(self, x: int, y: int) -> None: self.x = x self.y = y print(str([1, 2]), str({"k": [1]}), str((1, "x")), str(Pt(1, 2))) ``` ```output [1, 2] {'k': [1]} (1, 'x') Pt(x=1, y=2) ``` ## F-strings An f-string interpolates expressions with `{expr}`; each value is rendered like `str(value)`. A literal brace is written `{{` or `}}`. Quotes inside a replacement field must differ from the f-string's own delimiter. ```nox name: str = "Ada" n: int = 3 print(f"{name} has {n * 2} items; {{literal}}") ``` ```output Ada has 6 items; {literal} ``` ### The format mini-language A field may carry a format specification, `{value:spec}`, with the full Python mini-language `[[fill]align][sign][#][0][width][,|_][.precision][type]`: - **align**: `<` left, `>` right, `^` centre, `=` pad between sign and digits; **fill** is any character before the align. - **sign**: `+`, `-` (default) or a space. - **#**: alternate form (`0x`, `0b`, `0o` prefixes). - **0**: zero padding. **,** and **_**: thousands separators. - **type** — integers: `b c d n o x X`; floats: `e E f F g G n %`; strings: `s`. `f` and `%` round the *exact binary value* like Python, so `f"{2.675:.2f}"` is `2.67`. An invalid specification raises `ValueError`. `!s` converts with `str`. ```nox x: int = 42 pi: float = 3.14159 big: int = 1234567 p: float = 0.256 print(f"{x:5d}|{x:03d}|{x:<6}|{x:^6}|{x:>6}|{x:*>6}|{x:+d}") print(f"{pi:.3f} {pi:10.2f} {big:,} {x:#x} {x:b} {p:.1%} {2.675:.2f}") print(f"{'ab':>5} {'ab':<5}| {x!s}") ``` ```output 42|042|42 | 42 | 42|****42|+42 3.142 3.14 1,234,567 0x2a 101010 25.6% 2.67 ab ab | 42 ``` `format(value, spec)` formats a single value, and `"...".format(...)` accepts positional (`{}`, `{0}`) and named (`{name}`) fields with the same specifications: ```nox print(format(3.14159, ".2f"), "{} scored {:.1f}".format("ada", 9.25), "{1}-{0}".format("a", "b")) ``` ```output 3.14 ada scored 9.2 b-a ``` `!r` converts with `repr` (`f"{name!r}"` is `f"{repr(name)}"`). Not supported: the `!a` conversion, nested `{}` inside a specification, attribute or index fields in `str.format` (use an f-string instead), and `%`-style formatting (`"%d" % x`). ## Raw strings and adjacent literals A string prefixed with `r` (`r"C:\new\table"`, also `r'…'` and `r"""…"""`) keeps backslashes as written. A raw string cannot end in an odd number of backslashes. String literals written next to each other are joined at compile time (`"ab" "cd"` is `"abcd"`); this is handy inside parentheses to split a long text over lines. Raw and f-string prefixes cannot be combined (`rf"…"` is not supported). ## Multi-line strings Triple-quoted literals span lines and keep their newlines. There is no implicit dedent; `"""` strings used as documentation should be dedented by the author. ## Encoding Source files and string literals are UTF-8. Invalid UTF-8 can enter a program only through byte-level APIs (files, sockets, `extern def`); `nox.strings` and `nox.binary` document how those are validated. NNI string handles are validated UTF-8 as well ([NNI](https://noxlang.com/docs/apis/nni/)). --- # Expressions ## Operator precedence From loosest to tightest binding (operators on one row bind equally): | Level | Operators | |---|---| | 1 | `lambda` | | 2 | `a if cond else b` (conditional expression; right-associative) | | 3 | `or` | | 4 | `and` | | 5 | `not` | | 6 | `== != < <= > >= in not in is is not` (chained, see below) | | 7 | `\|` | | 8 | `^` | | 9 | `&` | | 10 | `<< >>` | | 11 | `+ -` | | 12 | `* / // %` | | 13 | unary `- + ~` | | 14 | `**` (right-associative; binds tighter than a unary minus on its left) | | 15 | subscription `x[i]`, slicing, call `f(x)`, attribute `x.name` | ```nox print(-2 ** 2, 2 ** 3 ** 2, 1 + 2 << 3, 6 & 3 == 2, 2 + 3 * 4 - 1, 7 // 2 * 2, not 1 == 2) ``` ```output -4 512 24 True 13 6 True ``` ## Boolean operators `and`, `or` and `not` take and return `bool` and **short-circuit**. There is no implicit truthiness: `if x:` with an `int`, `str` or `list` is a compile error; write the comparison, or use `bool(x)` / `len(x) > 0`. ## Comparisons Comparison operators work on numbers (`int` and `float` mix), strings (code-point order), `bool` (equality only), lists, dictionaries, tuples and classes (equality, structural: element-wise for lists/tuples, key-by-key for dictionaries — insertion order does not matter, as in Python — and field-wise for classes unless `__eq__` is defined). The structure is followed all the way down: a class field, a list element or a dictionary value that is itself a list, dictionary or class is compared structurally, and a nested class that defines `__eq__` is compared with its `__eq__`. Comparisons **chain** like Python: `a < b < c` means `a < b and b < c`, and the middle operand is evaluated once and must be free of side effects. `==` and `!=` also accept optional operands (`T | None`) — two optionals, or an optional and a plain `T`: `None == None` is true, `None` against a value is false, and two values are compared with the equality of `T` (including a class's `__eq__`). The same holds for optional class fields. ```nox a: str | None = None b: str | None = None c: str | None = "x" d1: dict[str, int] = {"p": 1, "q": 2} d2: dict[str, int] = {"q": 2, "p": 1} print(a == b, a == c, c == "x", d1 == d2) ``` ```output True False True True ``` `x in c` and `x not in c` test membership: an element of a list, a key of a dict, a member of a set, a substring of a string. `x is None`, `x is not None`, `x == None` and `x != None` test optionals and are never overloaded. ```nox x: int | None = None d: dict[str, int] = {"a": 1} print(1 < 2 < 3, 1 < 3 < 2, 5 > 3 == 3) print("a" in d, "b" not in d, 3 in [1, 2, 3], x is None, x is not None) ``` ```output True False True True True True True False ``` ## Conditional expressions `a if cond else b` evaluates only the chosen branch. `cond` must be a `bool`; both branches must have the same type (`1 if ok else 2.5` is rejected — convert explicitly). After an `x is not None` / `x is None` test the optional is narrowed in the matching branch. ```nox n: int = 15 label: str = "big" if n > 20 else "medium" if n > 10 else "small" node_val: int | None = 7 print(label, node_val if node_val is not None else 0) ``` ```output medium 7 ``` ## Subscription and slicing `x[i]` indexes a list, string, dictionary or tuple. List and string indexes may be negative; an out-of-range index raises `IndexError`, a missing dictionary key raises `KeyError`. A tuple index must be a constant. `x[a:b]`, `x[:b]`, `x[a:]`, `x[:]`, `x[a:b:step]` and `x[::-1]` produce a new list or string; bounds clamp, a zero step raises `ValueError`. Slices cannot be assigned to. ```nox xs: list[int] = [1, 2, 3, 4, 5] print(xs[1:3], xs[::2], xs[::-1], xs[-2:], xs[:-1], xs[10:]) t: tuple[int, str] = (1, "a") print(t[0], t[-1]) ``` ```output [2, 3] [1, 3, 5] [5, 4, 3, 2, 1] [4, 5] [1, 2, 3, 4] [] 1 a ``` ## Calls and attributes `f(a, b, key=c)` calls a function, constructor or method ([Functions](https://noxlang.com/docs/language/functions/)). `obj.name` reads a field, and `obj.method(...)` calls a method. **Arguments are evaluated left to right, in the order written**; keyword arguments are bound by name afterwards, so `f(b=g(), a=h())` calls `g` before `h`. ## Comprehensions List, dictionary and set comprehensions build a collection from one or more `for` clauses with optional `if` filters. The loop variable does not leak. The iterable may be a list, a `range(...)`, a `str` or a `dict`: ```nox print([x * x for x in range(5) if x % 2 == 0]) print({k: len(k) for k in ["a", "bb"]}) print({c for c in "hello"}) print([a * b for a in [1, 2] for b in [3, 4] if a != b]) ``` ```output [0, 4, 16] {'a': 1, 'bb': 2} {'h', 'e', 'l', 'o'} [3, 4, 6, 8] ``` A comprehension's condition and iterable are `or`-level expressions; parenthesise a conditional expression there. Lambdas inside comprehensions are not supported. ### Generator expressions A generator expression such as `x * x for x in xs if x > 0` is accepted as the **sole argument of a call** (`sum(...)`, `"".join(...)`, `any(...)`, `list(...)`). It is **evaluated eagerly** into a list — it is not a lazy generator, so it must not be used to model infinite sequences, and side effects inside it happen before the call. ```nox print(sum(x * x for x in [1, 2, 3] if x > 1), ", ".join(str(x) for x in [1, 2])) ``` ```output 13 1, 2 ``` ## Lambdas `lambda a, b: a * b` creates a function value. Parameter and return types come from the expected function type, so a lambda can be passed to a function-typed parameter, assigned to an annotated variable, returned, or placed in a `list[(T) -> U]` literal. Lambdas capture enclosing variables like nested `def`s (read-only). See [Functions](https://noxlang.com/docs/language/functions/). ```nox mul: (int, int) -> int = lambda p, q: p * q print(mul(3, 4), sorted(["bb", "a", "ccc"], key=lambda s: len(s))) ``` ```output 12 ['a', 'bb', 'ccc'] ``` ## Tuples and unpacking `(1, "x")` and `1, "x"` build tuples; an assignment target may be a tuple pattern (`q, r = divmod(17, 5)`, `a, b = b, a`, `self.x, self.y = p`). Tuples are compared and printed element-wise and can be returned from functions to return several values. ```nox def split_pair(n: int) -> tuple[int, int]: return n // 10, n % 10 tens, ones = split_pair(47) a: int = 1 b: int = 2 a, b = b, a print(tens, ones, a, b) ``` ```output 4 7 2 1 ``` ## Operator overloading Classes may define special methods (`__add__`, `__eq__`, `__lt__`, `__getitem__`, `__len__`, `__str__`, `__bool__`, `__contains__`, …) that give meaning to the operators; see [Classes](https://noxlang.com/docs/language/classes/#special-methods). ## Assignment expressions Nox has no walrus operator (`:=`); assign on a separate statement. --- # Statements A Nox program is a sequence of statements. The top-level statements of the entry file are the program's entry point — there is no `main` function ([Modules](https://noxlang.com/docs/language/modules/#the-entry-point)). ## Expression statements Any expression may stand alone as a statement (typically a call). Its value is discarded. A bare string literal is allowed and ignored. ## Assignment ### Declaration The first assignment to a name declares it and **must state its type**: ```nox count: int = 0 names: list[str] = [] ``` Re-stating the same type on a later assignment in the same scope is allowed; re-declaring a name with a *different* type is a compile error. A declaration without a value is not allowed for local variables (a class body may declare *fields* without a value — see [Classes](https://noxlang.com/docs/language/classes/#fields)). ### Unpacking with `*` and nested targets `a, *rest = xs` binds `a` to the first element and `rest` to a new list of the others; `*init, last = xs` and `first, *mid, last = xs` work too (one starred target at most). The right-hand side must be a `list` for a starred target (its length must cover the plain targets). Targets may nest tuples: `(a, b), c = (1, 2), 3`. List and dict displays can spread other lists and dicts: `[*xs, 0, *ys]` builds a new list and `{**defaults, "k": v}` a new dict where later entries win. Operands must be lists (for `[*…]`) or dicts of the same type (for `{**…}`). ```nox xs: list[int] = [1, 2, 3, 4] head, *tail = xs print(head, tail) joined: list[int] = [*tail, 0, *tail] print(joined) base: dict[str, int] = {"a": 1, "b": 2} over: dict[str, int] = {**base, "b": 20} print(over) ``` ```output 1 [2, 3, 4] [2, 3, 4, 0, 2, 3, 4] {'a': 1, 'b': 20} ``` ### Plain, augmented and tuple assignment ```nox x: int = 1 x = x + 1 # plain x += 3 # augmented: += -= *= /= //= %= **= &= |= ^= <<= >>= xs: list[int] = [1, 2, 3] xs[0] = 10 # subscript target xs[1] *= 5 class Box: n: int def __init__(self) -> None: self.n = 0 b: Box = Box() b.n += 1 # attribute target a: int = 1 c: int = 2 a, c = c, a # tuple assignment (swap) print(x, xs, b.n, a, c) ``` ```output 5 [10, 10, 3] 1 2 1 ``` Augmented assignment accepts a variable, an attribute or a subscript whose subexpressions are free of calls (`f()[0] += 1` is rejected). Assigning to a slice, to a call result, or to a tuple element is not supported. For a class value `x += y` uses `__add__` (there is no separate in-place protocol). ## `pass` and `...` `pass` does nothing; it is the body of an empty block. `...` (Ellipsis) is accepted as a statement with exactly the same meaning. (In a `protocol`, `pass` is the required body of each method — see [Protocols and generics](https://noxlang.com/docs/language/protocols-generics/).) ## One-line forms Statements on one line can be separated with `;` (`a: int = 1; b: int = 2`), and the body of a compound statement may follow its colon on the same line (`if x > 1: print(x)`, `else: return 0`, `while i < 3: i += 1`, `def f(): return 1`); several simple statements after the colon are separated with `;` and all belong to the body. A compound statement cannot be the one-line body of another. `noxc fmt` expands these forms to one statement per line. ## `if`, `elif`, `else` The condition must be a `bool`. ```nox n: int = 0 if n > 0: print("positive") elif n == 0: print("zero") else: print("negative") ``` ```output zero ``` ## `while` ```nox i: int = 0 while i < 3: i += 1 print(i) ``` ```output 3 ``` ## `for` `for target in iterable:` iterates a `range(...)`, any `list[T]` expression, a `str` (one `str` per character), a `dict` (its keys in insertion order), or a `set[T]`, and any object whose class defines `__iter__` returning a list, or `__next__() -> T | None` (pulled lazily: `None` ends the loop; generators are such objects). A tuple target unpacks pairs: ```nox for i in range(2, 10, 3): # 2 5 8 (a negative step counts down) print(i) d: dict[str, int] = {"a": 1, "b": 2} for k, v in d.items(): print(k, v) for i, x in enumerate(["p", "q"]): print(i, x) for a, b in zip([1, 2], ["u", "v"]): print(a, b) ``` ```output 2 5 8 a 1 b 2 0 p 1 q 1 u 2 v ``` `range(stop)`, `range(start, stop)` and `range(start, stop, step)` take `int`s; a zero step is an error. Modifying a list while iterating over it is allowed but iterates over the live list; copy first (`for x in xs.copy():`) when you add or remove elements. ### `else` on loops `while … else` and `for … else` run the `else:` block when the loop finishes without hitting `break` (also when the loop body never ran): ```nox def find(xs: list[int], target: int) -> int: for i in range(len(xs)): if xs[i] == target: break else: return -1 return i print(find([4, 5, 6], 5), find([4, 5, 6], 9)) ``` ```output 1 -1 ``` ### `break` and `continue` `break` leaves the innermost `while`/`for`; `continue` jumps to its next iteration. Both are compile errors outside a loop (a nested `def` is a new function and does not count). A `break` or `continue` that leaves a `try … finally`, a `with` or a `lowlevel` block runs the `finally` body, the `__exit__` method or the arena teardown first, exactly as `return` does. ## `return` `return expr` ends the function with a value of the declared return type; a function returning `None` may use a bare `return`. A function with a non-`None` return type must return on every path. `return a, b` returns a tuple. ## `del` `del xs[i]` removes a list element (`IndexError` when out of range, negative indexes allowed); `del d[k]` removes a dictionary entry (`KeyError` when absent). Deleting from a dictionary is amortized O(1) (a deleted entry is a tombstone; tombstones are compacted in one pass once they outnumber half the entries). Insertion order is preserved. ```nox xs: list[int] = [1, 2, 3, 4] d: dict[str, int] = {"a": 1, "b": 2} del xs[0] del d["a"] print(xs, d) ``` ```output [2, 3, 4] {'b': 2} ``` ## `assert` `assert cond` and `assert cond, "message"` raise `AssertionError` when `cond` is false. Assertions are always on — they are not removed in optimised builds. ## `raise`, `try`, `with`, `defer` See [Exceptions](https://noxlang.com/docs/language/exceptions/). ## Definitions `def`, `class`, `protocol` and `extern def` are statements; see [Functions](https://noxlang.com/docs/language/functions/), [Classes](https://noxlang.com/docs/language/classes/), [Protocols and generics](https://noxlang.com/docs/language/protocols-generics/) and [Foreign functions](https://noxlang.com/docs/language/ffi/). `import` and `from … import` are covered in [Modules](https://noxlang.com/docs/language/modules/). ## Scoping Nox has **function scope and module scope — not block scope**. A variable first assigned inside an `if`, `while` or `for` body is visible in the rest of the enclosing function or module, and a loop variable stays defined after the loop (its value there is unspecified — after a `range` loop it is one past the last element, not the last element as in Python — so do not rely on it): ```nox for i in range(3): last: int = i print(last) ``` ```output 2 ``` Rules for names: - A name declared with an annotation inside a function is **local** to that function and may shadow a module-level name of the same name without affecting it. - An un-annotated assignment to a name that is declared at module level (`total += 1`, `total = 5`) from inside a function assigns the **module-level variable**; you may write `global total` inside the function to say so (it changes nothing, but the name must be a module-level variable). - Reading an undeclared name is a compile error ("undefined variable"). - Parameters are locals; assigning to a parameter changes only the local. - A nested `def` can read the enclosing function's variables (closure); assigning to them from the nested function is not supported. ```nox total: int = 0 def bump() -> None: total += 1 # module-level variable def shadow() -> None: total: int = 100 # a new local; the module-level total is untouched print(total) bump() bump() shadow() print(total) ``` ```output 100 2 ``` ## Module-level initialisation order Top-level `name: T = expr` declarations are initialised **before** any other top-level statement runs, in source order, so a function called from a later statement always sees initialised module variables. Cyclic dependencies between module-level initialisers are not detected; keep initialisers simple. --- # Functions ## Defining functions ```nox def area(width: int, height: int) -> int: return width * height def greet(name: str) -> None: print("hello", name) greet("nox") print(area(3, 4)) ``` ```output hello nox 12 ``` Every parameter has a type and every function has a return type (`-> None` for procedures; a `def` that writes no `-> T` at all returns `None`, so `def greet(name: str):` is the same as `def greet(name: str) -> None:` and `return value` in it is a type error). The other exception is `self` in a method ([Classes](https://noxlang.com/docs/language/classes/)). A function must return a value of its declared type on **every path**; the compiler reports "does not return a value on all paths" otherwise. Function names are unique within a module (defining the same name twice is an error), and a top-level function may not be called `main`. Functions can be defined at module level, inside other functions (nested functions) and inside classes (methods). ## Default parameter values A parameter may have a default. The default must be a **constant literal** — an `int`, `float`, `bool`, `str`, a negative number, or `None` for an optional parameter — and parameters with defaults come last: ```nox def connect(host: str, port: int = 8080, label: str | None = None) -> str: name: str = "-" if label is not None: name = label return host + ":" + str(port) + " " + name print(connect("localhost")) print(connect("example.com", 443, "prod")) ``` ```output localhost:8080 - example.com:443 prod ``` ## Keyword arguments A call may name arguments: `f(1, b=3)`, `f(b=3, a=1)`. Positional arguments come first. An unknown name, a repeated parameter or a missing required argument is a compile error. Keyword arguments work for functions, constructors, methods (including `super().__init__`), generic functions and `spawn f(...)`. Function-typed *values* and built-ins take positional arguments only. **Evaluation order.** Arguments are evaluated **in the order written**, left to right; binding to parameters happens afterwards by name. So `f(b=g(), a=h())` calls `g` before `h`. (The one exception: in a `spawn` call, keyword arguments with side effects must be written in parameter order.) ```nox def trace(s: str) -> str: print("eval", s) return s def join(x: str, y: str) -> str: return x + y print(join(y=trace("y"), x=trace("x"))) ``` ```output eval y eval x xy ``` A function can take a variable number of positional arguments with a trailing `*name: T`. Inside the body `name` is a `list[T]`; extra arguments at the call are collected into it (none gives an empty list). It must be the last positional parameter, cannot be passed by keyword, and every extra argument must be a `T`. A trailing `**name: T` collects keyword arguments that match no declared parameter into a `dict[str, T]` (names that match a declared parameter bind to it as usual); it must be the very last parameter and takes no extra positional arguments. Parameters after a bare `*` or after `*args` are **keyword-only**: they can only be given as `name=value` (`def conf(name: str, *, retries: int = 3)`). A call can unpack a list into a `*args` parameter with `f(a, *xs)`; the list is copied, and the `*xs` must sit exactly at the position of the `*args` parameter (no positional argument may follow it). A call can unpack a `dict[str, T]` into a `**kwargs: T` parameter with `f(a, **d)` (several `**` and explicit keywords may be mixed; the callee must have a `**kwargs` parameter). Because the keys are only known at run time, a key never binds a named parameter: a key that equals the name of one raises `ValueError` ("got multiple values"), and a key given twice raises `ValueError` too. A bare `/` in the parameter list makes every parameter before it **positional-only** (`def log(msg: str, level: int, /, **fields: str)`): it cannot be passed by keyword, and `log("x", 1, msg="y")` puts `msg` into `fields`. Keyword-only, `*args` and `**kwargs` parameters may follow defaulted ones without a default of their own. ```nox def log(msg: str, level: int, /, **fields: str) -> str: out: str = msg + ":" + str(level) for k in fields.keys(): out = out + " " + k + "=" + fields[k] return out extra: dict[str, str] = {"user": "ada"} print(log("hi", 2, host="h", **extra)) print(log("hi", 2, msg="shadow")) ``` ```output hi:2 host=h user=ada hi:2 msg=shadow ``` ```nox def total(first: int, *rest: int) -> int: t: int = first for r in rest: t += r return t print(total(1), total(1, 2, 3, 4)) ``` ```output 1 10 ``` ## Growing a list parameter A free function can add to a list its caller passed in, as in Python: ```nox def fill(acc: list[int], n: int) -> None: for i in range(n): acc.append(i * i) xs: list[int] = [] fill(xs, 4) print(xs) ``` ```output [0, 1, 4, 9] ``` `append`, `insert` and `extend` on a list parameter are visible to the caller, also through several call levels, recursion, module-level lists, object fields (`fill(obj.items, 3)`) and methods, and a fresh temporary argument (`fill([1, 2], 3)`) is simply dropped afterwards. Nothing about this shows in the syntax: a list is a handle whose header never moves when it grows, so every name that refers to it sees the new elements (exactly as in Python). ## Functions are values A function name used as a value has a function type `(P1, P2) -> R`. Functions can be assigned, stored in lists and dictionaries, passed as arguments and returned: ```nox def double(n: int) -> int: return n * 2 def triple(n: int) -> int: return n * 3 def apply(f: (int) -> int, x: int) -> int: return f(x) ops: list[(int) -> int] = [double, triple] for op in ops: print(apply(op, 7)) print(ops[1](4)) ``` ```output 14 21 12 ``` ### Closures A nested function or lambda may **read** variables of the enclosing function. The captured variables stay alive as long as the closure does. To **assign** to a variable of the enclosing function, declare it `nonlocal` in the nested function (see below); without it, assigning to a captured variable is a compile error. ```nox def make_adder(k: int) -> (int) -> int: def add(x: int) -> int: return x + k return add add5: (int) -> int = make_adder(5) fs: list[(int) -> int] = [make_adder(1), make_adder(2), lambda z: z * 10] for f in fs: print(f(3)) print(add5(1)) ``` ```output 4 5 30 6 ``` ### Generators (`yield`) A function whose body contains `yield` (or `yield from`) and whose return type is `Iterator[T]` (`Generator[T]` is the same type) is a **generator**: calling it runs nothing yet, and each value is produced only when the consumer asks for it. ```nox def squares(n: int) -> Iterator[int]: for i in range(n): print("making", i) yield i * i def naturals() -> Iterator[int]: n: int = 0 while True: n += 1 yield n for v in squares(3): print("using", v) if v >= 1: break total: int = 0 for k in naturals(): total += k if total > 20: break print(total, list(squares(3)), sum(squares(4))) g: Iterator[int] = squares(2) print(next(g), next(g), next(g, -1)) ``` ```output making 0 using 0 making 1 using 1 making 0 making 1 making 2 making 0 making 1 making 2 making 3 21 [0, 1, 4] 14 making 0 making 1 0 1 -1 ``` The producer and the loop alternate (`making 0`, `using 0`, `making 1`, …), `break` stops the producer for good, and an infinite generator such as `naturals` is fine as long as the consumer stops. (`list(squares(3))` and `sum(squares(4))` run their generators to the end while the arguments of `print` are evaluated, before the line is printed.) - `for x in g` pulls values one at a time. `list(g)`, `sum(g)`, `sorted(g)`, `max(g)`, `enumerate(g)`, … drain what is left of the generator. - `next(g)` returns the next value and raises `StopIteration` when the generator is exhausted; `next(g, default)` returns `default` instead. - `yield from xs` yields every element of a list, a `range(...)` or another generator, lazily. - A bare `return` ends the generator. An exception raised inside it propagates to the consumer and ends it (later pulls produce nothing). ### Cleanup, `send()` and generic generators `yield` may appear inside a `try` body and inside a `with` block. The generator keeps its place, a `finally` clause (or the `with`'s `__exit__`) runs when the generator **finishes**, raises, or is closed with `g.close()` (which raises `GeneratorExit` at the paused `yield`), and `__enter__` runs once. A `for` loop over a *fresh call* of such a generator (`for x in lines(...)`) closes it on every exit, so a `break` cleans up like in CPython. A generator that is abandoned some other way (stored in a variable and dropped, or passed to another function that stops early) is closed when its last reference goes away (the generator object defines [`__del__`](https://noxlang.com/docs/language/classes/#destructors-__del__)), so a `with` block or `finally` that was waiting at a `yield` still runs, at the moment of the last release. Objects reclaimed by the cycle collector or created inside `lowlevel` are the exception: call `close()` for those. A generator annotated `Generator[Y, S]` also receives values: `x = yield value` pauses with `value` and resumes with the value passed to `g.send(v)`. Prime it with `next(g)` first (sending to a just-started generator is a `ValueError`); `send` returns the next yielded value or raises `StopIteration`. `Generator[Y, S]` is not assignable to `Iterator[Y]`; use `g.iterator()` for that. Generator functions may be generic. ```nox class Resource: def __init__(self, name: str) -> None: self.name: str = name def __enter__(self) -> str: print("open", self.name) return self.name def __exit__(self) -> None: print("close", self.name) def lines(name: str) -> Iterator[str]: with Resource(name) as r: for i in range(3): yield r + ":" + str(i) def running_total() -> Generator[int, int]: total: int = 0 while True: n: int = yield total total += n for line in lines("log"): print(line) if line == "log:1": break g: Generator[int, int] = running_total() print(next(g), g.send(5), g.send(7)) g.close() def take[T](it: Iterator[T], n: int) -> Iterator[T]: count: int = 0 for x in it: if count >= n: break yield x count += 1 print(list(take(lines("tmp"), 3))) ``` ```output open log log:0 log:1 close log 0 5 12 open tmp close tmp ['tmp:0', 'tmp:1', 'tmp:2'] ``` `g.throw(error)` raises `error` at the generator's current `yield`. A `try`/`except` around that `yield` can catch it and the generator carries on (the call returns the next yielded value, or raises `StopIteration` if the generator then ends); if nothing catches it, the exception reaches the caller and the generator is finished. Throwing into a generator that has not started, or has finished, raises the exception directly. ```nox def worker() -> Iterator[int]: n: int = 0 while True: try: yield n n += 1 except ValueError as e: print("caught", e.message) n = 100 w: Iterator[int] = worker() print(next(w), next(w), w.throw(ValueError("reset")), next(w)) ``` ```output caught reset 0 1 100 101 ``` `yield` may also appear in an `except` handler and in a `finally` block (a `finally` that yields runs after the protected region and re-raises a pending exception once it ends; calling `close()` on a generator that yields from such a `finally` raises `RuntimeError`, as in Python). A local variable or parameter of function type may live across a `yield`. ```nox def retry(attempts: int) -> Iterator[str]: for i in range(attempts): try: if i < 2: raise ValueError("fail " + str(i)) yield "ok " + str(i) except ValueError as e: yield "handler " + e.message finally: yield "cleanup " + str(i) print(list(retry(3))) ``` ```output ['handler fail 0', 'cleanup 0', 'handler fail 1', 'cleanup 1', 'ok 2', 'cleanup 2'] ``` A generator is compiled to a resumable state machine, so a few things are not allowed: `yield` inside `lowlevel`; `return value`; and a `return`, `break` or `continue` that leaves a `try` whose `finally` contains a `yield` (the `finally` would be skipped, so this is a compile-time error). `Iterable[T]` stays a plain `list[T]` (use it for parameters that take a finished sequence). `async def` generators are covered in [Concurrency](https://noxlang.com/docs/language/concurrency/#async-generators-and-async-for). ### `nonlocal` `nonlocal name` lets a nested function assign to a variable that belongs to an enclosing function. The variable must be declared with an explicit type (or be a typed parameter) in the enclosing function, and it cannot be a `for` loop variable. Internally such a variable lives in a shared one-element cell, so every closure sees the same value. ```nox def make_counter() -> int: hits: int = 0 def hit() -> None: nonlocal hits hits += 1 hit() hit() hit() return hits print(make_counter()) ``` ```output 3 ``` ### Bound methods `obj.method` used as a value is a function bound to `obj`: ```nox class Counter: n: int def __init__(self, n: int) -> None: self.n = n def add(self, k: int) -> int: return self.n + k c: Counter = Counter(10) g: (int) -> int = c.add print(g(5)) ``` ```output 15 ``` ### Lambdas `lambda a, b: expr` creates an anonymous function whose parameter and return types are inferred from the **expected function type**: a lambda must appear where that type is known — an argument of a function-typed parameter, an annotated declaration, a return value, or a function-list literal. Assigning a lambda to an un-annotated name is an error because there is nothing to infer from. ```nox def compose(f: (int) -> int, g: (int) -> int) -> (int) -> int: return lambda x: g(f(x)) inc_then_double: (int) -> int = compose(lambda x: x + 1, lambda x: x * 2) print(inc_then_double(4)) ``` ```output 10 ``` ## Recursion Functions may call themselves and each other. The main thread runs on the operating-system stack, so very deep recursion works (a 200 000-level recursion is fine). Code running in a [fiber](https://noxlang.com/docs/language/concurrency/) (a `spawn`ed task) has a smaller fixed stack, large enough for roughly two thousand frames of an average function; deeply recursive algorithms should run on the main program or use an explicit work list. The compiler may turn tail calls into loops, but you must not rely on it. ```nox def depth(n: int) -> int: if n == 0: return 0 return 1 + depth(n - 1) print(depth(10000)) ``` ```output 10000 ``` ## Generic functions `def first[T](xs: list[T]) -> T` is generic over `T`, specialised at compile time; see [Protocols and generics](https://noxlang.com/docs/language/protocols-generics/). ## Decorators `@name` and `@name("arg")` before a top-level function attach **metadata** that tools can query with `nox.reflect`; they do not wrap the function. See [Decorators and reflection](https://noxlang.com/docs/language/decorators/). ## Object-file symbol names: `@link_name` `@link_name("symbol")` before a top-level `def` changes only the **object-file symbol** of that function; the Nox name is unchanged and calls use it as usual. It exists for wrappers that must keep a C library's name but cannot share its symbol (`noxc bindgen` writes it for you); you rarely need it by hand. ```nox-fragment @link_name("nox_w_square") def square(x: int) -> int: return x * x ``` ## Async functions `async def` defines a function that may be started with `spawn` and awaited; see [Concurrency](https://noxlang.com/docs/language/concurrency/). ## Calling conventions at a glance | Form | Meaning | |---|---| | `f(1, 2)` | positional | | `f(1, b=2)` | positional then keyword | | `obj.m(1)` | method call, `self` implicit | | `Class(1)` | constructor call (`__init__`) | | `f[int](x)`, `obj.m[int](x)` | explicit type argument to a generic function/method | | `spawn f(1)` | start `f` as a task, yields `Task[T]` | --- # Classes A `class` declares a new reference type with fields and methods. Nox supports [multiple inheritance](#several-bases-multiple-inheritance), special ("dunder") methods for operators and protocols, and structural [protocols](https://noxlang.com/docs/language/protocols-generics/). There are no metaclasses and no dynamic attribute creation. ## Fields A class's fields are fixed. They can be established three ways, and all may be used in the same class: 1. **Implicitly**, by the first `self.name = expr` assignment inside `__init__` (the type is inferred from the expression), or 2. **With an annotation**, `self.name: type = expr` inside `__init__`: the declared type is the field's type, so an empty `[]` or `{}` or a `None` needs no further hint (`self.items: list[int] = []`), or 3. **Explicitly**, with a bare `name: type` line in the class body (no initialiser — the assignment itself still happens in `__init__`). If a field is declared explicitly it must actually be assigned in `__init__`; an unassigned declared field is a compile error, never a zeroed value. Fields can only be *created* in `__init__`: assigning a new `self.name` from another method is a compile error. Values shared by the whole class are [class attributes](#class-attributes-and-constants). ### Class attributes and constants `NAME: type = literal` in a class body declares a **constant**: `int`, `float`, `bool` or `str`, with a literal value (a leading `-` is allowed). It is not a field and takes no space in an instance. Read it as `ClassName.NAME`, `self.NAME` or `obj.NAME`; the compiler replaces the read with the literal. Subclasses inherit them. The value cannot be an expression (`N: int = 1 + 2` is an error). If the program **assigns** the name anywhere (`ClassName.NAME = value`, `ClassName.NAME += 1`, in a method, a function or another module), it is a **mutable class attribute** instead: one storage shared by the class, its subclasses and every instance, held like a module-level variable, and reads see the latest value. Names that are never assigned stay compile-time constants. Assign through the declaring class: `self.NAME = v` and `Sub.NAME = v` are compile errors (instances and subclasses have no copy of a class attribute). Mixins share the attribute with the class that declares it. ```nox class Limits: MAX: int = 5 RATE: float = 2 count: int def __init__(self) -> None: self.count = 0 def room(self) -> int: return Limits.MAX - self.count print(Limits.MAX, Limits().room()) ``` ```output 5 5 ``` ```nox class Counter: count: int = 0 LIMIT: int = 3 def __init__(self) -> None: Counter.count += 1 @staticmethod def reset() -> None: Counter.count = 0 a: Counter = Counter() b: Counter = Counter() print(Counter.count, a.count, Counter.LIMIT) Counter.reset() print(b.count) ``` ```output 2 2 3 0 ``` ```nox class Account: """A bank account.""" owner: str balance: int def __init__(self, owner: str, balance: int) -> None: self.owner = owner self.balance = balance def deposit(self, amount: int) -> None: self.balance += amount def describe(self) -> str: return self.owner + ": " + str(self.balance) acct: Account = Account("ada", 100) acct.deposit(50) print(acct.describe()) ``` ```output ada: 150 ``` ## `self` `self` is the first parameter of every method. It may be written bare (`def deposit(self, amount: int)`) or explicitly typed (`self: Account`) — they are equivalent; the compiler always infers the enclosing class. This is the single sanctioned exception to "every parameter has a type". ## Construction and identity `ClassName(args)` allocates an instance and runs `__init__`. A class without `__init__` takes no constructor arguments. Class values are **references**: `b: Account = acct` makes both names refer to one object, so a change through either is visible through both. Memory is reclaimed automatically ([Memory](https://noxlang.com/docs/language/memory/)). ```nox class Cell: v: int def __init__(self, v: int) -> None: self.v = v a: Cell = Cell(1) b: Cell = a b.v = 9 print(a.v, a == Cell(9), a == Cell(1)) ``` ```output 9 True False ``` Equality `==` is **structural** by default: two instances of the same class are equal when all their fields are equal (recursively). Define `__eq__` to override. ## Inheritance `class Dog(Animal):` declares a subclass. Subclasses inherit fields and methods and may override methods; calls dispatch dynamically through a vtable. `super().method(...)` calls the base implementation (and `super().__init__(...)` chains constructors). A value of a subclass can be used wherever the base class is expected, including inside `list[Base]`. `except Base:` also matches every subclass ([Exceptions](https://noxlang.com/docs/language/exceptions/)). ```nox class Animal: name: str def __init__(self, name: str) -> None: self.name = name def speak(self) -> str: return self.name + " makes a sound" def intro(self) -> str: return "this is " + self.speak() class Dog(Animal): def __init__(self, name: str) -> None: super().__init__(name) def speak(self) -> str: return self.name + " barks" class Puppy(Dog): def speak(self) -> str: return "tiny " + super().speak() zoo: list[Animal] = [Animal("cat"), Dog("rex"), Puppy("bit")] for a in zoo: print(a.intro()) ``` ```output this is cat makes a sound this is rex barks this is tiny bit barks ``` There is no `isinstance` and no run-time type test; use a protocol, a virtual method, or an `except` clause for dispatch on type. ### Several bases (multiple inheritance) `class C(A, B, D):` is allowed. The **first** base is the primary base class (vtable dispatch, `super()`). Methods, declared fields and constants of the other bases are compiled into `C` (so `C` has its own copy of each method, bound to `C`'s layout). Name resolution follows Python's order: `C`'s own members, then `A` and its bases, then `B`, then `D`. `C` is a **subtype of every base**: a `C` can be passed or stored wherever an `A`, a `B` or a `D` is expected (parameters, `list[B]`, fields, returns), the calls and field accesses on that `B` reach the `C`'s own methods and state (overrides included), and `except B:` catches a `C` when the bases are exception classes (`class Timeout(Retryable, Fatal)`). All bases see the same object: there are no pointer adjustments or wrapper objects. As in Python, a mixin's `__init__` runs only when you call it, and you call a base's method explicitly with `Base.method(self, ...)`. The compiler turns `Mixin.method(self, args)` into a call of a private copy of that method, and `A.method(self, args)` on the real base into `super().method(args)`. A mixin's `__init__` may create fields, so the mixin keeps its own state: ```nox class Animal: def __init__(self, name: str) -> None: self.name: str = name def speak(self) -> str: return self.name + " makes a sound" class Swimmer: def __init__(self, depth: int) -> None: self.depth = depth self.laps = 0 def swim(self) -> str: self.laps += 1 return "swims to " + str(self.depth) + ", lap " + str(self.laps) class Duck(Animal, Swimmer): def __init__(self, name: str) -> None: super().__init__(name) Swimmer.__init__(self, 3) def speak(self) -> str: return self.name + " quacks, then " + Animal.speak(self) d: Duck = Duck("Donald") print(d.speak()) print(d.swim(), "|", d.swim(), d.laps) ``` ```output Donald quacks, then Donald makes a sound swims to 3, lap 1 | swims to 3, lap 2 2 ``` A mixin may instead declare its state as a class-level field (`depth: int`); then `C.__init__` must assign it. The shared-name rules of Python apply: a field or method name that appears in two bases is **one** attribute of `C`, so the two definitions must agree: the same field type and the same method signature (a mismatch is a compile-time error). `Base.__init__(self, ...)` works for the direct base in any class and in a mixin's `__init__`. The object layout of every class in an inheritance family that contains multiple inheritance is arranged so that each field keeps one storage slot across the family (fields that are never present together share slots, so the cost is small); families without multiple inheritance keep the ordinary layout. Limits: `super()` is an error inside a mixin method (the method is copied into `C`); generic classes cannot be bases of a multiple-inheritance class; `@repr("C")` and `@packed` classes cannot take part. ### Concrete generic base classes A generic class can be instantiated with concrete type arguments and used as the base of an ordinary class: ```nox class Stack[T]: items: list[T] def __init__(self) -> None: self.items = [] def push(self, v: T) -> None: self.items.append(v) class IntStack(Stack[int]): def total(self) -> int: s: int = 0 for x in self.items: s = s + x return s ``` `Stack[int]` is instantiated once and `IntStack` inherits its fields and methods (including `super()` and overriding) like from any other base; an `IntStack` can be assigned to a `Stack[int]` variable. A generic class itself still cannot have a base (`class B[U](A[U])` is not supported). ## Special methods A class may define special methods; the compiler rewrites each operator into an ordinary method call, so ownership, inheritance and both backends need no special support. | Syntax | Method | |---|---| | `a + b`, `a - b`, `a * b`, `a / b`, `a // b`, `a % b`, `a ** b` | `__add__`, `__sub__`, `__mul__`, `__truediv__`, `__floordiv__`, `__mod__`, `__pow__` | | `a & b`, `a \| b`, `a ^ b`, `a << b`, `a >> b` | `__and__`, `__or__`, `__xor__`, `__lshift__`, `__rshift__` | | `2 * v` (left operand not a class) | `__rmul__` (likewise `__radd__`, `__rsub__`, …) | | `a == b`, `a != b` | `__eq__`, `__ne__` (or `not __eq__`) | | `a < b`, `a <= b`, `a > b`, `a >= b` | `__lt__`, `__le__`, `__gt__`, `__ge__` (a missing one falls back to the reflected method of the right operand) | | `-a`, `~a` | `__neg__`, `__invert__` | | `x in a`, `x not in a` | `__contains__` | | `a[i]`, `a[i] = v` | `__getitem__`, `__setitem__` | | `len(a)` | `__len__` | | `str(a)`, `print(a)`, `f"{a}"` | `__str__` | | `repr(a)`, and the elements of printed containers | `__repr__` (else `__str__`, else the structural form) | | `bool(a)` | `__bool__`, else `__len__() != 0`, else `True` | | `for x in a` | `__next__() -> T \| None` (lazy: one value per pull, `None` ends it) or `__iter__` returning a `list[T]` | Comparison methods must return `bool`, `__len__` an `int`, `__str__`/`__repr__` a `str`. `x += y` on a class value uses `__add__`; there is no separate in-place protocol. Comparing against `None` is never overloaded. Operand evaluation order can differ from Python only for reflected comparisons with side-effecting operands. ```nox class Vec: x: int y: int def __init__(self, x: int, y: int) -> None: self.x = x self.y = y def __add__(self, o: Vec) -> Vec: return Vec(self.x + o.x, self.y + o.y) def __lt__(self, o: Vec) -> bool: return self.x < o.x def __neg__(self) -> Vec: return Vec(-self.x, -self.y) def __str__(self) -> str: return "Vec(" + str(self.x) + "," + str(self.y) + ")" def __len__(self) -> int: return 2 def __getitem__(self, i: int) -> int: if i == 0: return self.x return self.y def __contains__(self, v: int) -> bool: return v == self.x or v == self.y a: Vec = Vec(1, 2) b: Vec = Vec(3, 4) print(a + b, a < b, -a, len(a), a[1], 2 in a, [a, b]) ``` ```output Vec(4,6) True Vec(-1,-2) 2 2 True [Vec(1,2), Vec(3,4)] ``` ### Destructors: `__del__` A class may define `def __del__(self) -> None:`. It runs **once**, when the last reference to an instance goes away (end of scope, reassignment, `del`, the container being released, an exception unwinding the frame), before the fields are released. A subclass inherits it or overrides it; there is no automatic chaining to a base-class `__del__`. ```nox class Res: def __init__(self, name: str) -> None: self.name = name def __del__(self) -> None: print("closing", self.name) def work() -> None: r: Res = Res("a") print("working") work() r2: Res = Res("b") r2 = Res("c") print("end") ``` ```output working closing a closing b end closing c ``` Rules: an exception raised inside `__del__` is swallowed (it never propagates, and a pending exception that was already unwinding is kept intact); an object that `__del__` stores somewhere else survives (and `__del__` does not run a second time for it); instances of a class with `__del__` are always reference counted, never promoted to the stack or an arena. `__del__` is **not** run for objects the cycle collector reclaims, for objects created inside a `lowlevel` block (arena memory is dropped as a whole), or for `ptr`/foreign handles. The order in which several objects of one scope are destroyed is unspecified. ### Default printing A class without `__str__`/`__repr__` prints structurally as `Name(field=value, ...)` — recursively and with Python-style quoting for strings inside containers — so `print(obj)` is always useful for debugging: ```nox class Item: name: str qty: int def __init__(self, name: str, qty: int) -> None: self.name = name self.qty = qty print(Item("pen", 3), [Item("ink", 1)], repr(Item("x", 0))) ``` ```output Item(name='pen', qty=3) [Item(name='ink', qty=1)] Item(name='x', qty=0) ``` ## Generated methods: `@dataclass` and `@derive` Two class decorators make the compiler write boilerplate methods from the class's **fields** (the bare `name: type` lines of the class body). The methods are generated as ordinary Nox source before type checking, so they are type-checked like code you wrote yourself, nothing is created at run time, and an error in a generated method points at the class. | Decorator | Generates | |---|---| | `@dataclass` | `__init__(self, )`; a base class must be a `@dataclass` too and its fields come first (`super().__init__` is called) | | `@derive("order")` | `__lt__`, `__le__`, `__gt__`, `__ge__`, comparing the fields in order (fields must be `int`, `float`, `bool`, `str` or an orderable class) | | `@derive("copy")` | `copy(self)`, a shallow copy (needs `@dataclass`) | | `@derive("json")` | `to_json()`, `write_json(w)`, and the static `from_json(text)` / `from_json_value(v)` (needs `@dataclass` and `import nox.json`) | `==`, `str()`/`print()` and `repr()` are already structural for every class, so there is nothing to derive for them. A class that defines one of the generated methods itself, or a `@dataclass` that defines `__init__`, is an error. JSON supports `int`, `float`, `bool`, `str`, `list[T]`, `dict[str, T]`, `T | None` (a missing or `null` field reads as `None`) and other classes with `@derive("json")`; a missing field or a value of the wrong type raises `JsonError`. ```nox import nox.json from nox.json import JsonError @dataclass @derive("order", "copy", "json") class Point: x: int y: float label: str @dataclass @derive("json") class Path: name: str points: list[Point] note: str | None p: Point = Point(1, 2.5, "a") q: Point = p.copy() q.x = 2 print(p, p < q, p == p.copy()) path: Path = Path("tri", [p, q], None) text: str = path.to_json() print(text) print(Path.from_json(text).to_json() == text) try: Point.from_json("{\"x\": 1}") except JsonError as e: print(e) ``` ```output Point(x=1, y=2.5, label='a') True True {"name":"tri","points":[{"x":1,"y":2.5,"label":"a"},{"x":2,"y":2.5,"label":"a"}],"note":null} True missing field 'y' ``` ## Layout control for foreign code `@repr("C")` lays fields out with natural C alignment and padding, `@packed` removes padding, and `sizeof(T)`, `alignof(T)` and `offsetof(T, "field")` query layouts. They exist for [foreign-function interfaces](https://noxlang.com/docs/language/ffi/); a class instance additionally carries a small runtime header, which `offsetof` accounts for. Un-decorated classes have an unspecified internal layout. ## Static methods, class methods and properties `@staticmethod` is a function that lives in the class namespace: it takes no `self`, and is called as `Account.cap(x)` (or through an instance, `acc.cap(x)`, as long as the receiver expression has no side effects). `@classmethod` takes `cls` as its first (un-annotated) parameter; inside the body `cls(...)` constructs an instance and `cls.NAME` reads a class constant. `cls` is bound at compile time to the class the method is called through, so `Sub.empty()` builds a `Sub`. `@property` turns a method into an attribute read (`acc.pretty`), and an `@name.setter` method makes `acc.name = value` call it; a property without a setter is read-only. ```nox class Account: LIMIT: int = 1000 def __init__(self, balance: int) -> None: self.balance = balance @staticmethod def cap(x: int) -> int: if x > Account.LIMIT: return Account.LIMIT return x @classmethod def empty(cls) -> Account: return cls(0) @property def pretty(self) -> str: return "$" + str(self.balance) @property def amount(self) -> int: return self.balance @amount.setter def amount(self, v: int) -> None: self.balance = Account.cap(v) acc: Account = Account.empty() acc.amount = 5000 print(acc.pretty, Account.cap(12)) ``` ```output $1000 12 ``` These decorators cannot be combined with other decorators, are not available in generic classes, and a static/class method cannot be used as a first-class value (`f = Account.cap`). ## What classes do not have Per-instance or per-subclass copies of class attributes, full multiple inheritance (only mixins), metaclasses, `__slots__`, `__getattr__`/`__setattr__`, `isinstance`/`type`, and `__call__`. Attributes cannot be added to an instance at run time. --- # Enums and `match` An `enum` is a type whose value is exactly one of several **variants**, and a variant can carry data (a *tagged union*). `match` takes a value apart by variant. The compiler checks that every variant is handled. ```nox enum Shape: Circle(radius: float) Rect(w: float, h: float) Empty def area(s: Shape) -> float: match s: case Shape.Circle(r): return 3.14159 * r * r case Shape.Rect(w, h): return w * h case Shape.Empty: return 0.0 c: Shape = Shape.Circle(2.0) print(area(c)) print(area(Shape.Rect(2.0, 3.0))) print(area(Shape.Empty)) ``` ```output 12.56636 6.0 0.0 ``` ## Defining an enum The body lists **variants**, one per line: `Name` (no data) or `Name(field: Type, ...)` (data). Methods go in the same body and may use `match self`. A docstring and `pass` are allowed. ```text enum Token: Word(text: str) Pair(left: str, right: str) Item(node: Node, weight: int) End def is_end(self) -> bool: match self: case Token.End: return True case _: return False ``` Field types are ordinary types: numbers, `str`, lists, dictionaries, classes and other enums. An enum must have at least one variant. ## Creating values A variant with data is built like a function call, `Shape.Circle(2.0)`. A variant without data is written without parentheses, `Shape.Empty`. Both can be used anywhere a value is expected: assigned, passed, stored in lists and dictionaries, returned. Values compare with `==` (same variant and equal data). Enum values follow the usual memory rules, with no keywords to learn: they are released automatically. ## `match` ```text match subject: case Enum.Variant(a, b): ... case Enum.Other: ... case _: ... ``` - The subject is evaluated once. It must be a value of an enum. - A pattern names the variant with its enum, `Shape.Circle`. The enum can be imported and qualified like any class: `shapes.Shape.Circle(r)`; a generic enum is named the same way in an annotation (`o: shapes.Option[int]`). - **Binding.** Inside the parentheses each name receives that field's value, in declaration order, with the field's type. `_` ignores a field. Naming fields works too: `Shape.Rect(h=height, w=width)`. When a pattern has parentheses it must account for every field (use `_`); without parentheses (`Shape.Rect:`) the fields are ignored. - `case _:` matches anything not matched above and must come last. - Cases are tried top to bottom and the first one that fits runs. There is no fall-through, so no `break` is needed. ### Nested patterns, literals and guards A field can itself be matched with a pattern, a literal or a name: ```nox enum Option[T]: Some(value: T) Nothing enum Token: Word(text: str) Num(n: int) End def deep(o: Option[Option[int]]) -> str: match o: case Option.Some(Option.Some(v)): return "some some " + str(v) case Option.Some(Option.Nothing): return "some nothing" case _: return "nothing" def lit(t: Token) -> str: match t: case Token.Word("end"): return "the end word" case Token.Num(0): return "zero" case Token.Num(n) if n > 100: return "large" case Token.Num(n): return "num " + str(n) case _: return "other" a: Option[Option[int]] = Option.Some(Option.Some(4)) print(deep(a), lit(Token.Word("end")), lit(Token.Num(0)), lit(Token.Num(500)), lit(Token.Num(7)), lit(Token.End)) ``` ```output some some 4 the end word zero large num 7 other ``` - **Nested pattern.** `Option.Some(Option.Some(v))` matches when the outer variant matches and the inner value matches its pattern. - **Literal.** An `int`, `float`, `str` or `bool` literal (including `-1`) matches a field that equals it. - **Guard.** `case P if condition:` runs only when the pattern matches *and* the condition is true; otherwise the next case is tried. The condition can use the names the pattern binds. - **Exhaustiveness.** A guarded case or a case with a literal can fail, so it does not cover its variant. Nested patterns do count when, together, they cover every variant of the inner enum: `Option.Some(Option.Some(v))`, `Option.Some(Option.Nothing)` and `Option.Nothing` is exhaustive. Otherwise finish the `match` with `case _:` (or a plain case for the variant); the error says the variant is "only partly covered". ### Matching plain values `match` also works on an `int`, `float`, `str` or `bool`. A pattern is a literal, several literals joined with `|`, a name that captures the value, or `_`: ```nox def describe(code: int) -> str: match code: case 0: return "ok" case 1 | 2 | 3: return "minor" case -1: return "unknown" case n if n > 100: return "major " + str(n) case _: return "other" print(describe(0), describe(2), describe(-1), describe(404), describe(42)) ``` ```output ok minor unknown major 404 other ``` - A literal case compares with `==`; the cases are tried from top to bottom and the first match runs. - `case name:` binds the value and matches anything (add `if` to limit it); `case _:` matches anything without binding. - Unlike enum matches there is no exhaustiveness check: if no case fits and there is no `case _:`, execution continues after the `match`. - Literal cases and enum-variant cases cannot be mixed in one `match`. ### Exhaustiveness Without a `case _:`, every variant has to appear in some case, otherwise the program does not compile: ```text type error (TypeMismatch): line 7: non-exhaustive match on enum 'E': missing variant(s) C (add the missing case(s) or a `case _:`) ``` Because the compiler proves every variant is handled, a function whose cases all `return` needs no `return` after the `match`. ### Other compile-time checks - the subject's type and the pattern's enum must be the same enum; - the variant must exist, and a positional pattern must bind as many names as the variant has fields. ## Generic enums An enum can have type parameters, like a generic class. `Option` and `Result` need no library: they are ordinary enums. ```nox enum Option[T]: Some(value: T) Nothing def unwrap_or(self, default: T) -> T: match self: case Option.Some(v): return v case Option.Nothing: return default enum Result[T, E]: Ok(value: T) Err(error: E) def first[T](xs: list[T]) -> Option[T]: if len(xs) == 0: return Option.Nothing return Option.Some(xs[0]) def divide(a: int, b: int) -> Result[int, str]: if b == 0: return Result.Err("division by zero") return Result.Ok(a // b) x: Option[int] = Option.Some(5) y: Option[int] = Option.Nothing print(x.unwrap_or(0), y.unwrap_or(7)) nums: list[int] = [4, 5] print(first(nums).unwrap_or(-1)) r: Result[int, str] = divide(1, 0) match r: case Result.Ok(v): print("ok", v) case Result.Err(e): print("error", e) ``` ```output 5 7 4 error division by zero ``` The type arguments come from the arguments of the variant (`Option.Some(5)` is an `Option[int]`) or, when the variant carries nothing that determines them, from the type the value is going to: the annotation of a variable, a parameter, a return type. `print(Option.Nothing)` has no such context and is rejected with a message that says so. ## Limits - A guard can use names, literals, operators, calls, attributes and indexing; lambdas, comprehensions and dictionary literals are not supported inside a guard (compute them in the body). - `match` bindings are not available inside generator functions (`yield`). ## How it works An enum is a class underneath, so every class rule applies (inheritance from an enum is not meant to be used). Each value stores a tag and the fields of its variant; the unused fields of other variants stay empty and are never read. A `match` is a chain of `if` tests on the tag, which is why it costs the same as writing the tests by hand. --- # Protocols and generics Nox has two complementary mechanisms for writing code that works over many types. Both are resolved **at compile time** by monomorphisation — the compiler generates a specialised, dispatch-free copy of the code for every concrete type it is used with. There is no boxing, no type erasure and no run-time cost. ## Generic functions A function becomes generic by listing type parameters in square brackets after its name. The type arguments are inferred from the call: ```nox def first[T](xs: list[T]) -> T: return xs[0] def pair[A, B](a: A, b: B) -> tuple[A, B]: return a, b print(first([1, 2, 3]), first(["a", "b"]), pair(1, "z")) ``` ```output 1 a (1, 'z') ``` Type parameters can be inferred from function-typed arguments too — from the lambda body when the other arguments do not determine them. A type argument can also be given explicitly with `f[int](x)`. A generic function is instantiated only for the types it is actually called with; an unused generic function costs nothing. ```nox def map_list[T, U](xs: list[T], f: (T) -> U) -> list[U]: out: list[U] = [] for x in xs: out.append(f(x)) return out print(map_list([1, 2, 3], lambda v: str(v) + "!")) ``` ```output ['1!', '2!', '3!'] ``` ## Generic classes A class may declare type parameters; every use names the concrete types: ```nox class Box[T]: item: T def __init__(self, item: T) -> None: self.item = item def get(self) -> T: return self.item class Pair[A, B]: a: A b: B def __init__(self, a: A, b: B) -> None: self.a = a self.b = b b: Box[int] = Box[int](5) s: Box[str] = Box[str]("x") p: Pair[int, str] = Pair[int, str](1, "u") print(b.get(), s.get(), p.a, p.b) ``` ```output 5 x 1 u ``` Each distinct instantiation (`Box[int]`, `Box[str]`) is a separate compiled class. The built-in generic types `Task[T]`, `Channel[T]`, `ThreadHandle[T]`, `ThreadChannel[T]` and `ptr[T]` follow the same syntax. ## Generic methods A method of a **non-generic** class can be generic. Call it with an explicit type argument or let it be inferred: ```nox class Picker: def pick[T](self, a: T, b: T) -> T: return a k: Picker = Picker() print(k.pick[int](1, 2), k.pick("x", "y")) ``` ```output 1 x ``` A generic class can have generic methods too. The class parameter is fixed by the receiver (`Box[int]`), the method parameter is bound at the call, explicitly or by inference from the arguments: ```nox class Box[T]: value: T def __init__(self, value: T) -> None: self.value = value def get(self) -> T: return self.value def map_to[U](self, f: (T) -> U) -> Box[U]: return Box[U](f(self.value)) def label(n: int) -> str: return "n=" + str(n) b: Box[int] = Box[int](21) print(b.map_to[str](label).get()) print(b.map_to(label).get()) ``` ```output n=21 n=21 ``` A generic method takes one type parameter. A lambda argument needs the explicit form (`map_to[str](lambda ...)`), because its parameter types are not known until `U` is. ## Protocols A protocol describes the *shape* a type must have; any class with matching methods satisfies it. No declaration of intent (`implements`) is needed — the match is structural. Every method of a protocol has the body `pass`: protocols declare shape, never behaviour. ```nox protocol Shape: def area(self) -> float: pass class Square: s: float def __init__(self, s: float) -> None: self.s = s def area(self) -> float: return self.s * self.s class Circle: r: float def __init__(self, r: float) -> None: self.r = r def area(self) -> float: return 3.0 * self.r * self.r def describe(shape: Shape) -> None: print(shape.area()) describe(Square(2.0)) describe(Circle(1.0)) ``` ```output 4.0 3.0 ``` A function with a protocol-typed parameter is compiled once **per concrete type** that is passed to it (monomorphisation) — `describe` above becomes two direct, non-virtual functions. Passing a class that lacks a required method is a compile error naming the missing method: ```text 'B' class does not satisfy protocol 'Named': method 'name' missing ``` ### Protocols as value types A protocol can also be the type of a variable, a field, a function result or a collection element. This is how a `list[Shape]` holds instances of **different** classes: ```nox protocol Shape: def area(self) -> float: pass def name(self) -> str: pass class Square: s: float def __init__(self, s: float) -> None: self.s = s def area(self) -> float: return self.s * self.s def name(self) -> str: return "square" class Circle: r: float def __init__(self, r: float) -> None: self.r = r def area(self) -> float: return 3.0 * self.r * self.r def name(self) -> str: return "circle" def describe(shape: Shape) -> None: print(shape.name()) shapes: list[Shape] = [Square(2.0), Circle(1.0)] sq: Square = Square(3.0) shapes.append(sq) total: float = 0.0 for s in shapes: total += s.area() describe(s) print(total) ``` ```output square circle square 16.0 ``` Nothing changes in the syntax: you write the protocol name where a type goes and assign any class that has the right methods. The compiler picks the representation: - A parameter of protocol type (`def describe(shape: Shape)`) is still compiled once per concrete type, with direct calls (monomorphisation). `describe(Circle(5.0))` costs the same as before. - A value that is *stored* as a protocol (a list element, a field, a variable, a function result) holds the object together with a table of its protocol methods. Calls through it are dynamic, like calls on a base class. The object is shared, not copied: a change made through `sq` is visible through `shapes[2]`. The conversion happens where a value flows into a protocol-typed place: assignments, list literals, `append`/`insert`, call arguments, `return`. A class that lacks a method is a compile error at that point. A protocol whose methods mention another protocol in their signatures cannot be used as a value type (parameters of such a protocol still work). If you prefer an explicit hierarchy, a common base class gives the same result: see [Classes](https://noxlang.com/docs/language/classes/#inheritance). ## Choosing between them | You want | Use | |---|---| | One algorithm over `int`, `str`, user types… with the same operations | a generic function (`[T]`) | | A container parameterised by element type | a generic class | | "Anything with these methods" for a function parameter | a protocol | | A heterogeneous list with run-time dispatch | a protocol (`list[Shape]`), or a base class and subclasses | --- # Exceptions Nox keeps Python's `try`/`except`/`finally`/`raise` syntax. Exceptions are ordinary **classes**; the error model underneath is not stack unwinding but an implicit **error-return chain** (compare Zig's error unions): a function that can raise is compiled to return either a value or an exception handle, and every call site checks it. No unwind tables or landing pads are ever emitted, so exceptions cost nothing on the success path and work identically on both backends. ## The exception hierarchy `Exception` is the root and is always available. Each instance has a `message: str` and a `line: int` (the source line of the `raise`, filled in automatically). Built-in subclasses: | Class | Raised by | |---|---| | `Exception` | the root; user-raised generic errors | | `ValueError` | bad conversions (`int("x")`), zero slice step, out-of-range shift, `list.remove`/`index` of a missing value | | `IndexError` | list/string index out of range, `pop`/`del` past the end | | `KeyError` | missing dictionary key (`d[k]`, `d.pop(k)`, `del d[k]`) | | `ZeroDivisionError` | integer `//` or `%` by zero, `0 ** negative` | | `AssertionError` | a failed `assert` | | `CancelledError` | a cancelled [task](https://noxlang.com/docs/language/concurrency/) | Standard-library modules define their own subclasses (`JsonError`, `SqliteError`, `NativeError`, `PluginError`, …). > **Diagnostics language.** Compiler diagnostics, built-in runtime errors (`e.message` of an `IndexError`, the uncaught-exception report, type errors) are English. Programs should branch on the exception *class*, never on built-in message text. User-raised messages are whatever you write. ## Raising and defining exceptions `raise` takes an instance of `Exception` or a subclass. Define your own exceptions as subclasses and call `super().__init__(message)`: ```nox class AppError(Exception): code: int def __init__(self, message: str, code: int) -> None: super().__init__(message) self.code = code class NotFound(AppError): pass def find(key: str) -> int: if key == "": raise ValueError("empty key") if key == "x": raise NotFound("no such key", 404) return 1 print(find("a")) ``` ```output 1 ``` ## Catching ```nox class AppError(Exception): code: int def __init__(self, message: str, code: int) -> None: super().__init__(message) self.code = code class NotFound(AppError): pass def find(key: str) -> int: if key == "": raise ValueError("empty key") if key == "x": raise NotFound("no such key", 404) return 1 for key in ["a", "", "x"]: try: print(find(key)) except NotFound as e: print("not found:", e.message, e.code) except (ValueError, KeyError) as e: print("value-ish:", e.message) finally: print("done", key) ``` ```output 1 done a value-ish: empty key done not found: no such key 404 done x ``` Rules: - `except Base:` matches `Base` **and every subclass** (single inheritance), tested in clause order — put specific classes first. - `except (A, B) as e:` matches either class; `except Exception as e:` is a catch-all; a bare `except:` also catches everything. - The bound name (`e`) is scoped like any other local and its class is the *clause's* class (for a tuple clause, the common base, so `e.message` is always available). - `raise` inside an `except` clause raises a new exception (there is no implicit chaining); a bare `raise` re-raise is not supported — raise the bound exception again with `raise e`. - An exception escaping a `finally` body replaces the one in flight (the replaced exception object is reclaimed only when the program exits — avoid raising from `finally` in long-running code). - Exceptions cross `async` boundaries: `await t` re-raises whatever the task raised. ### Uncaught exceptions An exception that escapes the top level terminates the program with exit status 1 after printing the class and source line to standard error. A failed fixed-width overflow or an out-of-range fixed-width conversion is *not* an exception: it terminates the program with a message and cannot be caught. ## `finally` A `finally` body runs when the `try` body finishes normally, when it exits by `return`, `break` or `continue`, and when an exception propagates — exactly once. `try` may have `except` clauses, a `finally`, or both. ### `try … else` An `else:` block after the `except` clauses runs only when the `try` body finished without an exception (and without `return`, `break` or `continue`). Exceptions raised inside the `else` block are *not* caught by the `except` clauses of the same `try`, and a `finally` body, if any, runs after the `else` block: ```nox def parse(text: str) -> None: try: n: int = int(text) except ValueError: print("bad number") else: print("number", n) finally: print("done") parse("42") parse("x") ``` ```output number 42 done bad number done ``` ## `with` `with expr as name:` calls `expr.__enter__()` (its result is bound to `name`), runs the body, and calls `expr.__exit__()` on every way out of the body — normal completion, `return`, `break`, `continue` or an exception. In Nox `__exit__` takes no arguments and cannot suppress an exception. ```nox class Resource: name: str def __init__(self, name: str) -> None: self.name = name def __enter__(self) -> Resource: print("enter", self.name) return self def __exit__(self) -> None: print("exit", self.name) def work() -> int: with Resource("a") as r: print("using", r.name) return 7 print(work()) try: with Resource("b") as r2: raise ValueError("oops") except ValueError as e: print("caught after exit") ``` ```output enter a using a exit a 7 enter b exit b caught after exit ``` A `with` statement can manage several resources: `with a as x, b as y:` is `with a as x:` containing `with b as y:` — `b` is entered after `a` and exited before it. `noxc fmt` writes the nested form. ## Re-raising and chaining A bare `raise` inside an `except` block raises the exception that block caught again (`noxc fmt` keeps the bare form when the clause binds no name; when it does bind one, the formatter writes `raise e`). Outside an `except` block a bare `raise` is a syntax error. `raise X from Y` raises `X` and records `Y.message` in `X.cause` (a `str`, empty for an ordinary `raise`); `raise X from None` is just `raise X`. There is no traceback object, so the cause is the message text. ```nox class AppError(Exception): pass def load(path: str) -> None: try: raise ValueError("bad number") except ValueError as e: raise AppError("could not load " + path) from e try: load("cfg") except AppError as e: print(e.message, "|", e.cause) try: try: raise ValueError("inner") except ValueError: print("cleanup") raise except ValueError as e: print("again:", e.message) ``` ```output could not load cfg | bad number cleanup again: inner ``` ## `defer` `defer call(args)` (Go-style) schedules a call for when the enclosing function exits by any route; several `defer`s run **last in, first out**. Only a call expression is accepted. Deferred arguments are evaluated at the `defer` statement. ```nox def cleanup(s: str) -> None: print("cleanup", s) def run() -> None: defer cleanup("one") defer cleanup("two") print("body") run() ``` ```output body cleanup two cleanup one ``` `finally`, `with`, `defer`, `return`, `break` and `continue` all share the same scope-exit mechanism that releases memory, so cleanup always runs in a single, predictable order. ## `assert` `assert cond, "message"` raises `AssertionError` when `cond` is false; assertions are always compiled in. ## Errors across boundaries Foreign code never sees a Nox exception: at an `extern def` boundary the compiler generates a trampoline that converts the foreign error convention into an exception on return, and fences raw `longjmp`s ([Foreign functions](https://noxlang.com/docs/language/ffi/)). NNI functions report errors through `error_set`, which becomes a `NativeError` ([NNI](https://noxlang.com/docs/apis/nni/)). --- # Concurrency Nox's concurrency model is **tasks and channels**: lightweight fibers started with `spawn`, joined with `await`, and connected by typed channels. Tasks are cheap (a small fixed stack each) and are scheduled by a runtime scheduler; whether they run on one thread or many is a property of the backend and is invisible to the source ([The scheduler](#the-scheduler)). ## Async functions, `spawn` and `await` `async def` declares a function that can run as a task. `spawn f(args)` starts it and immediately returns a `Task[T]`, where `T` is the function's return type. `await task` suspends the caller until the task finishes and yields its result. `await` may be used inside an `async def` and at the top level of a program. ```nox async def square(n: int) -> int: return n * n a: Task[int] = spawn square(6) b: Task[int] = spawn square(7) print(await a + await b) ``` ```output 85 ``` A call to an async function without `spawn` is a compile error: starting a task is always explicit. ### Nested `async def` An `async def` may be written inside another function, which keeps small task bodies next to the code that starts them: ```nox import nox.time async def total(base: int) -> int: scale: int = 10 async def part(i: int) -> int: nox.time.sleep_ms(2) return base + i * scale a: Task[int] = spawn part(1) scale = 100 b: Task[int] = spawn part(2) return await a + await b t: Task[int] = spawn total(5) print(await t) ``` ```output 220 ``` - It is started like any other async function, with `spawn part(...)`; calling it directly or using it as a value is a compile error. - It reads variables of the enclosing function **by value, at the moment of the `spawn`** (above, `a` sees `scale == 10` and `b` sees `100`). Only `int`, `float`, `bool`, `str`, `None` and fixed-width integers can be captured: a task may run on another worker, so a captured `list`, `dict` or class instance is rejected with a message asking you to pass it as a parameter instead. - It cannot assign to captured variables, cannot be generic, and cannot spawn itself (move such a function to module level). ### Failures propagate through `await` If a task raises, the exception is delivered to whoever awaits it — `await` re-raises it, so ordinary `try`/`except` works across tasks: ```nox async def fail() -> int: raise ValueError("task failed") async def run() -> None: f: Task[int] = spawn fail() try: r: int = await f print(r) except ValueError as e: print("caught:", e.message) t: Task[None] = spawn run() await t ``` ```output caught: task failed ``` ### Fire and forget `spawn f(x)` written as a statement starts a task and drops the handle; the task keeps running until it finishes. An exception in a task nobody awaits is not reported, so use this only for work that handles its own errors. ### Cancellation `task.cancel()` requests cancellation. It is **cooperative**: it sets a flag, and the cancelled task gets a `CancelledError` the next time *it* awaits another task. A task that never awaits (pure computation) is not interrupted by itself: put `nox.tasks.checkpoint()` inside the CPU loop (it raises `CancelledError` when cancellation was requested; `nox.tasks.is_cancelled()` asks without raising), and call `nox.time.sleep_ms(0)` now and then so other tasks and timers can run. `h.cancel()` on a `ThreadHandle` sets the same flag for the thread's entry task. The `CancelledError` can be caught inside the task; if it is not, it reaches whoever awaits the task. ```nox async def step() -> int: return 1 async def worker() -> int: total: int = 0 while True: s: Task[int] = spawn step() total += await s return total async def run() -> None: w: Task[int] = spawn worker() w.cancel() try: await w except CancelledError as e: print("worker cancelled") t0: Task[None] = spawn run() await t0 ``` ```output worker cancelled ``` ### Timeouts and waiting for the first of two tasks `t.is_done()` asks, without blocking and without consuming the result, whether the task has finished. `t.wait(ms)` waits cooperatively for it up to `ms` milliseconds and returns whether it finished; `t.wait_any(other, ms)` waits for whichever of the two tasks finishes first and returns `0` (`t`), `1` (`other`) or `-1` (timeout). None of them cancels a task or consumes its result: after a `True`, `await t` returns immediately; after a timeout call `t.cancel()` if the work should stop. ```nox import nox.time async def work(ms: int, v: int) -> int: nox.time.sleep_ms(ms) return v async def run() -> None: slow: Task[int] = spawn work(400, 1) if slow.wait(50): print(await slow) else: print("timed out") slow.cancel() t0: Task[None] = spawn run() await t0 ``` ```output timed out ``` ### Async generators and `async for` An `async def` whose body contains `yield` is an **async generator**. Calling it does not start a task (it is not `spawn`ed): it returns a lazy `AsyncIterator[T]` — the same type as the [`Iterator[T]`](functions.md#generators-yield) of an ordinary generator — and its body may `await`. Consume it with `async for`, which is allowed inside an `async def` and at the top level: ```nox async def double(n: int) -> int: return n * 2 async def numbers(n: int) -> AsyncIterator[int]: for i in range(n): d: int = await spawn double(i) yield d async def total() -> int: t: int = 0 async for v in numbers(5): t += v return t async for x in numbers(3): print("got", x) r: Task[int] = spawn total() print(await r) ``` ```output got 0 got 2 got 4 20 ``` Each value is produced when the loop asks for it, in the loop's own task: the generator's `await`s suspend that task, so a `break` also stops the producer. `async for` needs an async iterator (a generator), not a list; the other limits of generators apply). Because an async generator is not itself a task, it can be passed around like any value, but a *task* (`spawn`ed `async def`) still takes only simple parameters on the QBE backend, so consume generators inside the task that creates them. ### `async with` `async with manager as name:` works like `with`, but calls the methods `__aenter__()` and `__aexit__()` of the manager, which may `await`. Declare them as `async def` methods; they are called directly by the `async with` statement (not spawned), so they take no arguments other than `self`. It is allowed inside an `async def`, at the top level and inside async generators. ```nox async def tick(n: int) -> int: return n + 1 class Conn: def __init__(self, name: str) -> None: self.name: str = name async def __aenter__(self) -> str: t: int = await spawn tick(0) print("open", self.name, t) return self.name + "!" async def __aexit__(self) -> None: print("close", self.name) async def work() -> None: async with Conn("db") as c: print("using", c) t: Task[None] = spawn work() await t ``` ```output open db 1 using db! close db ``` `await` also works inside list and dict comprehensions (`[await spawn f(i) for i in range(3)]`); the awaits run one after another. ## Channels `Channel[T](capacity)` is a typed queue connecting tasks. `await ch.send(v)` suspends while the channel is full; `await ch.recv()` suspends while it is empty. A capacity of `0` is a rendezvous channel: a send completes only when a receiver takes the value. Channels are values you pass to tasks as arguments. ```nox async def producer(ch: Channel[int], n: int) -> None: for i in range(n): await ch.send(i) async def consumer(ch: Channel[int], n: int) -> int: total: int = 0 for i in range(n): total += await ch.recv() return total async def run() -> None: ch: Channel[int] = Channel[int](2) p: Task[None] = spawn producer(ch, 5) c: Task[int] = spawn consumer(ch, 5) await p print(await c) t: Task[None] = spawn run() await t ``` ```output 10 ``` ### Waiting with a timeout `ch.wait(ms)` returns `True` as soon as a `recv` would not block (a value is buffered or a sender is waiting) and `False` if `ms` milliseconds pass first. It does not consume the value: call `await ch.recv()` afterwards. If several tasks receive from the same channel, another one may take the value between `wait` and `recv`; use one receiver per channel when that matters. ```text if ch.wait(500): job: int = await ch.recv() else: print("no work for 500 ms") ``` ### Waiting on several channels (`wait_any`) `a.wait_any(b[, c[, d]], ms)` waits for the first of up to four channels (which may carry different element types) to become receivable. It returns the index of a ready channel (`0` is `a`, `1` is the first argument, and so on) or `-1` if `ms` milliseconds pass first. Like `wait`, it does not consume anything: call `await .recv()` on the channel it names. ```text which: int = jobs.wait_any(control, 1000) if which == 0: job: int = await jobs.recv() elif which == 1: cmd: str = await control.recv() else: print("idle") ``` This is a receive-only, polling-based select (it re-checks every few milliseconds, so the wake-up latency is at most about 4 ms); there are no send cases. ### Fan-out and fan-in There is no `list[Task[T]]` in 2.0 (tasks and channels cannot be stored in collections). The idiom for "start N workers and gather the results" is a channel the workers write to: ```nox async def worker(ch: Channel[int], n: int) -> None: await ch.send(n * n) async def run() -> None: ch: Channel[int] = Channel[int](4) for i in range(4): spawn worker(ch, i) total: int = 0 for i in range(4): total += await ch.recv() print("total", total) t: Task[None] = spawn run() await t ``` ```output total 14 ``` Results arrive in completion order, not spawn order; send an index with the result if order matters. ## Task-local values `TaskLocal[T]` holds one value per running task (`T` must be a `str`, `list`, `dict` or class). `get()` returns `T | None`; `set(v)` and `clear()` change it. It is useful for per-request context in servers. ```nox async def run() -> None: who: TaskLocal[str] = TaskLocal[str]() print(who.get()) who.set("ada") name: str | None = who.get() if name is not None: print(name) who.clear() print(who.get()) t: Task[None] = spawn run() await t ``` ```output None ada None ``` ## Threads For explicit worker threads, `nox.thread` offers `nox.thread.start(fn, arg)` returning a `ThreadHandle[T]` (`await h.join()` yields the result) and `ThreadChannel[T](capacity)` for communicating with it. The module is described in the [standard library](https://noxlang.com/docs/stdlib/thread/). ```nox import nox.thread async def worker(x: int) -> int: return x * 2 async def run() -> None: h: ThreadHandle[int] = nox.thread.start(worker, 21) print(await h.join()) tc: ThreadChannel[int] = ThreadChannel[int](4) await tc.send(7) print(await tc.recv()) t: Task[None] = spawn run() await t ``` ```output 42 7 ``` ## The scheduler All tasks run on fibers scheduled by the runtime: - **Both backends (hosted targets):** an automatic **M:N work-stealing scheduler** — the program's tasks run in parallel on a pool of worker threads. The pool has one worker per CPU by default (since v2.1.142; it was a fixed 2 for programs using only plain `spawn`) and the size can be overridden at run time with the `NOX_POOL_WORKERS` environment variable. **Blocking foreign calls** (a C function such as `usleep`, a blocking database driver) park the whole worker thread. A monitor thread notices when every worker has been busy on the same fiber for ~30 ms while runnable work is queued, and starts an additional worker (up to twice the initial size, at most 64). The extra workers pick up *unstarted* tasks; a task that has already started stays on the worker it began on, so it waits for that worker to return. Growth is off when `NOX_POOL_WORKERS` is set without `NOX_POOL_MAX_WORKERS`, for the WebAssembly targets and for the multi-core server pool. Reference counting is atomic whenever a program uses tasks or threads, so values may safely be shared between tasks on different workers. On the QBE backend (which has no atomic instructions in its IL) the atomic count updates are calls into the runtime, emitted only for programs that use `spawn`, `async`, `nox.thread` or the multi-core pool; other QBE programs keep plain, faster counts. Module-level variables: by default every worker keeps its own copy of them (this is what makes `serve_multicore` handlers independent). **Shared values (all types, no syntax):** lists, dicts, class instances (including inheritance, mixins, `__del__`, `@packed`/`@repr("C")`), closures, `str`, channels/tasks, and any nesting of them can be shared between tasks, held in module-level variables (assigned or reassigned anywhere) and class fields, and handed to `spawn`/channels — the program always runs on the whole worker pool; no program is pinned to one worker. The compiler picks the protection per type, invisibly: - A value becomes **shared** the moment it can be seen by another worker (it is stored in a shared module variable, handed to `spawn`, sent on a channel, returned from a task, or captured by a shared closure). From then on, reading a heap-typed field/element/variable takes a new reference under a short per-object lock, writing one publishes the new value, swaps it under the lock and drops the old value **outside** the lock, and list operations (`append`, `pop`, `insert`, `remove`, `sort`, `[i]`, `[i] = v`, `for`, `in`, `==`, `+`, slices, comprehensions, `print`) are atomic as a whole. User code (`__eq__`, `__repr__`, `__str__`, `__del__`) never runs while a lock is held. - An object that was never shared pays only a flag test. - Memory safety is guaranteed; **compound updates are not atomic**: `x = x + 1`, `d[k] = d[k] + 1`, `xs[i] = xs[i] + 1`, `obj.hits = obj.hits + 1` can lose updates, and unlocked scalar elements of a list may be read while another task appends (Go-style data races on plain numbers, never a crash). Use a channel, `AtomicRef` or `nox.atomic` when you need exact counters. (`scripts/tsan_check.sh` runs the shared-data fixtures under ThreadSanitizer: the lock/barrier paths are race-free; only these documented plain-number races are reported.) - Module-level variables in programs that use `serve_multicore*` / `nox.thread.pool_run` keep the per-worker-copy model (this is what makes handlers independent); module-level constants (numbers and strings assigned once) need nothing. - Hot loops that scan or write the same shared container from many workers are limited by lock contention (like a `sync.Mutex` in Go); work that is mostly computation scales with the worker count (see `benchmarks/mn_shared/`). Setting `NOX_POOL_WORKERS` overrides the worker count. - **Freestanding targets:** a single-threaded cooperative scheduler. Tasks interleave only at `await` points (and at blocking I/O, which is non-blocking at the fiber level); `time.sleep_ms` inside a task suspends only that task. Consequences for portable code: - Do not rely on tasks running in parallel *or* strictly interleaved — write them to be correct under both. - Data shared between tasks should still preferably flow through channels; shared module-level values and class fields are memory-safe (see above) but compound updates are not atomic — use channels, `AtomicRef`, `nox.atomic` counters, or `nox.sharedmem` for exact counters. (With `serve_multicore*` / `nox.thread.pool_run` every worker keeps its own copy of the module state.) - `time.sleep_ms` inside a task (an `async def`, an HTTP handler) suspends only that task on both backends; outside a task (and on Windows) it blocks its thread. - The argument and result types of `spawn`/`nox.thread.start` may be scalars, `str`, `None`, `ptr`, thread channels, lists, dictionaries, class instances, tasks and channels on both backends of hosted targets; freestanding targets are restricted to scalars, `str`, `None`, `ptr` and thread channels. `Optional`, function values and `ThreadHandle` are never accepted. - A listening socket shared by several tasks (for example `serve_fd` called on the same fd from two threads) is closed by whichever task finishes first; use `nox.http.serve_multicore*` for multi-worker servers. ### Fiber stacks Each task runs on a fixed-size fiber stack (192 KiB) with a guard page below it; overflowing it terminates the program instead of corrupting memory. The runtime's own recursive algorithms (class release, cycle collection, JSON) are iterative or depth-limited so they fit comfortably; user code that recurses very deeply should run outside fibers. ## Concurrency and the type system - Ownership stays invisible: values handed to a task are retained for it; a value can be used by several tasks safely under the M:N runtime (atomic reference counts). - Since v2.1.139 the compiler no longer rejects mutating a list/dict/class instance that is shared through `spawn` (the accesses are locked and memory-safe). The old compile-time check is available as a lint: `noxc check --strict-spawn-shared` (also accepted by `build` and `run`). - Network and file operations in the standard library are non-blocking at the fiber level: a task waiting on a socket does not block the worker. --- # Memory There is no ownership syntax anywhere in Nox: no `&`, no `move`, no lifetimes, no `Annotated[...]`, no `read`/`mut`/`owned`. You never free memory and never think about aliasing rules. The compiler chooses the cheapest safe strategy for every value, automatically, and falls back to a more general one — silently, never with an error — whenever it cannot prove the cheaper one correct. ## The ownership pyramid | Layer | Mechanism | When it applies | |---|---|---| | 1 | **Stack / ASAP destructors** | ownership and lifetime are statically provable. Small fixed-size values live on the stack; others are freed at the exact point of last use, with no reference count at all | | 2 | **ARC** (automatic reference counting) | the compiler cannot prove ownership. Retain/release are O(1); values are never deep-copied | | 3 | **Cycle collector** | reference cycles among ARC-managed class instances (a stop-the-world trial-deletion scan in the spirit of Nim's ORC; large scans use several threads, see below), triggered by allocation pressure and at program exit | | 4 | **`lowlevel` blocks** | you opt in to arena allocation (below) | Promotion from layer 1 to layer 2 is silent and is an internal compiler decision, not part of the language semantics: the observable behaviour of a program is the same whichever layer a value ends up in. The analysis is **conservative** — it never decides a value is safe unless it can prove it. What this means for you in practice: - Values are released **deterministically**, at scope exit or earlier — not at some later collection pause. (Operating-system resources such as files and sockets are closed explicitly or with `with`; memory release does not run user code.) - Reference cycles are reclaimed, but only by the cycle collector; a cyclic structure lives until a collection runs or the program ends. - Assignment of a class instance copies the **reference**, never the object. `list`, `dict` and `set` are reference values as well. - Strings are immutable; sharing them is always safe. ## Seeing the compiler's decisions: `noxc explain` `noxc explain file.nox` prints, for every local variable, where it will be allocated and why: ```text mm1.nox:13 xs allocation: stack (40 bytes) reasons: - fixed-size literal list (40 bytes) - does not escape, within size/budget -> stack frame budget: 40 / 24576 bytes (before: 0) mm1.nox:19 h allocation: ARC (heap, reference-counted) reasons: - unknown call target (not a class constructor) -> ARC ``` A small literal list that does not escape is kept on the stack; a class instance returned from a function, stored in a field or captured by a closure is reference counted. You do not need to act on this — it is a tool for understanding performance, never a requirement. `noxc explain --release` shows the decisions for the LLVM backend. ## Reference counting and concurrency On the LLVM backend reference counts are **atomic**, so a value can be shared by tasks running on different worker threads ([Concurrency](https://noxlang.com/docs/language/concurrency/)). On the QBE backend the single-threaded scheduler needs no atomics. Either way, the cycle collector coordinates with the scheduler (all workers pause at a safe point while it runs). ### Measuring reference-count traffic `nox.mem.stats()` counts allocations. To see how many **retain/release operations** a program actually executes, build and run it with `NOX_RC_STATS=1` (a diagnostic; nothing changes when the variable is not set): ```bash NOX_RC_STATS=1 noxc build app.nox -o app NOX_RC_STATS=1 ./app # prints NOXRC lines on stderr when the program exits ``` The output lists inline retain and release counts per heap kind (`str`, `list`, `class`, `dict`, ...) and the totals together with allocation and free counts. Counts are best effort (not atomic), cover the code the compiler emits inline (not retains done inside the runtime), and the build-time variable only affects the hosted backends (not WebAssembly or freestanding). Sampling profilers (`sample`, `perf`) show where the time goes; combining the two tells you whether reference counting or allocation dominates. With `NOX_RC_STATS=1` the exit report also contains `NOXGC` lines: how many cycle collections ran, their total/longest pause and a log2 histogram of pause lengths (`parallel=` counts the collections that ran multi-threaded). ### Pauses with several workers With `serve_multicore` or a thread pool, a cycle collection stops all workers at a **safe point between fibers**. A worker that is inside one long CPU-bound stretch with no I/O, `await` or `yield` cannot reach it, so every other worker waits until that stretch ends. Measured with four workers (`benchmarks/stw_latency`): ordinary requests have a p99 of 1.5 ms and a collection adds nothing visible (max 5.7 ms); with a 300 ms non-yielding handler running and a collection requested at the same time, the p99 of *all* workers becomes about 300 ms. The stall is bounded by the longest non-yielding stretch, not by the size of the heap. If a handler does long pure computation, split it with an `await` between chunks, or keep cyclic data out of that service so no collection is requested. ### Large cyclic garbage The collector also reacts to **bytes**, not only to the number of candidate objects: when the live memory held in large blocks (64 KiB and up — big lists and strings) has grown by 64 MiB since the last collection and cyclic candidates are waiting, the next candidate registration starts a collection. A collection that frees little backs the trigger off (the step doubles, up to 4 GiB), so a large live cyclic structure is not rescanned over and over. Nothing is added to the allocation of small objects or to reference counting; only allocating and freeing a block of 64 KiB or more updates one counter. wasm and freestanding builds do not use it. ### Cycle collector threads The cycle collector stops the world while it runs. When the previous collection visited at least 32 768 objects, the next one splits its mark/scan/collect phases over a few threads (default `min(CPU count, 4)`). Set `NOX_GC_THREADS=1` to force the single-threaded collector, or `NOX_GC_THREADS=` to choose the thread count; `NOX_GC_PAR_MIN=` changes the switch-over threshold. Programs without cyclic data (most servers) never run the collector in steady state, so nothing changes for them. wasm and freestanding builds always use the single-threaded collector. ## `lowlevel` blocks `lowlevel:` gives a block **arena allocation** and, together with `ptr[T]`, raw memory access. It is Nox's analogue of `unsafe`, with one absolute difference: **static typing stays fully mandatory inside `lowlevel`**. The block relaxes only the allocation *strategy*, never the type system. ```nox def compute() -> int: total: int = 0 lowlevel: nums: list[int] = [1, 2, 3, 4, 5] i: int = 0 while i < 5: total = total + nums[i] i = i + 1 return total print(compute()) ``` ```output 15 ``` Rules: - Heap values created inside the block are allocated from a per-block arena that is torn down in one step when the block exits — by falling off the end, `return`, `break`, `continue` or an exception. - A heap-typed value that belongs to the block may not **escape** it: it cannot be stored in a variable declared outside, returned, or passed to a function. The compiler rejects such a program at code generation. Copy the data you need into scalars (or construct a new value outside the block) before leaving it. - `extern def` calls inside `lowlevel` run with full native authority exactly as outside — `lowlevel` does not weaken or strengthen the [trust boundary](https://noxlang.com/docs/language/ffi/#the-trust-boundary). For manual, typed access to memory (kernels, device registers, FFI buffers) see `ptr[T]`, `ptr_read`/`ptr_write`/`ptr_offset`, `adopt`, and the `nox.mem` module ([Foreign functions](https://noxlang.com/docs/language/ffi/), [stdlib](https://noxlang.com/docs/stdlib/mem/)); freestanding builds with a kernel-provided allocator are described in [Freestanding](https://noxlang.com/docs/tools/freestanding/). ## What is not exposed There is no `del x` that frees an object (`del` removes list elements and dictionary entries), no weak references and no way to ask for an object's address from ordinary code. A class may define `__del__`; it runs when the object's last reference goes away (not for objects reclaimed by the cycle collector). Resource cleanup is expressed with `with` (context managers), `defer` and `finally` ([Exceptions](https://noxlang.com/docs/language/exceptions/)), which share one scope-exit mechanism with automatic memory release. --- # Modules and packages ## Programs and modules A **module** is a `.nox` file. A **program** is an entry file plus every module it imports, directly or transitively. All modules of a program are compiled **together as one unit**: there is no separate compilation, no linking of precompiled Nox objects and therefore no ABI to keep stable between your own modules. A **project** is a directory with a `nox.json` manifest: ```json { "name": "demo", "entry": "main.nox", "requires": [] } ``` `noxc init demo` creates one. `name` and `entry` are required; `requires` lists third-party packages (see [Packages](https://noxlang.com/docs/tools/packages/)). Single-file programs need no manifest and can import only the standard library. ## The entry point There is no `main` function. The **top-level statements of the entry file** run in order and form the program. A top-level function named `main` is rejected because the compiler synthesises its own entry symbol with that name. The top-level statements of *imported* modules run too, once, **before** the statements of the module that imports them (modules are merged in dependency order, imports first); keep imported modules to declarations unless you want that side effect. Module-level variable initialisers always run before any other top-level statement. ## `import` ```nox import nox.strings # qualified use: nox.strings.upper(s) from nox.math import sqrt, pi # direct use: sqrt(2.0) from nox.strings import upper as up # alias import nox.time as t # module alias ``` ```nox-fragment import util # /util.nox import app.models # /app/models.nox from app.models import User, greet x: util.Box = util.Box(2) # qualified type names work in annotations y: util.Pair[int] = util.Pair[int](2) # so do generic ones ``` Forms: | Statement | Effect | |---|---| | `import a.b` | makes the module's functions and classes available as `a.b.name(...)` and `a.b.Class` | | `import a.b as m` | the same, under the alias `m` | | `from a.b import x, y` | makes `x` and `y` available unqualified | | `from a.b import x as z` | the same, renamed to `z` | There is no `from … import *`. Imports are static: they must be at the top level of a module, are resolved before anything runs, and an unresolved module is a compile error. Importing the same module twice is harmless. **Cyclic imports are rejected.** ### How names are resolved A dotted module path is looked up in this order: 1. **The standard library** — the `nox.*` modules ([Standard library](https://noxlang.com/docs/stdlib/)). 2. **The current project** — `a/b.nox` under the project root (the directory containing `nox.json`); `import helpers` is `/helpers.nox` and `import utils.mathy` is `/utils/mathy.nox`. 3. **A dependency** — the `alias` of an entry in `requires` is a package name: `import nyx.app` loads module `app` of the package aliased `nyx`. ### Qualified access has two quirks - A module's **functions and classes** can be used qualified (`util.double(4)`, `util.Box`), but its **module-level variables** are read with `from util import LIMIT` — `util.LIMIT` is not valid. - `extern def` functions (raw native bindings, such as `sqrt` in `nox.math`) are never name-mangled, so they are used unqualified after the import — see the notes on each standard-library page. ## Module-level state Variables declared at the top level of a module are **module-level variables**. Functions of the same module read and assign them without any `global` keyword ([Statements](https://noxlang.com/docs/language/statements/#scoping)). Initialisers run before any other top-level statement, in source order. ```nox counter: int = 0 def bump() -> int: counter += 1 return counter print(bump(), bump()) ``` ```output 1 2 ``` A module-level variable that a function reads is initialised before `main` runs. Whatever its initialiser needs comes with it: a variable the initialiser mentions is initialised in the same step, together with the attribute assignments (`cfg.port = 80`) and method calls (`names.append("a")`) on those variables that precede the last such declaration in the file. This is what makes the common "configure, then boot" shape work: ```nox class Config: name: str def __init__(self, name: str) -> None: self.name = name cfg: Config = Config("dev") cfg.name = "prod" label: str = cfg.name + "!" def show() -> None: print(label) show() ``` ```output prod! ``` Statements after the last such declaration, and compound statements such as `if` or `for`, run in `main` after all initialisers. An initialiser may not read a module variable that a function reads but that is declared *after* it; the compiler rejects that with a message naming both variables instead of reading uninitialised memory. ### Module-level state and the multi-core runtime What happens to module variables when several workers run depends on the program (details in [Concurrency](https://noxlang.com/docs/language/concurrency/#the-scheduler)): - In a program that uses `serve_multicore*` or `nox.thread.pool_run`, each worker keeps its **own copy** of module state; that is what makes the handlers independent. Share data between those workers with channels, `nox.atomic` or `nox.sharedmem`. - In every other program, lists, dicts, class instances and the other heap values held in module variables are **shared between tasks** whichever worker runs them, and the program uses the whole worker pool. Access is memory-safe, but compound updates such as `x = x + 1` or `obj.hits = obj.hits + 1` are not atomic: use a channel or `nox.atomic` for exact counters. - This includes plain `nox.http.serve` on the default LLVM backend: connections can be handled by any worker, so shared values stay consistent but plain-number read-modify-write updates can lose increments. Only the variables' own initialisers (and method calls on them up to the last declaration a function reads) run for every worker. The one exception is route registration: `r.get(...)`, `r.post(...)`, `r.use(...)` and the other calls on a [`nox.router.Router`](https://noxlang.com/docs/stdlib/router/) variable that directly follow its declaration (only `def`, `class` and imports may sit between them) also run for every worker, so the usual `router = Router()` / `router.get(...)` layout works. Any other statement placed *after* the last module variable, such as `app.run()` or `db.seed()` on your own objects, runs once, on the main worker. Put setup that every worker needs inside a function and call it from the initialiser: ```nox class Counter: def __init__(self: Counter) -> None: self.n = 0 def build() -> Counter: c: Counter = Counter() c.n = 10 return c counter: Counter = build() def bump() -> int: counter.n = counter.n + 1 return counter.n print(bump()) ``` ```output 11 ``` The same applies to a database connection (open it in the initialiser; each worker then has its own) and to routers: see [`nox.router`](https://noxlang.com/docs/stdlib/router/#using-a-router-with-the-server). ## Packages A package is an ordinary project whose repository can be listed in another project's `requires`. Dependencies are fetched into a cache, pinned to an exact commit in `nox.lock`, and compiled into your program with everything else. The registry, the lock file, `noxc add`, `noxc publish` and the trust implications are in [Packages](https://noxlang.com/docs/tools/packages/) and [The noxpkg registry](https://noxlang.com/docs/tools/noxpkg/). A package that declares `extern def` bindings runs native code with full authority — see [Security](https://noxlang.com/docs/reference/security/). ## Visibility By default all top-level names of a module are importable; Nox has no `public`/`private` keywords. By convention a leading underscore marks a name as internal, and names beginning with `__nox_` belong to the compiler's prelude. A leading-underscore name is not hidden from importers. ### `__all__`: an explicit public API A module that wants the compiler to enforce its public API declares a top-level list of string literals: ```text # mylib/util.nox __all__: list[str] = ["public_add", "Box"] def public_add(a: int, b: int) -> int: return _helper(a) + b # the module itself can use everything def _helper(a: int) -> int: ... def internal_only(a: int) -> int: ... class Box: ... class Hidden: ... ``` From **another module**, `util.internal_only(...)`, `util.Hidden(...)`, an annotation `util.Hidden`, and `from util import internal_only` are then compile errors: `'internal_only' is not part of the public API of module 'util' (it is not listed in that module's __all__)`. The listed names work exactly as before. - The list applies to top-level **functions and classes** (the names the compiler qualifies by module). It is opt-in: a module without `__all__` keeps exporting everything, so existing code is unaffected. - Every listed name must be a function or class defined in that module; a typo is an error (`__all__ of module 'util' lists 'nope', which is not a function or class defined there`), not a silently hidden name. - `__all__` must be a plain list of string literals; it is read at compile time and is not a runtime variable. - This is compile-time API hygiene, not a security boundary: it does not change what is linked into the program. --- # Decorators and reflection A decorator is a line starting with `@` immediately before a `def`, a method or a `class`. In Nox decorators are **metadata, not wrappers**: the compiler records *which* declaration was decorated, with *which* literal arguments, and does **not** interpret the meaning or rewrite the function. A framework (or your own code) reads the recorded metadata through `nox.reflect` and decides what it means. This keeps the language small and the behaviour static — nothing is wrapped at run time. ```text @name a decorator without arguments @name("path", 5, True) with literal arguments @name(["admin", "ops"]) a list of string literals @ffi.escape("xs") dotted names are allowed ``` Decorator arguments must be **literals**: strings, integers, booleans or a list of string literals. Nested or computed arguments are a compile error. ## What can be decorated | Target | Notes | |---|---| | top-level `def` | recorded with its parameters and return type; if it has the exact signature `(Context) -> HttpResponse` it is also usable as a handler | | `class` | recorded with the parameters of its `__init__` | | method | recorded with the method's parameters (without `self`) and the owning class | | `extern def` | the compiler-interpreted `@ffi.*` and `@capability.requires` decorators ([Foreign functions](https://noxlang.com/docs/language/ffi/)) | A few decorator names **are** interpreted by the compiler, because they describe how to compile rather than what to do: | Decorator | On | Meaning | |---|---|---| | `@repr("C")` | class | natural C field alignment and padding ([Classes](https://noxlang.com/docs/language/classes/#layout-control-for-foreign-code)) | | `@packed` | class | no padding between fields | | `@dataclass`, `@derive("order", "copy", "json")` | class | the compiler generates `__init__`, ordering, `copy` and JSON methods from the fields ([Classes](https://noxlang.com/docs/language/classes/#generated-methods-dataclass-and-derive)) | | `@ffi.escape("p", …)`, `@ffi.noescape("p", …)` | `extern def` | which pointer arguments the native code may retain | | `@ffi.callback("cb", "userdata")` | `extern def` | Nox function passed as a C callback | | `@ffi.errors(raises=E, ok=0 \| ok_min=0 \| null_is_error=True, errno=True, message="fn")` | `extern def` | turns the C error convention into a Nox exception | | `@capability.requires("clock")` | `def`/`extern def` | the function needs a runtime capability ([Freestanding](https://noxlang.com/docs/tools/freestanding/)) | Every other decorator name is yours. ## Reading metadata: `nox.reflect` `nox.reflect` is the query API. Every decorator occurrence in the program is a numbered *record*; `decorator_count()` says how many exist and the accessors below take the record index `i`: | Function | Result | |---|---| | `decorator_name(i)` | the decorator's name (`"get"`) | | `decorator_kind(i)` | what it decorates: `0` function, `1` class, `2` method | | `decorator_target_name(i)` | the function, class or method name | | `decorator_owner(i)` | the owning class of a method record (empty otherwise) | | `decorator_arg_count(i)` | number of arguments | | `decorator_arg_kind(i, j)` | per-argument kind: `0` string, `1` int, `2` bool, `3` string list | | `decorator_arg(i, j)`, `decorator_arg_int(i, j)`, `decorator_arg_bool(i, j)` | the argument value | | `decorator_arg_list_len(i, j)`, `decorator_arg_list_item(i, j, k)` | a list argument | | `decorator_param_count(i)`, `decorator_param_name(i, k)`, `decorator_param_type(i, k)`, `decorator_return_type(i)` | the decorated declaration's signature (informational) | | `class_count()`, `class_name(i)`, `class_init_param_count(i)`, `class_init_param_name(i, k)`, `class_init_param_type(i, k)`, `class_index(name)` | every class's `__init__` signature — enough for a framework to write its own dependency-injection wiring | | `decorator_is_handler(i)`, `decorator_handler(i)` | for `kind == 0` records with a `(Context) -> HttpResponse` signature, the function as a callable value | | `router_from_decorators()` | builds a `nox.router.Router` from `@get`/`@post`/`@put`/`@delete` handlers (a small example consumer) | Asking an accessor for an argument kind it does not hold (for example `decorator_arg_bool` on an int) returns a safe default (`0`, `False`, `""`) instead of failing. ```nox import nox.reflect @controller("/users", 2, True) class UserController: def __init__(self, prefix: str) -> None: self.prefix = prefix @get("/:id") def show(self, id: int) -> str: return "x" @post("/") @auth(["admin", "ops"]) def create(self, body: str, n: int) -> bool: return True def find(kind: int, name: str) -> int: n: int = nox.reflect.decorator_count() i: int = 0 while i < n: if nox.reflect.decorator_kind(i) == kind and nox.reflect.decorator_name(i) == name: return i i = i + 1 return -1 c: int = find(1, "controller") print(nox.reflect.decorator_target_name(c), nox.reflect.decorator_arg(c, 0), nox.reflect.decorator_arg_int(c, 1), nox.reflect.decorator_arg_bool(c, 2)) g: int = find(2, "get") print(nox.reflect.decorator_owner(g) + "." + nox.reflect.decorator_target_name(g), nox.reflect.decorator_arg(g, 0)) a: int = find(2, "auth") print(nox.reflect.decorator_arg_list_len(a, 0), nox.reflect.decorator_arg_list_item(a, 0, 1), nox.reflect.decorator_param_count(a)) ``` ```output UserController /users 2 True UserController.show /:id 2 ops 2 ``` A *method* decorator makes the method a candidate handler; to call it the framework uses the bound-method value `obj.method` ([Functions](https://noxlang.com/docs/language/functions/#bound-methods)) after constructing the class itself, using the recorded `__init__` parameters. ## `noxc expand` `noxc expand file.nox` prints the decorator metadata the compiler extracted from a file — the same data `nox.reflect` serves — which is handy for debugging a framework's decorators. ## Limits - Decorators never run code and never change a function's signature or behaviour. - Only literal arguments are recorded; there is no decorator composition. - Generic classes and functions are not reflected. - Metadata for a package's decorators is included when the package is imported. --- # Foreign functions Nox calls native code through **`extern def`**: a declaration of a function implemented outside Nox — in C, Zig, Rust (with a C ABI), or the system libraries — callable from Nox with normal static typing at the boundary. This page covers `extern def`, raw pointers, callbacks and the trust boundary. For richer integrations see [the three APIs](https://noxlang.com/docs/apis/): the **Nox Native Interface** for plugins that keep the runtime's data structures private, and the HPy/WASM bridges in [Internals](https://noxlang.com/docs/internals/hpy-wasm/). For a whole C library, [`noxc bindgen`](https://noxlang.com/docs/tools/bindgen/) writes the declarations for you from its header. ## `extern def` ```nox extern def malloc(n: int) -> ptr from "c" extern def free(p: ptr) -> None from "c" extern def sqrt(x: float) -> float from "m" ``` ```text extern def NAME(PARAMS) -> RETURN from "LIBRARY" [retains(p1, p2)] ``` (`with_rt`, which passes the hidden runtime-state pointer as the first argument, exists for the standard library's own runtime shims and is not meant for user code.) `from "LIBRARY"` says where the symbol lives: - a **file path** (it contains `/` or ends in `.o` / `.a`) — an object or archive that is passed to the linker: `from "./add.o"`, `from "build/libfoo.a"`; - otherwise a **system library name**, linked as `-l`: `"m"` (libm), `"c"`, `"sqlite3"`. A relative file path is looked up in the **current directory** first, so `noxc run examples/app/main.nox` from the project root finds `native/libfoo.o`. If it is not there, `noxc` looks in the **project root** (the directory with `nox.json`) and passes the file to the linker by absolute path, so `cd examples/app && noxc run main.nox` works too. The search stops at the project root: it never walks into parent directories, and a script without a `nox.json` keeps the plain current-directory behaviour. An absolute path is used as written. The function name is the C symbol and is **never mangled**, so `extern def` functions are called unqualified after an import ([Modules](https://noxlang.com/docs/language/modules/#qualified-access-has-two-quirks)). A library used by several declarations is linked once. ### Type mapping | Nox | C ABI | |---|---| | `int` | `int64_t` | | `float` | `double` | | `bool` | integer `0`/`1` | | `str` | `const char*` — NUL-terminated UTF-8, valid for the duration of the call | | `None` (return) | `void` | | `u8 … u64`, `i8 … i64`, `usize`, `isize` | the same-width C integer (`uint8_t`, …) | | `ptr`, `ptr[T]` | `void*` / `T*` | | `(P…, ptr) -> R` | a C function pointer, see [Callbacks](#callbacks) | | `dict[str, str]` | an opaque handle (runtime shims only) | Only these types may cross the boundary; classes, lists, `Optional` values and so on are rejected at compile time. The *return* of a `str` from native code is reserved for the runtime's own shims (the string must be built with the runtime's allocator); plugins that need to return text use the [Nox Native Interface](https://noxlang.com/docs/apis/nni/). ```nox extern def malloc(n: int) -> ptr from "c" extern def free(p: ptr) -> None from "c" def demo() -> int: total: int = 0 lowlevel: raw: ptr = malloc(16) p: ptr[i32] = ptr[i32](ptr_to_int(raw)) ptr_write(ptr_offset(p, 0), i32(7)) ptr_write(ptr_offset(p, 1), i32(35)) total = int(ptr_read(ptr_offset(p, 0))) + int(ptr_read(ptr_offset(p, 1))) free(raw) return total print(demo()) ``` ```output 42 ``` A call to a native function that returns a fixed-width integer keeps its type (`print(f(u8(41)))` prints `42`). ### Calling your own native code ```text // add.c — cc -c add.c -o add.o #include int64_t c_add(int64_t a, int64_t b) { return a + b; } ``` ```nox-fragment extern def c_add(a: int, b: int) -> int from "add.o" print(c_add(2, 40)) # 42 ``` The same mechanism links a Zig object (`zig build-obj`), a static archive, or a system library — to Nox they are indistinguishable. ### Ownership across the call: `retains` and `@ffi.escape` By default the compiler assumes native code **does not keep** the pointers and strings it is given beyond the call, so Nox values may be freed or reused immediately after. If a function stores an argument (a registry, a handle that outlives the call), list the parameter in `retains(…)` or decorate the declaration with `@ffi.escape("param", …)`; `@ffi.noescape("param")` states the default explicitly. Contradictory annotations are a compile error. ```nox-fragment extern def take_list(xs: list[int]) -> None from "libexample.a" retains(xs) @ffi.escape("xs") extern def keep_ref(xs: ptr) -> None from "libexample.a" ``` ### Errors An `extern def` call has no exception channel of its own, but most C APIs follow one of three conventions. Declare which with **`@ffi.errors`** and every call raises a Nox exception on failure instead of returning a code you must remember to check: ```nox-fragment class SysError(Exception): pass def describe(code: int) -> str: return "code " + str(code) @ffi.errors(raises=SysError, ok=0, errno=True, message="describe") extern def chdir(path: str) -> int from "c" # 0 = success, -1 = failure with errno set @ffi.errors(raises=SysError, ok_min=0) extern def dup(fd: int) -> int from "c" # >= 0 = success @ffi.errors(raises=SysError, null_is_error=True, errno=True) extern def fopen(path: str, mode: str) -> ptr from "c" # NULL = failure ``` | Argument | Meaning | |---|---| | `raises=E` | the exception class raised on failure (required); it is built from one message string | | `ok=V` / `ok_min=V` / `null_is_error=True` | the success test, **exactly one**: result `== V`; result `>= V`; result is not NULL/0 | | `errno=True` | append `strerror(errno)` to the message (needs `import nox.ffi`; the value is read right after the call) | | `message="fn"` | append `fn(code)` where `def fn(code: int) -> str` is a top-level function of yours | The raised message reads `chdir failed (code -1): describe(-1): No such file or directory`. The result type must be an integer (`ok=`/`ok_min=`) or a `ptr`/integer (`null_is_error=True`); `@ffi.errors` cannot be combined with `@ffi.callback`. Calls are compiled through a small wrapper the compiler writes for you, so the raw declaration keeps its C symbol name. For APIs with other conventions (an out-parameter, a separate `get_last_error()`), wrap the call in a Nox function that checks it and raises. ## Callbacks Native code may call back into Nox through an ordinary top-level function, using the **trailing-userdata convention** that most C libraries (`qsort_r`, GLib, libuv) follow: the callback's last parameter is a `void*` that the library hands back untouched. Mark the declaration with `@ffi.callback("cb", "userdata")`, naming the callback parameter and the `userdata` parameter; the compiler fills `userdata` itself (you do **not** write that argument at the call site) and generates the trampoline. ```nox-fragment def add_ints(a: int, b: int) -> int: return a + b @ffi.callback("cb", "userdata") extern def c_apply(cb: (int, int, ptr) -> int, a: int, b: int, userdata: ptr) -> int from "add.o" print(c_apply(add_ints, 3, 4)) ``` Rules: the callback type's last parameter must be `ptr`; every parameter and the result must be `int`, `float`, `bool` or `ptr`; the target must be a plain top-level, non-`async`, non-`extern` `def`, passed by name, **or** a `nox.ffi.Callback[F]` handle that wraps a lambda, closure or bound method (see below). An exception escaping the callback terminates the program. The userdata does not have to be the callback's last parameter: `@ffi.callback("cb", "userdata", ud_index=0)` says it is parameter 0 of the callback type (C APIs such as `sqlite3_exec` put it first). Pass `None` where the callback goes to give the library a NULL function pointer (and a NULL userdata) when it accepts "no callback". ### Stored callbacks The native side may keep the callback and call it **later**, from any later point of the program: register it in one call (`reg_set(on_event)`), fire it from another (`reg_fire(20)`), replace it by registering a different function. The compiler passes the same hidden `userdata` both times, so nothing else is needed. Two rules keep this safe: call the stored function **only on a thread Nox started** (the main thread or one of its own worker threads) — never from an OS thread the native library created itself — and **never after the program has finished** (an event loop that outlives `main`). To pass a **lambda, closure or bound method**, wrap it in a `nox.ffi.Callback[F]` handle and give the handle where the callback goes; close it with `close()` when the library is done with it ([`nox.ffi`](https://noxlang.com/docs/stdlib/ffi/)). ## Raw pointers `ptr` is an opaque address; `ptr[T]` is a typed address. They are only usable in [`lowlevel`](https://noxlang.com/docs/language/memory/#lowlevel-blocks) code and exist for FFI, kernels and device access: | Operation | Meaning | |---|---| | `ptr[T](addr)` | a typed pointer from an `int` address | | `ptr_to_int(p)`, `ptr_from_int(n)` | address ↔ integer | | `ptr_offset(p, i)` | `p + i` elements (typed) | | `ptr_read(p)`, `ptr_write(p, v)` | typed load / store | | `ptr_read_volatile`, `ptr_write_volatile` | loads/stores the optimiser must not elide (memory-mapped I/O) | | `memory_fence()`, `compiler_fence()` | ordering barriers | | `ptr_of(xs)` | the data pointer of a `list[int]`, `list[float]` or a list of fixed-width integers, as `ptr[T]` — zero-copy hand-over to native code (see below) | | `detach(x)`, `adopt(p)` | turn a managed object into a raw pointer, and take a raw pointer back as a managed object of a given class | Typed reads and writes are type-checked: `ptr_write(p, v)` requires `v` to have the pointee type. The [`nox.mem`](https://noxlang.com/docs/stdlib/mem/) module wraps the common patterns (`copy`, `move`, `set`, volatile access) so ordinary code rarely needs a `lowlevel` block of its own. ### Passing a list to native code without copying `ptr_of(xs)` (inside `lowlevel`) gives the address of a list's elements, laid out contiguously at their natural width (`list[int]` as 8-byte integers, `list[u8]` as bytes, `list[float]` as doubles, and so on), typed as `ptr[T]`. Native code can then read or fill the list in place: ```nox-fragment extern def memset(p: ptr, c: int, n: int) -> ptr from "c" buf: list[u8] = [u8(0), u8(0), u8(0), u8(0)] lowlevel: memset(ptr_from_int(ptr_to_int(ptr_of(buf))), 255, 4) print(buf[0]) # 255 ``` Rules: the argument must be a variable or a field (not a call result, whose list would be freed with the temporary); only `list[int]`, `list[float]` and lists of fixed-width integers are accepted. The pointer is valid until the list is released **or grows** (`append` moves the elements to a bigger buffer; the list itself stays put, so call `ptr_of` again after growing), exactly like any other `lowlevel` pointer, and lies inside the [trust boundary](#the-trust-boundary). Compared with copying the elements into a native buffer, this costs nothing per element (0.08 ns/element against 0.36 ns in the FFI benchmark). ## Sizes and layouts `sizeof(T)`, `alignof(T)` and `offsetof(T, "field")` work for every type; `@repr("C")` and `@packed` give classes a defined layout to share with C structs ([Classes](https://noxlang.com/docs/language/classes/#layout-control-for-foreign-code)). ## The trust boundary **`extern def` is raw native code execution.** The compiler marshals types and tracks reference counts around the call, but it cannot constrain what the native function does: it runs with the full authority of the process — memory access, files, network — outside Nox's type and ownership guarantees. Consequently: - A bug in native code (bad alignment, an out-of-bounds write, retaining a pointer it was told not to) can corrupt the whole program. - `lowlevel` blocks are part of the same boundary: they relax the allocation strategy, but `extern def` calls inside them are no safer. - A **dependency** listed in `nox.json` may declare its own `extern def`s; adding it means trusting its native code ([Security](https://noxlang.com/docs/reference/security/)). - The standard library's `nox.fs` and `nox.os` perform no path validation; sanitise untrusted paths yourself. Nox deliberately has no "safe mode" for `extern def` in 2.0 — a sandbox needs a dedicated security design. ## Other foreign-code mechanisms - **Nox Native Interface (NNI)** — a stable C ABI with opaque handles for plugins that must not depend on the runtime's layouts ([NNI](https://noxlang.com/docs/apis/nni/), [Plugin API](https://noxlang.com/docs/apis/plugin-api/)). - **HPy / CPython extensions** — Python C extensions load through an opaque-handle compatibility layer; a raw `PyObject*` never crosses ([Internals](https://noxlang.com/docs/internals/hpy-wasm/)). - **WebAssembly** — a WASM module can be imported like a native library; importing a WASM module is separate from compiling Nox *to* WASM (`--target wasm32-wasi`, [WebAssembly](https://noxlang.com/docs/tools/wasm/)). --- # Built-in functions The **prelude** is everything available without an `import`. It consists of compiler built-ins and a small set of functions and classes written in Nox itself (`stdlib/nox/core.nox`, merged into every program). Names beginning with `__nox_` are internal. ## Output and input | Function | Description | |---|---| | `print(*values, sep=" ", end="\n")` | prints its arguments separated by `sep` and followed by `end`; with no arguments prints a blank line. Each value is rendered like `str(value)` (containers structurally) | | `input() -> str` | reads one line from standard input (without the newline); an empty string at end of input | ```nox print("a", "b", sep="-", end="!\n") print() print([1, 2], {"k": 1}, (1, "x"), None, 2.0) ``` ```output a-b! [1, 2] {'k': 1} (1, 'x') None 2.0 ``` ## Conversions | Function | Description | |---|---| | `int(x)` | from `float` (truncating), `str` (decimal; `ValueError` if malformed), `bool`, fixed-width integer | | `int(s, base)` | parses `s` in base 2–36 (or 0: from the `0x`/`0o`/`0b` prefix); sign, surrounding spaces, a matching prefix and single `_` between digits are accepted; `ValueError` otherwise | | `hex(n)`, `oct(n)`, `bin(n)` | `'0xff'`, `'-0o17'`, `'0b101'` | | `float(x)` | from `int`, `bool`, fixed-width integer, `str` | | `str(x)` | text of an `int`, `float`, `bool`, `str`, list, dict, set, tuple or class (uses `__str__`) | | `repr(x)` | like `str`, with strings quoted (uses `__repr__`) | | `bool(x)` | truthiness of `bool`, `int`, `float`, `str`, `list`, `dict` or a class (`__bool__`, `__len__`) | | `list(x)` | a new list from `range(...)`, a list (copy), a `str` (its characters) or a `dict` (its keys) | | `chr(cp)`, `ord(s)` | code point ↔ one-character string (`chr(0)` is the NUL character; a negative, surrogate or out-of-range `cp` gives `""`) | | `u8(x)`, `i32(x)`, … | fixed-width integer conversions (range-checked) | | `format(value, spec)` | formats one value with the [format mini-language](https://noxlang.com/docs/language/strings/#the-format-mini-language) | ## Sizes and sequences | Function | Description | |---|---| | `len(x)` | number of elements of a `str` (code points), list, dict, set or tuple, or `__len__` of a class | | `range(stop)`, `range(start, stop[, step])` | integer progression, usable in `for`, comprehensions and `list(...)` | | `enumerate(xs)`, `enumerate(xs, start)` | a list of `(index, element)` tuples; the index begins at `start` (default 0) | | `zip(a, b)`, `zip(a, b, c)` | a list of pairs (triples), as long as the shortest input | | `reversed(xs)` | a **new list** in reverse order (not a lazy iterator) | | `sorted(xs, key=f, reverse=False)` | a new sorted list; stable; without `key` the elements must be `int`, `float` or `str` | | `map(f, xs)`, `filter(f, xs)` | a **new list** (not lazy) | | `any(bs)`, `all(bs)` | over a `list[bool]` | ```nox xs: list[int] = [3, 1, 2] print(sorted(xs), sorted(["b", "a"], reverse=True), sorted(xs, key=lambda n: -n)) print(list(reversed(xs)), list(range(3)), list("ab"), list({"k": 1})) print(enumerate(["a", "b"]), zip([1, 2], ["x", "y"])) print(map(lambda n: n + 1, [1, 2]), filter(lambda n: n > 1, [1, 2, 3])) print(any([False, True]), all([True, False])) ``` ```output [1, 2, 3] ['b', 'a'] [3, 2, 1] [2, 1, 3] [0, 1, 2] ['a', 'b'] ['k'] [(0, 'a'), (1, 'b')] [(1, 'x'), (2, 'y')] [2, 3] [2, 3] True False ``` `xs.sort()` sorts in place and accepts `reverse=` and `key=` as well. ## Numbers | Function | Description | |---|---| | `abs(x)` | absolute value of an `int` or `float` | | `min(a, b, ...)`, `max(a, b, ...)` | of two or more numbers or strings (all arguments the same type) | | `min(xs)`, `max(xs)`, with `key=f` | of a list; `ValueError` when the list is empty | | `min(xs, default=d)`, `max(xs, default=d)` | like above, but `d` is returned for an empty list (also combines with `key=f`) | | `sum(xs)`, `sum(xs, start)` | sum of a `list[int]` or `list[float]` (plus `start`, default 0); also accepts a generator expression | | `pow(a, b)` | `a ** b`: `int, int` gives an `int` (`ValueError` for a negative exponent — use floats), `float, float` a `float` | | `pow(a, b, m)` | modular power of ints with a 128-bit intermediate (`b >= 0`, `m != 0`); the result has the sign of `m` like Python | | `round(x)` | nearest `int`, halves to even | | `round(x, n)` | a `float` rounded to `n` digits, using the exact binary value like Python | | `divmod(a, b)` | the tuple `(a // b, a % b)` | ```nox print(sum([1, 2, 3]), sum([1.5, 2.5]), sum(x * x for x in [1, 2])) print(max([3, 9, 2]), min(["b", "a"]), max(["aa", "b"], key=lambda s: len(s)), min(4, 2), max(1.5, 0.5)) print(abs(-4), abs(-1.5), round(2.567, 1), divmod(17, 5), divmod(-7, 2)) ``` ```output 6 4.0 5 9 a aa 2 1.5 4 1.5 2.6 (3, 2) (-4, 1) ``` ## Memory, layout and low-level helpers `sizeof(T)`, `alignof(T)`, `offsetof(T, "field")` ([Foreign functions](https://noxlang.com/docs/language/ffi/)); `ptr_*`, `detach`, `adopt` (inside `lowlevel`). ## Prelude classes `Exception`, `ValueError`, `IndexError`, `KeyError`, `ZeroDivisionError`, `AssertionError`, `CancelledError`, `HPyError`, and `JsonValue` (the node type of [`nox.json`](https://noxlang.com/docs/stdlib/json/)). The generic types `Task[T]`, `Channel[T]`, `TaskLocal[T]`, `ThreadHandle[T]` and `ThreadChannel[T]` are built in ([Concurrency](https://noxlang.com/docs/language/concurrency/)). ## What is not built in `isinstance`, `type`, `id`, `hash`, `open`, `getattr`/`setattr`, `eval`/`exec`, `iter`/`next`, `print(file=…)`, and `%` string formatting. File access is [`nox.fs`](https://noxlang.com/docs/stdlib/fs/); dynamic attribute access does not exist by design. --- # Grammar A compact grammar of Nox. It is descriptive, not normative — the parser in `compiler/parser/` is the definition — and it omits the lexical details in [Lexical structure](https://noxlang.com/docs/language/lexical/). Notation: `A B` sequence, `A | B` choice, `[A]` optional, `{A}` zero or more, `(…)` grouping, quoted text is literal, `NEWLINE`, `INDENT`, `DEDENT` come from the lexer. ## Program and statements ```text program = { statement } ; block = NEWLINE INDENT statement { statement } DEDENT | simple_stmts NEWLINE ; (* one-line body: `if x: y(); z()` *) statement = simple_stmts NEWLINE | compound_stmt ; simple_stmts = simple_stmt { ";" simple_stmt } [ ";" ] ; simple_stmt = var_decl | infer_decl | assignment | aug_assignment | tuple_assignment | expr | type_alias | unpack_assign | "pass" | "..." | "global" NAME { "," NAME } | "break" | "continue" | "return" [ expr { "," expr } ] | "raise" [ expr [ "from" expr ] ] | "del" target | "assert" expr [ "," expr ] | "defer" call | import_stmt ; var_decl = NAME ":" type "=" expr ; infer_decl = NAME ":=" expr ; (* function/method locals only *) assignment = target "=" expr ; aug_assignment = target aug_op expr ; aug_op = "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**=" | "&=" | "|=" | "^=" | "<<=" | ">>=" ; tuple_assignment = target "," target { "," target } "=" expr { "," expr } ; unpack_assign = unpack_target { "," unpack_target } "=" expr ; (* one "*name"; "(a, b)" nests *) unpack_target = [ "*" ] target | "(" unpack_target { "," unpack_target } ")" ; type_alias = "type" NAME "=" type ; (* module level *) target = NAME | target "." NAME | target "[" expr "]" ; import_stmt = "import" dotted [ "as" NAME ] | "from" dotted "import" import_name { "," import_name } ; import_name = NAME [ "as" NAME ] ; dotted = NAME { "." NAME } ; compound_stmt = if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | lowlevel_stmt | match_stmt | func_def | class_def | enum_def | protocol_def | extern_def ; if_stmt = "if" expr ":" block { "elif" expr ":" block } [ "else" ":" block ] ; while_stmt = "while" expr ":" block [ "else" ":" block ] ; for_stmt = "for" for_target "in" expr ":" block [ "else" ":" block ] ; for_target = NAME | NAME "," NAME ; try_stmt = "try" ":" block { except_clause } [ "else" ":" block ] [ "finally" ":" block ] ; except_clause = "except" [ ( dotted | "(" dotted { "," dotted } ")" ) [ "as" NAME ] ] ":" block ; with_stmt = "with" expr [ "as" NAME ] { "," expr [ "as" NAME ] } ":" block ; lowlevel_stmt = "lowlevel" ":" block ; match_stmt = "match" expr ":" NEWLINE INDENT case_clause { case_clause } DEDENT ; case_clause = "case" ( "_" | pattern ) ":" block ; pattern = dotted [ "(" [ pat_arg { "," pat_arg } ] ")" ] ; pat_arg = ( NAME | "_" ) | NAME "=" ( NAME | "_" ) ; ``` ## Definitions ```text decorator = "@" dotted [ "(" [ literal { "," literal } ] ")" ] NEWLINE ; func_def = { decorator } [ "async" ] "def" NAME [ type_params ] "(" [ params ] ")" "->" type ":" block ; type_params = "[" NAME { "," NAME } "]" ; params = param { "," param } ; param = "self" [ ":" type ] | NAME ":" type [ "=" default ] ; default = literal | "-" number | "None" ; class_def = { decorator } "class" NAME [ type_params ] [ "(" dotted ")" ] ":" NEWLINE INDENT [ docstring ] { field_decl | func_def | "pass" } DEDENT ; field_decl = NAME ":" type NEWLINE ; enum_def = "enum" NAME ":" NEWLINE INDENT [ docstring ] { variant | func_def | "pass" } DEDENT ; variant = NAME [ "(" NAME ":" type { "," NAME ":" type } ")" ] NEWLINE ; protocol_def = "protocol" NAME ":" NEWLINE INDENT { method_sig } DEDENT ; method_sig = "def" NAME "(" [ params ] ")" "->" type ":" NEWLINE INDENT "pass" NEWLINE DEDENT ; extern_def = { decorator } "extern" "def" NAME "(" [ params ] ")" "->" type "from" STRING [ "with_rt" ] [ "retains" "(" NAME { "," NAME } ")" ] ; ``` ## Types ```text type = base_type [ "|" "None" ] ; base_type = NAME (* int float bool str None, class, protocol, u8 … *) | NAME "[" type { "," type } "]" (* list[T] dict[K,V] set[T] tuple[A,B] Task[T] Channel[T] ptr[T] Box[int] *) | "(" [ type { "," type } ] ")" "->" type (* function type *) | dotted ; (* qualified class name: util.Box *) ``` ## Expressions Listed from loosest to tightest binding: ```text expr = lambda | conditional ; lambda = "lambda" [ NAME { "," NAME } ] ":" expr ; conditional = or_expr [ "if" or_expr "else" expr ] ; or_expr = and_expr { "or" and_expr } ; and_expr = not_expr { "and" not_expr } ; not_expr = "not" not_expr | comparison ; comparison = bit_or { comp_op bit_or } ; comp_op = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not" "in" | "is" | "is" "not" ; bit_or = bit_xor { "|" bit_xor } ; bit_xor = bit_and { "^" bit_and } ; bit_and = shift { "&" shift } ; shift = sum { ( "<<" | ">>" ) sum } ; sum = term { ( "+" | "-" ) term } ; term = factor { ( "*" | "/" | "//" | "%" ) factor } ; factor = ( "-" | "+" | "~" ) factor | power ; power = postfix [ "**" factor ] ; postfix = atom { "." NAME | "[" subscript "]" | "[" type_args "]" | "(" [ args ] ")" } ; subscript = expr | [ expr ] ":" [ expr ] [ ":" [ expr ] ] ; args = arg { "," arg } ; arg = expr | NAME "=" expr ; atom = NAME | NUMBER | STRING | FSTRING | "True" | "False" | "None" | "(" expr ")" | tuple | list | dict | set | comprehension | "spawn" call | "await" postfix ; tuple = "(" expr "," [ expr { "," expr } ] ")" ; list = "[" [ list_item { "," list_item } [ "," ] ] "]" ; list_item = [ "*" ] expr ; dict = "{" [ dict_item { "," dict_item } [ "," ] ] "}" ; dict_item = expr ":" expr | "**" expr ; set = "{" expr { "," expr } "}" ; comprehension = "[" expr comp_for "]" | "{" expr ":" expr comp_for "}" | "{" expr comp_for "}" ; comp_for = ( "for" for_target "in" or_expr { "if" or_expr } )+ ; ``` A generator expression `expr comp_for` is also accepted as the single argument of a call. --- # Differences from Python Nox looks like Python and most small Python programs become Nox programs by adding type annotations. This page is the checklist of what differs, grouped by what you will hit first. Everything here is deliberate unless marked *(not yet)*. ## Types are mandatory Every variable's first assignment, every parameter and every return value carries a type. There is no `Any`, no dynamic attribute creation, no `setattr`/`getattr`/`exec`/`eval`. `x = []` is an error — write `x: list[int] = []`. A name keeps its type for its scope. Inside functions `x := expr` infers the type from the value (not `None`/empty containers; see [Types](https://noxlang.com/docs/language/types/#inferred-local-declarations)); this is not Python's walrus operator. ## Numbers | Python | Nox | |---|---| | unbounded `int` | 64-bit `int` that **wraps** on overflow; fixed-width types (`u8`…`i64`) **trap** on overflow | | `2 ** -1` is `0.5` | `int ** int` is an `int` (negative exponent → `0`); use a `float` base | | `10 ** 30` is exact | wraps modulo 2⁶⁴ | | `True + 1` is `2` | `bool` never takes part in arithmetic — `int(True) + 1` | | `if x:` truthiness | conditions must be `bool` — write `if x != 0:` / `if len(xs) > 0:` | | `round(2.5)` is `2` | same (half to even), but `round(x)` always returns `int` | | `int(u8_value)` n/a | `int(x)` works on fixed-width integers and `bool` | Integer `//` and `%` by zero raise `ZeroDivisionError`; float division never raises (`inf`/`nan`). Floats print like Python's `repr`. ## Syntax - No `lambda` with statements. Semicolons, one-line compound statements (`if x: y()`), `try … else`, `for/while … else`, `with a, b:`, raw strings (`r"…"`), adjacent literal concatenation, `...` and `global x` are supported; `noxc fmt` writes the expanded canonical form. - No Python expression walrus (`(n := f())`); `x := value` is a *declaration* statement that infers the type (see [Types](https://noxlang.com/docs/language/types/#inferred-local-declarations)). - `*args`, `**kwargs`, keyword-only (`*`), positional-only (`/`) and call-site unpacking (`f(*xs)`, `f(**d)`) are supported (see [Functions](https://noxlang.com/docs/language/functions/)); `f(**d)` never binds a named parameter by key. Star-assignment (`a, *b = xs`, lists only), nested targets and `[*a]`/`{**d}` displays work. Default values must be constant literals. - `yield` generators are **lazy** state machines typed `Iterator[T]` (see [Functions](https://noxlang.com/docs/language/functions/#generators-yield)); `yield` inside `try … finally` is allowed, there is no `send()`. Generator expressions are accepted only as a call argument and are evaluated eagerly into a list. - `nonlocal` is supported (the variable needs an explicit type at its first declaration); `global x` is accepted and changes nothing, because module-level names are assigned directly from functions. - No `%` formatting and no `!a` in f-strings (`!r` and `!s` work). `\xHH` is limited to ASCII; use `\uHHHH`/`\UHHHHHHHH` for other characters. Identifiers are compared by code point (no NFKC normalization; see [`nox.unicode`](https://noxlang.com/docs/stdlib/unicode/) for normalizing text). - Bare `raise` (inside `except`) and `raise X from Y` (the cause is stored as `X.cause`, the message text of `Y`) work. - `async with` and `async for` exist; `await` takes a `Task`, a channel operation or an async-protocol call, not an arbitrary expression. - No `del name` (only `del xs[i]` and `del d[k]`). - `__name__ == "__main__"` does not exist: the top-level statements of the entry file are the program, and `main` is a reserved name. - `type Name = T` aliases are supported (module level, no generic aliases); decorators that wrap are not part of Nox. `match` (on `enum`s), `@property`, `@staticmethod` and `@classmethod` are. - Chained comparisons (`a < b < c`) work. ## Collections and iteration - `map`, `filter`, `zip`, `enumerate` and `reversed` return **new lists**, not lazy iterators; `range` is only usable in `for`, comprehensions and `list(...)`. - `dict` keys are `int`, `float`, `bool` or `str`; values are scalars, classes, lists or dicts. `set` elements are `int`, `float`, `bool` or `str`. Both keep **insertion order** (as Python dicts do; Python sets do not). Tuples cannot be dictionary keys. - Lists are homogeneous: `[1, "a"]` is a type error. A list of subclasses needs an annotation (`xs: list[Base] = [Dog(), Cat()]`). - Slices are values — you cannot assign to a slice or delete one. `xs.sort()` needs `int`, `float` or `str` elements unless you pass `key=`. - A loop variable keeps its value after the loop, but after a `range` loop it is one past the last element, not the last element. - `sorted`, `min`, `max` take `key=`, but the elements (or the keys) must be `int`, `float` or `str`. ## Strings `str` is UTF-8 and indexed by code point; case conversion and character classes follow Unicode like Python (no normalization, no locale-specific mappings). The format mini-language is fully supported in f-strings, `format()` and `str.format`. ## Classes - Multiple inheritance (`class C(A, B)`: `C` is a subtype of every base, see [Classes](https://noxlang.com/docs/language/classes/#several-bases-multiple-inheritance)); class attributes are shared storage assigned only through the declaring class (`Cls.X = v`, never `self.X = v`); no metaclasses, `__slots__`, `__getattr__`, `__call__` or `isinstance`. - Fields are fixed: created in `__init__` (or declared in the class body) and never added later. `self` may be left unannotated. - `==` on two instances compares fields structurally unless you define `__eq__`; `is` is only for `None`. - Operator overloading uses the usual dunder names; `x += y` calls `__add__`. - A class used before it is defined is fine; a protocol is structural and only usable as a parameter type (no `list[Protocol]`). ## Errors and resources Exceptions are classes, `except Base:` catches subclasses, and `e.message`/`e.line` are available. There is no traceback object — an uncaught exception prints the class and source line. Resources are released by `with`, `defer` and `finally`; `__del__` runs once when the last reference goes away ([Classes](https://noxlang.com/docs/language/classes/#destructors-__del__)); there is no `weakref`. Built-in error text is English; match the exception class, not the wording. ## Modules `import a.b` / `from a.b import x [as y]` only — no `import *`, no relative imports, no dynamic import; a module may restrict what others can use with an opt-in `__all__`. All modules compile together; module-level variables are read from other modules with `from m import name`, not as `m.name`. Third-party code arrives through `nox.json` and `noxc fetch`, not `pip`. ## Concurrency There is no GIL and no `threading`/`asyncio`. Tasks (`spawn`/`await`), channels and `nox.thread` replace them, and on the default backend tasks run in parallel on a worker pool ([Concurrency](https://noxlang.com/docs/language/concurrency/)). There is no `list[Task[T]]`; gather results through a channel. ## Performance model Nox is compiled ahead of time to native code. There is no interpreter overhead, no boxing of `int`/`float`, and memory is released deterministically. A straight port of a numeric Python loop typically runs one to two orders of magnitude faster. --- # How-to guides Short, task-oriented pages: each one answers a single question and links to the reference for the details. If you are new to Nox, start with the [tutorial](https://noxlang.com/docs/tutorial/) instead. | I want to… | Guide | |---|---| | keep my executables small | [Reduce binary size](https://noxlang.com/docs/howto/binary-size/) | | build for another operating system or CPU | [Cross-compile](https://noxlang.com/docs/howto/cross-compile/) | | use LZ4, xxHash, yyjson, PCRE2, Brotli or Zstandard | [Use the embedded C libraries](https://noxlang.com/docs/howto/embedded-c-libraries/) | Looking for something else? The [language reference](https://noxlang.com/docs/language/) says what Nox guarantees, the [standard library](https://noxlang.com/docs/stdlib/) lists every module, and the [FAQ](https://noxlang.com/docs/reference/faq/) answers common questions. --- # Reduce binary size A Nox program is one native executable with the runtime linked in. The linker drops everything the program does not use, so size follows what you **import**, not what the standard library contains. ## What to expect Measured on release builds, with a program that only prints a line: | Target | Size | |---|---| | macOS arm64 | 0.21 MB | | Linux x86-64 (cross-compiled) | 0.34 MB | | Windows x86-64 (cross-compiled) | 0.78 MB | These are the numbers for the default LLVM back end at version 2.1.176. A real program grows with the modules it imports: a TLS client, a database driver or a full HTTP server each add their own code, nothing else does. ## What helps 1. **Import only what you use.** An unused module costs nothing, but every module you do import is linked in. Prefer a narrow module (`nox.strings`) over a broad one when both would do. 2. **Do not pass `-g` unless you are debugging.** `-g` selects the QBE back end and keeps DWARF line tables in the executable ([Debugging](https://noxlang.com/docs/tools/debugging/)). Without it the linker strips debug information (`--strip-debug` on Linux and Windows) and no `.pdb` file is written. 3. **Keep the default back end.** LLVM, the default, produces the smaller and faster code on macOS, Linux and Windows. QBE is chosen automatically for freestanding builds, `--emit-asm` and `-g` ([Back ends](https://noxlang.com/docs/tools/backends/)). 4. **Use the C-backed modules only where you need them.** `nox.lz4`, `nox.yyjson`, `nox.pcre2` and the others link a C library into the program only when imported ([Embedded C libraries](https://noxlang.com/docs/howto/embedded-c-libraries/)). ## How the linker does it The runtime is built with one section per function and per data item, and the final link runs with dead-code elimination (`--gc-sections` on Linux and Windows, `-dead_strip` on macOS). Before Nox 2.1.176 cross-built Linux and Windows programs carried the runtime's debug information and could not drop unused code, so a hello-world was 19 MB on Linux; if you see that on an old compiler, `noxc upgrade` fixes it. ## Check what you got ```sh noxc build main.nox -o app ls -l app ``` `noxc explain main.nox` shows where each value lives, which is the other half of a program's footprint: memory at run time rather than bytes on disk ([Memory](https://noxlang.com/docs/language/memory/)). --- # Cross-compile `noxc build --target ` produces an executable for another system from any host that has `zig` on its `PATH`. The program goes through the same LLVM back end as a native build, so it is optimised the same way. ## Desktop targets | `--target` | Produces | |---|---| | `macos-arm64`, `macos-x64` | macOS executable | | `linux-x64`, `linux-arm64` | Linux executable | | `linux-riscv64` | Linux executable (static musl) | | `windows-x64` | Windows `.exe` | ```sh noxc build --target windows-x64 main.nox -o app.exe noxc build --target linux-arm64 main.nox -o app ``` Without `zig`, a desktop `--target` falls back to QBE and a C compiler for that target, or fails if there is none. The complete list of targets and their support level is in [Platforms](https://noxlang.com/docs/reference/platforms/). ## Things to know - **The runtime travels with the compiler.** Cross builds link `noxrt-.o` from the compiler's `lib/` directory, so a compiler installed from a release archive can cross-compile without extra downloads. - **Embedded C libraries are per target.** Programs that import `nox.lz4`, `nox.yyjson` and the like also need `noxclibs-.a` next to the runtime ([Embedded C libraries](https://noxlang.com/docs/howto/embedded-c-libraries/)). Release archives from 2.1.176 include it. - **Run it where it belongs.** A Windows `.exe` built on Linux is checked on a real Windows machine in the project's CI on every change; you can verify yours the same way. - **WebAssembly is a target too:** `--target wasm32-wasi` or `wasm32-freestanding` ([WebAssembly](https://noxlang.com/docs/tools/wasm/)). - **Mobile targets produce libraries**, not executables (`--emit-obj`, `--emit-static-lib`, `--emit-shared-lib`), and are experimental ([Platforms](https://noxlang.com/docs/reference/platforms/)). ## Freestanding For bare metal, `--profile freestanding --target x86_64|aarch64|riscv64` builds a kernel-style ELF ([Freestanding](https://noxlang.com/docs/tools/freestanding/)). --- # Use the embedded C libraries Six standard-library modules are backed by well-known C libraries that ship with Nox. They are real wrappers with Nox semantics: errors are Nox exceptions, strings are Nox strings, and nothing leaks. | Module | Library | What it does | |---|---|---| | [`nox.lz4`](https://noxlang.com/docs/stdlib/lz4/) | LZ4 | frame compression, very fast | | [`nox.xxhash`](https://noxlang.com/docs/stdlib/xxhash/) | xxHash | fast non-cryptographic hashes | | [`nox.yyjson`](https://noxlang.com/docs/stdlib/yyjson/) | yyjson | JSON read and write, the fastest reader in the standard library | | [`nox.pcre2`](https://noxlang.com/docs/stdlib/pcre2/) | PCRE2 with JIT | Perl-compatible regular expressions | | [`nox.brotli`](https://noxlang.com/docs/stdlib/brotli/) | Brotli | decompression | | [`nox.zstd`](https://noxlang.com/docs/stdlib/zstd/) | Zstandard | compression (the C library); decompression is built in | They sit **next to** the pure modules (`nox.json`, `nox.regex`, ...), which are unchanged. Reach for the C-backed one when speed matters or when you need its exact semantics (for example Perl-style look-behind). ## How they are linked The C code lives in one archive, `lib/noxclibs.a` (and `noxclibs-.a` for cross targets). A program links it **only if it imports one of these modules**, so programs that do not use them do not grow. It behaves identically on macOS, Linux and Windows. Each module except `nox.zstd` has `is_supported()`. It returns `True` in any program that has the library linked, which is every program that can call it, so it is mostly useful as a feature probe in library code that wants one code path for all modules. ```sh noxc build main.nox -o app # links lib/noxclibs.a because main.nox imports nox.lz4 ``` ## Where they are not available - **Mobile targets (iOS, Android):** the archive is not linked. Importing `nox.lz4`, `nox.xxhash`, `nox.yyjson` or `nox.brotli` is a compile-time error that says so, and `nox.pcre2` is rejected by the mobile capability rules. `nox.zstd.decompress` works; a call to `nox.zstd.compress` is rejected at compile time because it needs the archive. - **WebAssembly:** `noxc build --target wasm32-wasi` stops with "this target has no embedded C libraries" for a program that imports one of these modules. - **Builds that deny `dynamic_code`:** `nox.pcre2` is rejected (the JIT generates machine code); use `nox.regex` instead. ## Installing Release archives and installers from 2.1.176 include `lib/noxclibs.a`. If you installed an earlier release, `noxc upgrade` brings it. When you build the compiler from source, `zig build` produces `zig-out/lib/noxclibs.a`. --- # The three APIs Nox deliberately separates **what you may build on** from **what the compiler and runtime may change**. There are three public, versioned APIs, each aimed at a different kind of author, and one private layer underneath that is never a compatibility promise. ```text Nox 2.x ├── NAPI — the Nox API source-level contract for libraries and frameworks written in Nox ├── NNI — the Nox Native Interface C ABI + opaque handles for native extensions (C, C++, Rust, Zig) ├── Plugin API manifests, versioning and capability consent, layered on NNI └── Internal runtime ABI compiler ↔ runtime ↔ stdlib shims — PRIVATE, unstable ``` | API | You are… | You write | Stability promise | |---|---|---|---| | [**NAPI**](https://noxlang.com/docs/apis/napi/) | writing a library or framework in Nox (a web framework, an ORM, a CLI toolkit) | `.nox` source | source compatibility for the whole 2.x series | | [**NNI**](https://noxlang.com/docs/apis/nni/) | writing native code that Nox programs call and that must not depend on runtime internals | C, C++, Rust or Zig against `nox_nni.h` | binary compatibility: a plugin built against NNI v1 loads in every Nox that implements v1 | | [**Plugin API**](https://noxlang.com/docs/apis/plugin-api/) | shipping or consuming a native plugin as a *product* — with a name, a version, declared functions and capabilities | a `nox-plugin.json` manifest next to an NNI library | manifest format and `nox.plugin` semantics are stable within `plugin_api: 1` | | [Internal ABI](https://noxlang.com/docs/apis/internal-abi/) | contributing to the compiler/runtime | Zig | **none** — may change in any release | The single hard rule: **the public interfaces and the internal runtime ABI must never be confused.** The layout of reference-counted objects, the runtime state, string/list/dictionary/class memory layouts, generated symbol names and every `nox_*` runtime symbol that is not part of NNI are internal. ## Which API do I use? - *"I want a reusable Nox library."* — just write Nox. Follow the [NAPI](https://noxlang.com/docs/apis/napi/) contract and the [package](https://noxlang.com/docs/tools/packages/) workflow. - *"I need to call a C library I already have."* — [`extern def`](https://noxlang.com/docs/language/ffi/). No plugin needed. - *"I am writing a native extension that Nox users should install and call safely, possibly from several Nox versions."* — NNI ([guide](https://noxlang.com/docs/apis/nni-guide/)), packaged with the [Plugin API](https://noxlang.com/docs/apis/plugin-api/). - *"I want to run a Python C extension or a WebAssembly module."* — the HPy/WASM bridges ([Internals](https://noxlang.com/docs/internals/hpy-wasm/)). ## How they compose A plugin author writes an NNI library, adds a `nox-plugin.json`, and ships both. A Nox program loads it with `nox.plugin.load_plugin(manifest, allowed_capabilities)`, which reads the manifest, checks the API version and the platform, asks the user's code for consent to the declared capabilities, loads the library through NNI, and verifies that the functions the library registered are exactly the ones the manifest declares. Calls then go through typed wrappers that check argument types against the manifest before any native code runs. A framework written in Nox (NAPI) can build on any of these: it consumes plugins for native engines, uses `nox.reflect` for decorators, and exposes its own stable Nox API to its users. ## Trust All three public APIs that involve native code — `extern def`, NNI and plugins — run native code with **full process authority**. The Plugin API's capabilities are a consent and declaration mechanism, not a sandbox. See [Security](https://noxlang.com/docs/reference/security/). ## Versioning at a glance | Thing | Version | Where it lives | |---|---|---| | Nox language / NAPI | the Nox release (`2.x.y`), semantic versioning | `build.zig.zon`, [Versioning](https://noxlang.com/docs/reference/versioning/) | | NNI | `NOX_NNI_ABI_VERSION` (currently `1`); members only ever appended to `NoxApiV1` | `include/nox_nni.h` | | Plugin API | `plugin_api` in the manifest (currently `1`) | `nox.plugin.PLUGIN_API_VERSION` | | Internal ABI | none | — | See [Stability and compatibility](https://noxlang.com/docs/apis/stability/) for the full matrix and deprecation policy. --- # NAPI — the Nox API NAPI is the contract between the Nox language/standard library and the people who build **libraries and frameworks in Nox**: web frameworks, ORMs, test runners, CLI toolkits, dependency-injection containers. It answers one question precisely: *what may I rely on staying the same across Nox 2.x releases?* The promise is **source compatibility**: Nox source that compiles and behaves correctly on Nox 2.0 keeps compiling and behaving the same on every 2.x release. Nothing in NAPI is a binary promise — Nox programs are always compiled from source as one unit. ## What is stable ### Language semantics Everything in the [language reference](https://noxlang.com/docs/language/) is part of NAPI: typing rules, scoping, evaluation order (arguments are evaluated left to right as written), integer behaviour (plain `int` wraps; fixed-width integers trap on overflow, identically on both backends), the special-method protocol, the exception hierarchy and `try`/`finally`/`with`/`defer`/`break`/`continue` cleanup order, structural protocols, generics and monomorphisation, closures, `async`/`spawn`/`await` semantics and cooperative cancellation. Compiler *diagnostics text* is not covered (only the error *kind* is stable): do not parse messages. ### The public standard library The names, signatures and documented behaviour of the `nox.*` modules in the [standard library reference](https://noxlang.com/docs/stdlib/). Excluded: - names beginning with `__nox_` and the contents of the prelude beyond its documented names, - anything the reference marks *experimental* or *deprecated*. **Constructor freeze.** Classes that frameworks construct directly — `HttpRequest`, `HttpResponse`, `Row`, `Statement` and similar — keep their existing constructor parameters for the whole major version; new parameters are only ever added **with default values**, and fields are only added, never removed or renamed. The same holds for objects the runtime constructs and hands to your code (for example the `HttpRequest` given to a `serve` handler). ### Reflection for decorators `nox.reflect` — the metadata API behind `@decorator` syntax ([Decorators](https://noxlang.com/docs/language/decorators/)) — including class `__init__` signatures, method records and `decorator_handler`. The *meaning* of a decorator is always yours. ### Concurrency `Task[T]`, `Channel[T]`, `TaskLocal[T]`, `ThreadHandle[T]`, `ThreadChannel[T]`, `spawn`/`await`, `CancelledError`, and the rule that tasks are correct under both the single-threaded and the multi-core scheduler. Which scheduler runs your tasks is *not* part of the contract. ### HTTP `nox.http` client and server abstractions, `HttpRequest`/`HttpResponse` fields and constructors, `nox.router` (routes, path parameters, middleware), the serve entry points and their argument order. ### Foreign functions The `extern def` C-ABI type mapping and the `@ffi.callback` trailing-`userdata` convention ([Foreign functions](https://noxlang.com/docs/language/ffi/)). ### Packages The `nox.json` manifest, the `nox.lock` format and `requires[]` resolution ([Packages](https://noxlang.com/docs/tools/packages/)). ### Native extensions NNI v1 ([NNI](https://noxlang.com/docs/apis/nni/)) and the Plugin API ([Plugin API](https://noxlang.com/docs/apis/plugin-api/)) are covered by their own, stronger (binary) promises. ## What is *not* stable AST and compiler internals · QBE and LLVM IR output · reference-count header layout · object, list, dictionary and string layouts · the runtime state · the cycle-collector implementation · generated symbol names (`Class_method`, `tuple__int_str`, `__nox_*`) · every `nox_*` runtime symbol that is not part of NNI · **binary compatibility between separately compiled Nox object files**. ## Guidance for framework authors 1. **Depend on source features.** Generics (including higher-order generics), callbacks and closures, decorators plus `nox.reflect`, allocator-independent collections and the task scheduler are all you need. Prefer the narrow modules (`nox.mem`, `nox.atomic`, `nox.thread`, `nox.fs`, `nox.os`, `nox.reflect`) over reaching toward runtime symbols. 2. **Treat module state as per-worker.** Under the multi-core scheduler each worker keeps its own copy of module-level variables; share data with channels, `nox.atomic` or `nox.sharedmem` ([Concurrency](https://noxlang.com/docs/language/concurrency/)). 3. **Pin and test against both backends.** The default backend is LLVM with a parallel scheduler; QBE is single-threaded. A framework should be correct under both (`noxc build --backend qbe`). 4. **Never parse diagnostics; branch on exception classes.** 5. **Gate native code behind the Plugin API** so users can see and consent to what your framework loads. 6. **Pin Nox in CI.** Declare the Nox version you test with; the stability promise is per *major* version. ## Deprecation policy A name is deprecated for at least one MINOR release (with a note in the reference and the changelog) before it can be removed, and removal only happens in the next MAJOR release. Removed in 2.0: the deprecated aliases listed in [Migrating from 1.x](https://noxlang.com/docs/whatsnew/migrating/). See [Versioning](https://noxlang.com/docs/reference/versioning/). --- # NNI — the Nox Native Interface (v1) NNI is a **C ABI** that lets native code — C, C++, Rust, Zig — extend Nox programs without ever depending on how the runtime represents data. A native extension is a shared library (`.so`, `.dylib`, `.dll`) that exports one entry point. The host hands it a **versioned table of functions**; everything that crosses the boundary is a plain C value or an **opaque handle**. A plugin never sees a pointer into Nox's heap, the reference-count header, a string layout or a generated symbol name — so the runtime stays free to change all of them without breaking a single plugin. The header is [`include/nox_nni.h`](https://github.com/mburakmmm/nox-lang/blob/main/include/nox_nni.h). Plugins are loaded from Nox with [`nox.native`](https://noxlang.com/docs/stdlib/native/) (raw) or, with manifests and consent, [`nox.plugin`](https://noxlang.com/docs/apis/plugin-api/). ## The entry point Every plugin exports exactly one required symbol: ```c NOX_EXPORT NoxStatus nox_plugin_init_v1(const NoxApiV1* api, NoxRuntime* rt); ``` The host calls it once, on load, with the API table and an opaque per-plugin runtime context `rt`. The plugin must: 1. check `api->abi_version` and `api->struct_size` and return `NOX_ABI_UNSUPPORTED` if the host is too old for what it needs; 2. register its functions with `api->register_function(rt, "name", fn)`; 3. return `NOX_OK`. An optional second symbol is called when the plugin is closed: ```c NOX_EXPORT void nox_plugin_shutdown_v1(const NoxApiV1* api, NoxRuntime* rt); ``` If exported, the host calls it exactly once, on the thread that closes the plugin, just before the library is unloaded. Stop native threads and release resources there. ## Status codes ```c typedef int32_t NoxStatus; enum { NOX_OK = 0, NOX_ERROR = 1, /* recoverable error: becomes a Nox exception (message from error_set) */ NOX_PANIC = 2, /* unrecoverable plugin failure: terminates the call with an error */ NOX_ABI_UNSUPPORTED = 3, /* returned by init when the host ABI is too old */ NOX_BAD_HANDLE = 4, NOX_OUT_OF_MEMORY = 5, NOX_NOT_FOUND = 6 }; ``` ## Values ```c enum { NOX_V_NONE = 0, NOX_V_INT = 1, NOX_V_FLOAT = 2, NOX_V_BOOL = 3, NOX_V_STRING = 4, NOX_V_BYTES = 5 }; typedef struct NoxValue { int32_t kind; /* NOX_V_* */ int32_t reserved; /* set to 0 */ union { int64_t i; double f; NoxHandle h; } u; } NoxValue; ``` A `NoxValue` is 16 bytes. `NOX_V_INT` and `NOX_V_BOOL` use `u.i` (`0`/`1` for bool), `NOX_V_FLOAT` uses `u.f`, and `NOX_V_STRING` / `NOX_V_BYTES` carry a **handle** in `u.h`. ### Handles `NoxHandle` is a 64-bit **generation-counted index**. `0` is never valid. A handle that was released — or reused after release — is *detected* (`NOX_BAD_HANDLE`), never dereferenced. Strings and byte buffers are only ever reachable through handles: - `string_new(rt, data, len)` creates a string from **validated UTF-8**; it returns `0` on invalid UTF-8 or out of memory. - `string_view(rt, h, &data, &len)` gives a read-only view valid **while the handle lives**. - `bytes_new` / `bytes_view` are the same for raw byte buffers. - `retain` / `release` adjust a handle's reference count. Handles in the `args` of a call are owned by the host. A handle you store in `*out` transfers ownership to the host. ## The API table ```c struct NoxApiV1 { uint32_t abi_version; /* NOX_NNI_ABI_VERSION the host implements */ uint32_t struct_size; /* sizeof(NoxApiV1) of the host; never read members past this */ void (*retain)(NoxRuntime* rt, NoxHandle h); void (*release)(NoxRuntime* rt, NoxHandle h); NoxHandle (*string_new)(NoxRuntime* rt, const uint8_t* data, size_t len); NoxStatus (*string_view)(NoxRuntime* rt, NoxHandle h, const uint8_t** data, size_t* len); NoxHandle (*bytes_new)(NoxRuntime* rt, const uint8_t* data, size_t len); NoxStatus (*bytes_view)(NoxRuntime* rt, NoxHandle h, const uint8_t** data, size_t* len); void* (*alloc)(NoxRuntime* rt, size_t size, size_t alignment); void (*free)(NoxRuntime* rt, void* p, size_t size, size_t alignment); NoxStatus (*error_set)(NoxRuntime* rt, int32_t code, const uint8_t* msg, size_t len); NoxStatus (*register_function)(NoxRuntime* rt, const char* name, NoxNativeFn fn); NoxStatus (*post_event)(NoxRuntime* rt, int64_t kind, const NoxValue* payload); /* Appended in v1.x. Do not read these unless struct_size covers them. */ NoxHandle (*list_new)(NoxRuntime* rt); NoxStatus (*list_append_int)(NoxRuntime* rt, NoxHandle h, int64_t v); NoxStatus (*list_len)(NoxRuntime* rt, NoxHandle h, int64_t* out_len); NoxStatus (*list_get_int)(NoxRuntime* rt, NoxHandle h, int64_t index, int64_t* out); NoxHandle (*dict_new)(NoxRuntime* rt); NoxStatus (*dict_set_int)(NoxRuntime* rt, NoxHandle h, const uint8_t* key, size_t key_len, int64_t v); NoxStatus (*dict_len)(NoxRuntime* rt, NoxHandle h, int64_t* out_len); NoxStatus (*dict_get_int)(NoxRuntime* rt, NoxHandle h, const uint8_t* key, size_t key_len, int64_t* out); }; ``` | Member | Contract | |---|---| | `retain`, `release` | thread-safe; adjust the reference count of any valid handle | | `string_new`, `string_view`, `bytes_new`, `bytes_view` | thread-safe; see *Handles* | | `alloc`, `free` | the host allocator (the one Nox uses for the plugin's context); `free` must receive the same size and alignment. `alloc` with `size == 0` returns `NULL` (like `malloc(0)` on some platforms) and `free(NULL, ...)` does nothing | | `error_set` | records a message for the *current call* and returns `NOX_ERROR`; use as `return api->error_set(rt, code, msg, len);` | | `register_function` | valid **only during** `nox_plugin_init_v1`; registers a callable by name | | `post_event` | thread-safe, callable from **any** thread; copies string/bytes payloads; `kind` must be `>= 0` | | `list_new`, `list_append_int`, `list_len`, `list_get_int` | appended in v1.x; a private list of `int64`, not a Nox list object. Returning `NOX_V_LIST` transfers the handle to the host | | `dict_new`, `dict_set_int`, `dict_len`, `dict_get_int` | appended in v1.x; a private `dict[str, int64]`. Returning `NOX_V_DICT` transfers the handle to the host | ## Native functions ```c typedef NoxStatus (*NoxNativeFn)(const NoxApiV1* api, NoxRuntime* rt, const NoxValue* args, size_t argc, NoxValue* out); ``` A native function receives the argument array and writes its result into `*out` (leave it as `NOX_V_NONE` for "no value"). It returns `NOX_OK`, `NOX_ERROR` (after `error_set`, which becomes a Nox [`NativeError`](https://noxlang.com/docs/stdlib/native/) carrying the message) or `NOX_PANIC`. **No exception, `longjmp` or unwinding may cross the boundary in either direction.** Always validate: check `argc` and each `args[i].kind` before use, as the host does not know your function's signature (a [manifest](https://noxlang.com/docs/apis/plugin-api/) lets it check for you). ## Threading contract 1. Native functions run **synchronously on the thread that called them** from Nox. 2. `retain`, `release`, `string_new`, `string_view` and `bytes_*` are internally locked and safe from any thread. 3. A native thread never enters the Nox object graph. To send work or results back it calls the thread-safe `post_event(rt, kind, payload)`; payloads are **copied** into a host queue. Nox code drains events with `Plugin.poll_event()` / `Plugin.wait_event(timeout_ms)` on its own scheduler. This is the "native → Nox callback" model: *native thread → `post_event` → Nox scheduler → Nox code*. 4. `register_function` is valid only during `nox_plugin_init_v1`. 5. A plugin that starts threads must stop them in `nox_plugin_shutdown_v1`. ## Versioning New members are **only ever appended** to the end of `NoxApiV1`. A plugin built against an older header stays valid because it gates on `struct_size` before touching any later member. Incompatible changes would be a new `NoxApiV2` with a new entry symbol (`nox_plugin_init_v2`), which a host can implement alongside v1. ## Deliberately out of NNI v1 Direct list/dictionary/object memory access, class layouts, reflection ABI, GC hooks, Nox closures as C function pointers and precompiled Nox-to-Nox binary linking. Keeping these out is what lets the runtime change its reference-counting scheme, arenas or object layout without ever breaking a plugin. v1.x appends integer list and string-key integer dict builders (`list_*`, `dict_*`). They store a private host encoding and are copied into a Nox `list[int]` or `dict[str, int]` only when the call returns. `invoke_callback` (a Nox closure as a C function pointer) stays out of this table. ## Platform notes | Platform | Library | Notes | |---|---|---| | macOS | `lib.dylib` | built with `-dynamiclib` | | Linux | `lib.so` | built with `-shared -fPIC` | | Windows | `.dll` | export with `__declspec(dllexport)` (`NOX_EXPORT`) | The host loads libraries with `dlopen`/`LoadLibrary`; the plugin's own dependencies are resolved by the platform loader as usual. ## Trust boundary A plugin runs with **full native authority**, exactly like `extern def` ([Security](https://noxlang.com/docs/reference/security/)). NNI does not sandbox it; its handle checks protect the *host's data*, not the system from a malicious plugin. See the [NNI guide](https://noxlang.com/docs/apis/nni-guide/) for complete working plugins in C, Zig and Rust. --- # Writing a native plugin This guide builds complete NNI plugins in **C**, **Zig** and **Rust**, loads them from Nox, adds a manifest, sends events from a native thread and shows the testing and packaging workflow. Read the [NNI reference](https://noxlang.com/docs/apis/nni/) for the exact contracts and the [Plugin API](https://noxlang.com/docs/apis/plugin-api/) for manifests. Every plugin below was built and loaded with the commands shown. ## 1. A plugin in C `myext.c` exposes `add(int, int) -> int` and `greet(str) -> str`: ```c #include "nox_nni.h" #include #include /* add(int, int) -> int */ static NoxStatus fn_add(const NoxApiV1* api, NoxRuntime* rt, const NoxValue* args, size_t argc, NoxValue* out) { if (argc != 2 || args[0].kind != NOX_V_INT || args[1].kind != NOX_V_INT) { const char* msg = "add(int, int) expects two integers"; return api->error_set(rt, 1, (const uint8_t*)msg, strlen(msg)); } out->kind = NOX_V_INT; out->u.i = args[0].u.i + args[1].u.i; return NOX_OK; } /* greet(str) -> str */ static NoxStatus fn_greet(const NoxApiV1* api, NoxRuntime* rt, const NoxValue* args, size_t argc, NoxValue* out) { if (argc != 1 || args[0].kind != NOX_V_STRING) return NOX_ERROR; const uint8_t* name; size_t n; if (api->string_view(rt, args[0].u.h, &name, &n) != NOX_OK) return NOX_ERROR; char buf[256]; int len = snprintf(buf, sizeof buf, "hello, %.*s!", (int)n, (const char*)name); out->kind = NOX_V_STRING; out->u.h = api->string_new(rt, (const uint8_t*)buf, (size_t)len); return out->u.h ? NOX_OK : NOX_OUT_OF_MEMORY; } NOX_EXPORT NoxStatus nox_plugin_init_v1(const NoxApiV1* api, NoxRuntime* rt) { if (api->abi_version < 1 || api->struct_size < sizeof(NoxApiV1)) return NOX_ABI_UNSUPPORTED; api->register_function(rt, "add", fn_add); api->register_function(rt, "greet", fn_greet); return NOX_OK; } ``` Build it (point `-I` at the directory containing `nox_nni.h`, shipped in the release's `include/` directory and in the repository): ```sh cc -shared -fPIC -I include -o libmyext.so myext.c # Linux cc -shared -fPIC -I include -o libmyext.dylib myext.c # macOS ``` ### Loading it raw with `nox.native` ```nox-fragment from nox.native import open_plugin, Plugin, NativeError p: Plugin = open_plugin("./libmyext.dylib") p.arg_int(40) p.arg_int(2) print(p.call_int("add")) # 42 p.arg_str("nox") print(p.call_str("greet")) # hello, nox! try: p.call("nope") except NativeError as e: print(e.message) # nope: no registered native function with that name p.close() ``` Arguments are pushed one at a time (`arg_int`, `arg_float`, `arg_bool`, `arg_str`) and consumed by the next call. `call_int`, `call_float`, `call_bool`, `call_str` read the result; `call` ignores it. A `NOX_ERROR` status raises `NativeError` with the message you gave `error_set`. ### Loading it with a manifest (recommended) Add `nox-plugin.json` next to the library: ```json { "name": "demo.hello", "version": "1.0.0", "plugin_api": 1, "library": { "macos-arm64": "libmyext.dylib", "linux-x64": "libmyext.so", "linux-arm64": "libmyext.so", "windows-x64": "myext.dll" }, "capabilities": [], "functions": [ { "name": "add", "args": ["int", "int"], "returns": "int" }, { "name": "greet", "args": ["str"], "returns": "str" } ] } ``` ```nox-fragment from nox.plugin import load_plugin, LoadedPlugin, PluginError p: LoadedPlugin = load_plugin("nox-plugin.json", []) p.arg_int(40) p.arg_int(2) print(p.call_int("add")) # 42 p.arg_str("nox") print(p.call_str("greet")) # hello, nox! try: p.arg_str("oops") p.arg_int(1) print(p.call_int("add")) except PluginError as e: print(e.message) # add: argument 1 must be int, got str p.shutdown() ``` The wrong-typed call never reaches native code: `nox.plugin` checks every call against the manifest signature first. ## 2. A plugin in Zig ```zig const std = @import("std"); const c = @cImport(@cInclude("nox_nni.h")); fn hypot2(api: [*c]const c.NoxApiV1, rt: ?*c.NoxRuntime, args: [*c]const c.NoxValue, argc: usize, out: [*c]c.NoxValue) callconv(.c) c.NoxStatus { _ = api; _ = rt; if (argc != 2 or args[0].kind != c.NOX_V_FLOAT or args[1].kind != c.NOX_V_FLOAT) return c.NOX_ERROR; const a = args[0].u.f; const b = args[1].u.f; out.*.kind = c.NOX_V_FLOAT; out.*.u.f = @sqrt(a * a + b * b); return c.NOX_OK; } export fn nox_plugin_init_v1(api: [*c]const c.NoxApiV1, rt: ?*c.NoxRuntime) callconv(.c) c.NoxStatus { if (api.*.abi_version < 1 or api.*.struct_size < @sizeOf(c.NoxApiV1)) return c.NOX_ABI_UNSUPPORTED; return api.*.register_function.?(rt, "hypot", hypot2); } ``` ```sh zig build-lib -dynamic -O ReleaseFast -I include -lc -femit-bin=libzigplug.dylib plug.zig ``` The manifest declares `{ "name": "hypot", "args": ["float", "float"], "returns": "float" }`; from Nox: ```nox-fragment p: LoadedPlugin = load_plugin("nox-plugin.json", []) p.arg_float(3.0) p.arg_float(4.0) print(p.call_float("hypot")) # 5.0 ``` ## 3. A plugin in Rust Rust needs no binding generator — declare the few `#[repr(C)]` types of the header (or generate them with `bindgen` from `nox_nni.h`). `Cargo.toml`: ```text [package] name = "rustplug" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] ``` `src/lib.rs` — `word_count(str) -> int`: ```text use std::os::raw::{c_char, c_int, c_void}; pub const NOX_OK: i32 = 0; pub const NOX_ERROR: i32 = 1; pub const NOX_ABI_UNSUPPORTED: i32 = 3; pub const NOX_V_INT: i32 = 1; pub const NOX_V_STRING: i32 = 4; #[repr(C)] #[derive(Clone, Copy)] pub union NoxValueData { pub i: i64, pub f: f64, pub h: u64 } #[repr(C)] pub struct NoxValue { pub kind: i32, pub reserved: i32, pub u: NoxValueData } pub type NoxRuntime = c_void; pub type NoxNativeFn = extern "C" fn(*const NoxApiV1, *mut NoxRuntime, *const NoxValue, usize, *mut NoxValue) -> i32; #[repr(C)] pub struct NoxApiV1 { pub abi_version: u32, pub struct_size: u32, pub retain: extern "C" fn(*mut NoxRuntime, u64), pub release: extern "C" fn(*mut NoxRuntime, u64), pub string_new: extern "C" fn(*mut NoxRuntime, *const u8, usize) -> u64, pub string_view: extern "C" fn(*mut NoxRuntime, u64, *mut *const u8, *mut usize) -> i32, pub bytes_new: extern "C" fn(*mut NoxRuntime, *const u8, usize) -> u64, pub bytes_view: extern "C" fn(*mut NoxRuntime, u64, *mut *const u8, *mut usize) -> i32, pub alloc: extern "C" fn(*mut NoxRuntime, usize, usize) -> *mut c_void, pub free: extern "C" fn(*mut NoxRuntime, *mut c_void, usize, usize), pub error_set: extern "C" fn(*mut NoxRuntime, i32, *const u8, usize) -> i32, pub register_function: extern "C" fn(*mut NoxRuntime, *const c_char, NoxNativeFn) -> i32, pub post_event: extern "C" fn(*mut NoxRuntime, i64, *const NoxValue) -> i32, } extern "C" fn word_count(api: *const NoxApiV1, rt: *mut NoxRuntime, args: *const NoxValue, argc: usize, out: *mut NoxValue) -> i32 { unsafe { let api = &*api; if argc != 1 || (*args).kind != NOX_V_STRING { let msg = b"word_count(str) expects one string"; return (api.error_set)(rt, 1, msg.as_ptr(), msg.len()); } let mut data: *const u8 = std::ptr::null(); let mut len: usize = 0; if (api.string_view)(rt, (*args).u.h, &mut data, &mut len) != NOX_OK { return NOX_ERROR; } let text = std::str::from_utf8_unchecked(std::slice::from_raw_parts(data, len)); (*out).kind = NOX_V_INT; (*out).u.i = text.split_whitespace().count() as i64; NOX_OK } } #[no_mangle] pub extern "C" fn nox_plugin_init_v1(api: *const NoxApiV1, rt: *mut NoxRuntime) -> c_int { unsafe { let a = &*api; if a.abi_version < 1 || (a.struct_size as usize) < std::mem::size_of::() { return NOX_ABI_UNSUPPORTED; } (a.register_function)(rt, b"word_count\0".as_ptr() as *const c_char, word_count) } } ``` ```sh cargo build --release # target/release/librustplug.dylib (or .so / .dll) ``` Declare `{ "name": "word_count", "args": ["str"], "returns": "int" }` in the manifest; `p.arg_str("the quick brown fox")` followed by `p.call_int("word_count")` returns `4`. Rust's `catch_unwind` is not needed: make sure no panic crosses the `extern "C"` boundary (build with `panic = "abort"` or wrap bodies in `std::panic::catch_unwind` and map a caught panic to `NOX_PANIC`). ## 4. Sending events from a native thread Native threads must not touch the Nox object graph. They send **events** that Nox code drains on its own scheduler. This plugin starts a thread that posts numbered values and a final string: ```c static const NoxApiV1* g_api; static NoxRuntime* g_rt; static void* worker(void* arg) { int64_t n = (int64_t)(intptr_t)arg; for (int64_t i = 0; i < n; i++) { NoxValue v = { .kind = NOX_V_INT, .reserved = 0, .u = { .i = i * 10 } }; g_api->post_event(g_rt, 7, &v); /* kind 7: a number */ } NoxHandle h = g_api->string_new(g_rt, (const uint8_t*)"done", 4); NoxValue sv = { .kind = NOX_V_STRING, .reserved = 0, .u = { .h = h } }; g_api->post_event(g_rt, 8, &sv); /* kind 8: finished */ g_api->release(g_rt, h); return NULL; } /* register a `start_thread(int)` function that stores api/rt and pthread_create()s `worker` */ ``` ```nox-fragment from nox.native import Event p.arg_int(3) p.call("start_thread") got: int = 0 done: bool = False while not done: ev: Event | None = p.wait_event(2000) # waits up to 2000 ms if ev == None: done = True else: if ev.kind == 7: got += ev.int_value else: print(ev.str_value, got) # done 30 done = True ``` `wait_event` and `poll_event` return an `Event` (`kind`, `value_kind`, `int_value`, `float_value`, `str_value`) or `None`. Payloads are copied, so the plugin can release its handles immediately after `post_event`. Stop the thread in `nox_plugin_shutdown_v1`. ## 5. Testing a plugin - **Unit-test the C/Rust/Zig code** with its own test framework — NNI functions are plain functions taking an `NoxApiV1*`; you can pass a mock table. - **Integration-test through Nox:** a `*_test.nox` file that loads the plugin with `load_plugin` and asserts on results (`noxc test`). - **Test the failure paths:** wrong argument counts and types (the manifest check), `NOX_ERROR` returns (`NativeError`), and a missing library or platform entry (`PluginError`). - **Test on every platform you ship** — the manifest's `library` table picks the file per platform. The repository's own tests do exactly this: `tests/compat/nni_ext/plugin.c` is exercised by `tests/cli/nni_test.zig` and `tests/cli/plugin_test.zig`. ## 6. Packaging Ship a directory containing `nox-plugin.json` and the libraries for each platform. Users put it anywhere and call `load_plugin("path/to/nox-plugin.json", allowed_capabilities)`. Declare every capability the code needs — see [Plugin API](https://noxlang.com/docs/apis/plugin-api/#capabilities). Version your manifest (`version`) independently of `plugin_api`, and keep NNI calls within the table members you rely on (`struct_size` gating) so one binary works across Nox releases. ## Checklist - [ ] Gate on `abi_version` and `struct_size` in `nox_plugin_init_v1`. - [ ] Validate `argc` and every `kind` in every function (or declare signatures in the manifest *and* still validate). - [ ] Never let an exception, panic or `longjmp` cross the boundary. - [ ] Release every handle you create and do not keep views past the handle's lifetime. - [ ] Stop your threads in `nox_plugin_shutdown_v1`. - [ ] Declare capabilities honestly. --- # The Plugin API The Plugin API turns an [NNI](https://noxlang.com/docs/apis/nni/) library into a **product**: something with a name, a version, a declared set of functions with types, and a declared set of capabilities that the host program must consent to before it loads. It is a thin, fully specified layer written in Nox ([`nox.plugin`](https://noxlang.com/docs/stdlib/plugin/)) on top of NNI — it adds no new binary interface, so every NNI plugin can be given a manifest. What it adds over raw NNI: - a **manifest** (`nox-plugin.json`) that describes the plugin and selects the right library for the current platform; - **API version negotiation** (`plugin_api`); - **typed signatures**: every call is checked against the declared argument and return types *before* native code runs; - **registration cross-check**: the functions the library registered must be exactly the ones the manifest declares; - **capability consent**: the host lists the capabilities it grants and a plugin that needs more is refused; - a **lifecycle**: `load_plugin` … `shutdown`, with the optional `nox_plugin_shutdown_v1` hook. ## The manifest `nox-plugin.json`, next to the library: ```json { "name": "acme.image", "version": "1.2.0", "plugin_api": 1, "library": { "macos-arm64": "libimage.dylib", "linux-x64": "libimage.so", "linux-arm64": "libimage.so", "windows-x64": "image.dll" }, "capabilities": ["fs.read"], "functions": [ { "name": "resize", "args": ["int", "int", "str"], "returns": "str" }, { "name": "version", "returns": "str" }, { "name": "sum", "args": ["int", "..."], "returns": "int" } ] } ``` ### Fields | Field | Type | Required | Meaning | |---|---|---|---| | `name` | string | yes | the plugin's identifier; reverse-DNS style (`acme.image`) is recommended | | `version` | string | yes | the plugin's own version (semantic versioning recommended); informational | | `plugin_api` | number | yes | the Plugin API version the manifest follows; **must equal** the host's (`1`) | | `library` | object | yes | maps a **platform key** to the library file; paths are relative to the manifest's directory (absolute paths are used as given) | | `capabilities` | array of strings | no | capabilities the plugin needs; default none | | `functions` | array | yes | the functions the library registers, with signatures | **Platform keys:** `macos-arm64`, `linux-x64`, `linux-arm64`, `linux-riscv64`, `windows-x64`. A manifest with no entry for the host platform is refused. Use `nox.plugin.host_platform()` to see the key of the current machine. ### Function signatures Each entry of `functions` has: | Field | Meaning | |---|---| | `name` | the name the library passes to `register_function` | | `args` | array of argument types, in order; omit or `[]` for none | | `returns` | the return type | Types: `"int"` (NNI `NOX_V_INT`), `"float"`, `"bool"`, `"str"` (a validated-UTF-8 string handle) and, for `returns` only, `"none"`, `"list"` (`list[int]`) and `"dict"` (`dict[str, int]`). A trailing `"..."` in `args` makes the **previous** type repeat zero or more times (`["int", "..."]` is one required integer followed by any number of integers; `"..."` cannot be first). ## Loading and calling ```nox-fragment from nox.plugin import load_plugin, LoadedPlugin, PluginError p: LoadedPlugin = load_plugin("plugins/image/nox-plugin.json", ["fs.read"]) p.arg_int(640) p.arg_int(480) p.arg_str("photo.png") out: str = p.call_str("resize") p.shutdown() ``` `load_plugin(manifest_path, allowed)` performs these steps in order, raising `PluginError` at the first failure: 1. read and **validate the manifest** — all required fields, known types, the `plugin_api` version, a `library` entry for this platform; 2. **check capabilities** — every capability in the manifest must be in `allowed`, or `"*"` must be present in `allowed`; 3. **load the library** and call `nox_plugin_init_v1` (a failure raises `PluginError` with the plugin's message); 4. **cross-check registration** — the set of functions the library registered must equal the manifest's `functions`; 5. return a `LoadedPlugin`. ### `LoadedPlugin` | Member | Description | |---|---| | `manifest` | the parsed `PluginManifest` (`name`, `version`, `plugin_api`, `library` path, `capabilities`, `functions`) | | `has_function(name)` | whether the manifest declares `name` | | `arg_int(v)`, `arg_float(v)`, `arg_bool(v)`, `arg_str(v)` | push the next argument | | `call(name)` | call a function declared `returns: "none"` | | `call_int(name)`, `call_float(name)`, `call_bool(name)`, `call_str(name)` | call and read the result; the requested kind must match `returns` | | `call_int_list(name)`, `call_str_int_dict(name)` | call a function declared `returns: "list"` or `"dict"` and copy the host buffer into a Nox `list[int]` or `dict[str, int]` | | `poll_event()`, `wait_event(timeout_ms)` | drain events a native thread posted ([NNI](https://noxlang.com/docs/apis/nni/#threading-contract)) | | `clear_args()` | discard pushed arguments | | `shutdown()` | call the plugin's `nox_plugin_shutdown_v1` (if exported), unload it; later calls raise `PluginError` | Before every call the pushed arguments are compared with the manifest signature — count (honouring `"..."`) and each type — and the requested `call_*` kind with `returns`. A mismatch raises `PluginError` **without calling native code** and discards the pushed arguments. If the native function returns `NOX_ERROR`, the call raises `NativeError` with the plugin's `error_set` message. `NOX_PANIC` terminates the call with an error. ### Errors | Situation | Exception | |---|---| | manifest missing, malformed, unknown type, wrong `plugin_api`, no library for this platform | `PluginError` | | capability not in `allowed` | `PluginError` (`capability not granted: fs.read`) | | library cannot be loaded / `nox_plugin_init_v1` fails | `PluginError` / `NativeError` | | registered functions differ from the manifest | `PluginError` | | wrong argument count/type, wrong `call_*` kind, unknown function, closed plugin | `PluginError` | | the native function reports an error | `NativeError` | ## Capabilities A capability is a short name for a kind of authority a plugin uses. The standard names are: | Capability | Authority | |---|---| | `fs.read` | reads files or directories | | `fs.write` | creates, modifies or deletes files | | `net` | opens network connections or listens | | `process` | starts processes or signals them | | `env` | reads or changes environment variables | | `threads` | starts native threads | | `unsafe` | uses raw memory, loads other native code or otherwise bypasses the plugin's own checks | The host passes the list it is willing to grant: `load_plugin(path, ["fs.read", "threads"])`; the joker `"*"` grants everything. A plugin that declares `"net"` while the host grants only `["fs.read"]` is **refused at load time**, before any native code runs. > **Capabilities are consent, not a sandbox.** They make a plugin's needs explicit and let the host (or a framework acting for its users) refuse a > plugin that wants more than expected. After loading, the plugin runs with the full authority of the process. A malicious or buggy plugin can > ignore its own declaration. Only load plugins you trust ([Security](https://noxlang.com/docs/reference/security/)). ## Lifecycle ```text load_plugin ─▶ manifest validated ─▶ capabilities checked ─▶ library loaded ─▶ nox_plugin_init_v1 ─▶ registration cross-checked ─▶ LoadedPlugin … calls … events … shutdown ─▶ nox_plugin_shutdown_v1 (optional) ─▶ library unloaded ``` If a `load_plugin` step fails after the library was opened (for example a registration mismatch), the library is shut down and unloaded before the error is raised, so a failed load leaves nothing behind. ## Versioning rules - `plugin_api` is bumped only for incompatible changes to the manifest format or `nox.plugin` semantics. A Nox release that implements Plugin API 1 loads every `plugin_api: 1` manifest; a manifest with a larger value is refused with a clear message. - New **optional** manifest fields may be added within `plugin_api: 1`; unknown fields are ignored. - A plugin's own `version` is independent and informational. - The binary contract underneath is [NNI](https://noxlang.com/docs/apis/nni/): one plugin binary works across Nox releases that implement NNI v1. ## Writing a plugin See the [NNI guide](https://noxlang.com/docs/apis/nni-guide/) for complete C, Zig and Rust plugins with manifests, event threads, testing and packaging. --- # The internal runtime ABI Underneath the three public APIs sits a fourth layer that is **not an API at all**: the interface between the code the compiler generates, the Zig runtime and the standard library's native shims. It is documented here so contributors understand it and so nobody mistakes it for a promise. > **Everything on this page may change in any release — including patch releases.** Never depend on it from plugins, extensions or libraries. > Use [NNI](https://noxlang.com/docs/apis/nni/) and `extern def` instead. ## What is in it - **Runtime symbols.** Generated code calls `nox_*` functions exported by the runtime (`nox_rc_alloc`, `nox_list_grow`, `nox_dict_set`, `nox_cycle_*`, `nox_async_spawn`, `nox_http_*`, …). These are the *fast* primitives: names, signatures and the data layouts they imply change as the compiler improves. Only the symbols declared in `include/nox_nni.h` are public. - **Object layouts.** The reference-count header in front of every managed object, the packed length/ASCII header of `str`, the list header (length, capacity and the `data` pointer to the element buffer), dictionary buckets, class instances (type tag, vtable pointer, fields), closures and `Task`/`Channel` objects. - **The runtime state.** The per-program (or per-worker) `RuntimeState`, allocator plumbing, cycle-collector tables and scheduler structures. The state is always threaded through generated code as a hidden first parameter — there is no hidden global state. - **Generated symbol names.** Mangled names like `Class_method`, `tuple__int_str`, `__nox_*`, `$name__cbtramp`. - **Intermediate representations.** The QBE `.ssa` and LLVM `.ll` text emitted by the compiler. - **Prelude internals.** Everything in the always-merged prelude (`stdlib/nox/core.nox`) beyond its documented names. - **Separate-compilation formats.** There is none: a program is always compiled from source as one unit. A `.o` built by one Nox version is not guaranteed to link with output of another. ## Why it is private Keeping this layer private is what lets Nox change its memory management (reference-counting scheme, arenas, a nursery), its string representation (the 2.0 `str` already carries a length and an ASCII flag), its backends and its scheduler **without** breaking any Nox program, library or plugin. Every exposure would become a compatibility burden. ## The one deliberate exception for kernels A freestanding runtime requires a kernel-provided allocator registered with `nox_allocator_install` ([Freestanding](https://noxlang.com/docs/tools/freestanding/)). That function pair is a small, documented ABI of its own, and it is part of the same **trust boundary** as `extern def`: a wrong allocator corrupts the whole program. **Threading contract.** The freestanding runtime is single-threaded (no scheduler pool, no OS threads), so the registered `kernel_alloc`/`kernel_free` are called from one thread at a time and need not be thread-safe, but they **must not be called re-entrantly from an interrupt handler** while the runtime is inside an allocation, and they must return memory aligned to at least 8 bytes (the ARC header assumes it). A kernel that runs Nox code on several cores must give each core its own runtime state and allocator, or serialise them itself; the runtime does no locking around these two hooks. Hosted builds never use this hook (they use the platform allocator, which is thread-safe). ## For contributors The rules for changing this layer are in [Contributing](https://noxlang.com/docs/internals/contributing/) and [Runtime](https://noxlang.com/docs/internals/runtime/): every code-generation change must be verified on **both** backends, snapshot-tested, and — if it touches layouts — re-run through the leak, double-free and `GeneralPurposeAllocator` safety suites. --- # Stability and compatibility This page is the single compatibility matrix for Nox 2.x. The long-form policy is in [Versioning](https://noxlang.com/docs/reference/versioning/). ## The promise | Surface | Promise within 2.x | Granularity | |---|---|---| | Language semantics ([reference](https://noxlang.com/docs/language/)) | source compatibility | every documented behaviour | | Public standard library ([reference](https://noxlang.com/docs/stdlib/)) | source compatibility; signatures and documented behaviour do not change; new parameters only with defaults | every documented name | | `nox.reflect` | source compatibility | the whole module | | `nox.json` manifest, `nox.lock` format | compatible; new optional fields may be added | file formats | | `noxc` subcommands and documented flags | existing behaviour kept; new flags may be added | CLI | | **NNI v1** | **binary compatibility** — a plugin built against NNI v1 loads on every Nox implementing NNI v1; members are only appended to `NoxApiV1` | C ABI | | **Plugin API 1** | manifest format and `nox.plugin` semantics fixed; optional fields may be added | manifest + Nox module | | `extern def` C-ABI type mapping | fixed | FFI | | **Internal runtime ABI**, IR, generated symbols | **none** | — | | Diagnostics *text* | **none** — the error *kind* is stable, the wording may improve in any release | messages | | Performance characteristics | not a promise (they improve) | — | ## Changes to the stable surfaces since 2.0 Everything below is additive: a program, library or plugin written for 2.0 builds and runs unchanged. | Surface | Since 2.0 | |---|---| | **NNI v1** | no change: `NOX_NNI_ABI_VERSION` is still 1 and `NoxApiV1` has the same members in the same order. The documentation is checked against `include/nox_nni.h` on every change (`scripts/check_docs.py`). Fuzzing found and fixed three bugs in the host side in 2.1.149; none changed the ABI. | | **Plugin API 1** | no change to the manifest or to `nox.plugin`. | | **NAPI (language and standard library)** | additions only: variadic and implicit-`None` functions documented, new builtins (`pow` with a modulus, `hex`, `oct`, `bin`, `int(text, base)`, `min`/`max` `default=`), new modules (`nox.lz4`, `nox.xxhash`, `nox.yyjson`, `nox.pcre2`, `nox.brotli`, and `compress` in `nox.zstd`), and the package `source` label. See [What's new in 2.2](https://noxlang.com/docs/whatsnew/2.2/). | | **Platforms** | Windows x86-64 and Linux riscv64 cross-compilation from any host with `zig`; iOS and Android remain experimental. | ## What a release number means `MAJOR.MINOR.PATCH`: - **PATCH** — bug fixes, performance work, documentation. Never breaks a valid program. - **MINOR** — new features, new standard-library modules or functions, new flags. Never breaks a valid program; a name may be *deprecated* (kept working, documented as deprecated). - **MAJOR** — the only place something deprecated may be removed or semantics may change. 2.0.0 is such a release; its changes are listed in [Migrating from 1.x](https://noxlang.com/docs/whatsnew/migrating/). Pre-releases (`2.0.0-rc.1`) carry no promise. ## Deprecation A deprecated name stays functional for **at least one MINOR release**, is marked in the reference and the changelog, and is removed no earlier than the next MAJOR release. Security fixes may take effect immediately. ## Backends LLVM and QBE are two implementations of one language. Both are tested against the entire golden corpus and **must agree on program output** (including integer overflow behaviour and keyword-argument evaluation order). Differences are limited to speed, to the scheduler (parallel under LLVM, single-threaded under QBE) and to the argument/result types allowed for `spawn`; correct programs do not depend on them. ## Platforms Tier 1 (tested in CI on every commit): macOS arm64, Linux x86-64, Linux arm64. Windows x86-64 runs the Debug `zig build test` corpus and end-to-end LLVM/QBE smoke tests on every commit (Release modes are not run there). See [Platforms](https://noxlang.com/docs/reference/platforms/). ## What this means for you - A **program** you write against the documented language and library keeps working across 2.x. - A **library or framework** you write against [NAPI](https://noxlang.com/docs/apis/napi/) does too, as long as it stays within it. - A **native extension** built against NNI v1 keeps loading; add a [manifest](https://noxlang.com/docs/apis/plugin-api/) to make it self-describing. - Do not depend on error messages, symbol names, IR, or runtime layouts. --- # The standard library The standard library is written in Nox itself (`stdlib/nox/*.nox`) with thin Zig shims wherever the operating system is involved. It ships with every compiler and is imported with `import nox.` or `from nox. import …`. Everything on these pages is part of the [stable Nox API](https://noxlang.com/docs/apis/napi/): signatures and documented behaviour do not change within 2.x. ## How to read these pages Each module page states how to import it, the **capability** it needs, a reference table of every public function and class, runnable examples whose output is checked, and notes about limits and traps. Three conventions recur: - **Qualified vs unqualified.** Ordinary functions are called qualified (`nox.strings.upper(s)`); `extern def` bindings are never name-mangled, so the few of those (the `libm` functions in [`nox.math`](https://noxlang.com/docs/stdlib/math/)) are called unqualified. Each page says which. - **Exceptions.** Each module that can fail defines its own exception class (`FsError`, `JsonError`, …), a subclass of `Exception`. Import the class by name to catch it (`from nox.fs import FsError`); qualified names are not accepted in an `except` clause. The text of messages produced by the library is not part of the API. - **Indexes.** Positions are zero-based everywhere, including SQL parameter indexes. ## Capabilities Every module has a **capability** set — the kind of authority it needs. In the default `hosted` profile all are available; the `freestanding` profile (kernels, no operating system) permits only modules with no capability requirement. `nox.crypto` and `nox.time` are finer-grained: only the functions that need entropy or a clock are marked. | Capability | Meaning | Modules | |---|---|---| | none | pure computation | `strings`, `mathx`, `bigint`, `decimal`, `fraction`, `argparse`, `fnmatch`, `random`, `collections`, `bits`, `buffer`, `binary`, `path`, `console`, `json`, `toml`, `yaml`, `csv`, `regex`, `unicode`, `template`, `validate`, `url`, `gzip`, `tar`, `zip`, `zstd`, `protobuf`, `db`, `orm`, `router`, `reflect`, `web`, `mem`, `test`, `uuid`, `base64`, `jwt`, `ed25519`, `crypto`*, `time`* | | `filesystem` | files and directories | `fs`, `glob`, `tempfile`, `sqlite`, `timezone`, `wasm` | | `network` | sockets | `http`, `websocket`, `tls`, `smtp`, `postgres`, `mysql`, `redis`, `redis_cluster`, `grpc`, `grpc_server`, `udp`, `dns`, `safehttp` | | `network` + `filesystem` | both | `transfer` | | `process` | the process and its children | `os`, `process`, `signal`, `terminal` | | `threads` | native threads | `thread`, `atomic` | | `clock` | reading the system clock | `log` (and the clock functions of `time`) | | `shared_memory` | cross-process memory | `sharedmem` | | `libc_math` | the C math library | `math` | | `entropy` | operating-system randomness | the salt-generating functions of `crypto` | `native` and `plugin` are hosted-only (they are not on the freestanding allow-list). `nox.base64` and `nox.jwt` are pure Nox and are available on freestanding and on a mobile target; `nox.bytes`, `nox.unicode` and `nox.web` are available on a mobile target too (not `nox.unicode` on freestanding, whose runtime has no Unicode tables). On a mobile target, `nox.mysql` and `nox.postgres` use drivers written in Zig over the operating system's sockets instead of `libmysqlclient`/`libpq` (see their pages for the TLS limits), while `nox.http.serve_tls` (including the file-descriptor and multicore TLS variants) and `nox.http.serve_ws_tls` are still rejected because they load libssl. The HTTP client, `nox.tls`, `nox.websocket` and `nox.smtp` stay available. `nox.hpy` is a preview package profile (`nox-hpy-host-v1`); it is not part of the stable 2.x API yet. See [HPy host v1](https://noxlang.com/docs/internals/hpy-wasm/) and [Freestanding](https://noxlang.com/docs/tools/freestanding/). ## The prelude Some names are available **without any import**: `print`, `len`, `range`, `sorted`, `min`, `max`, `sum`, `abs`, `round`, `enumerate`, `zip`, `map`, `filter`, `input`, the exception classes (`Exception`, `ValueError`, `IndexError`, `KeyError`, `ZeroDivisionError`, `AssertionError`, `CancelledError`), `JsonValue`, and the generic concurrency types (`Task`, `Channel`, …). They are documented in [Built-in functions](https://noxlang.com/docs/language/builtins/). ## Modules by area ### Text and numbers | Module | Purpose | |---|---| | [`nox.strings`](https://noxlang.com/docs/stdlib/strings/) | split, join, trim, replace, search, padding, byte-level helpers | | [`nox.math`](https://noxlang.com/docs/stdlib/math/), [`nox.mathx`](https://noxlang.com/docs/stdlib/mathx/) | floating-point mathematics (libm-backed / libc-free) | | [`nox.bigint`](https://noxlang.com/docs/stdlib/bigint/), [`nox.decimal`](https://noxlang.com/docs/stdlib/decimal/), [`nox.fraction`](https://noxlang.com/docs/stdlib/fraction/) | arbitrary-precision integers, exact decimals, exact rationals | | [`nox.random`](https://noxlang.com/docs/stdlib/random/) | pseudo-random numbers and shuffling | | [`nox.time`](https://noxlang.com/docs/stdlib/time/) | wall clock, sleeping, calendar date-times, monotonic intervals | | [`nox.tasks`](https://noxlang.com/docs/stdlib/tasks/) | task groups: add, wait, limit, cancel | | [`nox.property`](https://noxlang.com/docs/stdlib/property/) | seeded property-based testing with size shrinking and replay | | [`nox.regex`](https://noxlang.com/docs/stdlib/regex/), [`nox.pcre2`](https://noxlang.com/docs/stdlib/pcre2/) | regular expressions (groups, alternation, captures); PCRE2 with JIT | | [`nox.unicode`](https://noxlang.com/docs/stdlib/unicode/) | Unicode normalization (NFC/NFD/NFKC/NFKD) and Turkish case mapping | | [`nox.template`](https://noxlang.com/docs/stdlib/template/) | `{{ name }}` text templates, HTML-escaped by default | ### Data structures and binary data | Module | Purpose | |---|---| | [`nox.collections`](https://noxlang.com/docs/stdlib/collections/) | stack, queue, deque, set, counter, ordered map, LRU cache, heap, priority queue | | [`nox.bits`](https://noxlang.com/docs/stdlib/bits/) | rotations, byte swaps, endianness, single-bit helpers | | [`nox.buffer`](https://noxlang.com/docs/stdlib/buffer/) | fixed-size byte buffers and spans | | [`nox.binary`](https://noxlang.com/docs/stdlib/binary/) | cursor-based binary readers and writers | | [`nox.bytes`](https://noxlang.com/docs/stdlib/bytes/) | `str` to `Buffer` byte conversion (hosted) | | [`nox.protobuf`](https://noxlang.com/docs/stdlib/protobuf/) | Protocol Buffers wire format: writer and reader (varint, zigzag, fixed, nested, packed) | ### Files, processes and the environment | Module | Purpose | |---|---| | [`nox.fs`](https://noxlang.com/docs/stdlib/fs/) | read, write, copy, rename, list, inspect | | [`nox.path`](https://noxlang.com/docs/stdlib/path/) | path manipulation | | [`nox.os`](https://noxlang.com/docs/stdlib/os/) | arguments, environment variables, working directory, exit | | [`nox.process`](https://noxlang.com/docs/stdlib/process/) | run external programs | | [`nox.signal`](https://noxlang.com/docs/stdlib/signal/) | `SIGINT`/`SIGTERM`/… as flags a task can poll | | [`nox.terminal`](https://noxlang.com/docs/stdlib/terminal/) | TTY detection, size, raw mode, echo, raw input/output | | [`nox.timezone`](https://noxlang.com/docs/stdlib/timezone/) | IANA time zones: offset, abbreviation, DST, local ↔ UTC conversion | | [`nox.console`](https://noxlang.com/docs/stdlib/console/), [`nox.log`](https://noxlang.com/docs/stdlib/log/) | levelled output without / with timestamps | ### Formats and encodings | Module | Purpose | |---|---| | [`nox.json`](https://noxlang.com/docs/stdlib/json/), [`nox.yyjson`](https://noxlang.com/docs/stdlib/yyjson/), [`nox.toml`](https://noxlang.com/docs/stdlib/toml/), [`nox.yaml`](https://noxlang.com/docs/stdlib/yaml/), [`nox.csv`](https://noxlang.com/docs/stdlib/csv/) | parsers and writers | | [`nox.validate`](https://noxlang.com/docs/stdlib/validate/) | validate JSON against a schema | | [`nox.url`](https://noxlang.com/docs/stdlib/url/) | URLs, percent-encoding, query strings | | [`nox.base64`](https://noxlang.com/docs/stdlib/base64/), [`nox.uuid`](https://noxlang.com/docs/stdlib/uuid/), [`nox.gzip`](https://noxlang.com/docs/stdlib/gzip/), [`nox.tar`](https://noxlang.com/docs/stdlib/tar/), [`nox.zip`](https://noxlang.com/docs/stdlib/zip/), [`nox.zstd`](https://noxlang.com/docs/stdlib/zstd/), [`nox.brotli`](https://noxlang.com/docs/stdlib/brotli/), [`nox.lz4`](https://noxlang.com/docs/stdlib/lz4/), [`nox.xxhash`](https://noxlang.com/docs/stdlib/xxhash/) | Base64, UUIDs, compression and archives | | [`nox.wasm`](https://noxlang.com/docs/stdlib/wasm/) | Run WebAssembly modules (embedded interpreter, sandboxed, fuel and memory limits) | | [`nox.ffi`](https://noxlang.com/docs/stdlib/ffi/) | `Callback[F]` handles: lambdas and closures as C callbacks | ### Security | Module | Purpose | |---|---| | [`nox.crypto`](https://noxlang.com/docs/stdlib/crypto/) | hashes, HMAC, secure randomness, password hashing | | [`nox.ed25519`](https://noxlang.com/docs/stdlib/ed25519/) | Ed25519 signature verification and key fingerprints | | [`nox.jwt`](https://noxlang.com/docs/stdlib/jwt/) | HS256 JSON Web Tokens | ### Networking and the web | Module | Purpose | |---|---| | [`nox.http`](https://noxlang.com/docs/stdlib/http/) | HTTP client and server (TLS and WebSocket upgrade included) | | [`nox.transfer`](https://noxlang.com/docs/stdlib/transfer/) | stream HTTP bodies to and from files | | [`nox.router`](https://noxlang.com/docs/stdlib/router/) | path routing and middleware | | [`nox.web`](https://noxlang.com/docs/stdlib/web/) | cookies, CORS, rate limiting, request ids, access log, security headers | | [`nox.websocket`](https://noxlang.com/docs/stdlib/websocket/) | WebSocket client and server connection | | [`nox.tls`](https://noxlang.com/docs/stdlib/tls/) | client TLS streams | | [`nox.udp`](https://noxlang.com/docs/stdlib/udp/) | UDP datagram sockets (loopback/telemetry/discovery), fiber-friendly receive | | [`nox.safehttp`](https://noxlang.com/docs/stdlib/safehttp/) | HTTP client safe for untrusted URLs: address checks on every redirect hop, DNS-rebinding proof | | [`nox.ip`](https://noxlang.com/docs/stdlib/ip/) | IPv4/IPv6 parsing and classification (`is_global`, private/loopback/metadata...) for SSRF defences | | [`nox.dns`](https://noxlang.com/docs/stdlib/dns/) | explicit DNS resolution (`resolve(host)`) for resolve-validate-connect SSRF defences; pairs with `nox.http.request(..., connect_ip=...)` | | [`nox.smtp`](https://noxlang.com/docs/stdlib/smtp/) | send e-mail | ### Databases | Module | Purpose | |---|---| | [`nox.db`](https://noxlang.com/docs/stdlib/db/) | shared `Row`, `Statement` and the `DbConnection` protocol | | [`nox.sqlite`](https://noxlang.com/docs/stdlib/sqlite/), [`nox.postgres`](https://noxlang.com/docs/stdlib/postgres/), [`nox.mysql`](https://noxlang.com/docs/stdlib/mysql/) | drivers | | [`nox.grpc`](https://noxlang.com/docs/stdlib/grpc/) | gRPC client over HTTP/2 (h2c or TLS): unary, streaming, bidirectional streams, metadata, mTLS, gzip | | [`nox.grpc_server`](https://noxlang.com/docs/stdlib/grpc_server/) | gRPC server on top of `nox.http`: unary, server and client streaming, status codes | | [`nox.redis_cluster`](https://noxlang.com/docs/stdlib/redis_cluster/) | Redis Cluster client: hash slots, `-MOVED`/`-ASK` redirects, topology refresh | | [`nox.redis`](https://noxlang.com/docs/stdlib/redis/) | Redis client: commands, Streams, scripts, AUTH/TLS | | [`nox.orm`](https://noxlang.com/docs/stdlib/orm/) | parameterised CRUD helpers over any driver | ### Concurrency and low level | Module | Purpose | |---|---| | [`nox.thread`](https://noxlang.com/docs/stdlib/thread/) | worker threads and thread channels | | [`nox.atomic`](https://noxlang.com/docs/stdlib/atomic/) | atomic counters and flags shared between workers | | [`nox.sharedmem`](https://noxlang.com/docs/stdlib/sharedmem/) | shared memory between processes | | [`nox.mem`](https://noxlang.com/docs/stdlib/mem/) | bulk typed-pointer operations and volatile access | ### Reflection, extensions and testing | Module | Purpose | |---|---| | [`nox.reflect`](https://noxlang.com/docs/stdlib/reflect/) | decorator and class metadata | | [`nox.native`](https://noxlang.com/docs/stdlib/native/), [`nox.plugin`](https://noxlang.com/docs/stdlib/plugin/) | load native plugins ([NNI](https://noxlang.com/docs/apis/nni/), [Plugin API](https://noxlang.com/docs/apis/plugin-api/)) | | [`nox.test`](https://noxlang.com/docs/stdlib/test/) | assertions and test suites | ## Third-party libraries Anything outside `nox.*` — web frameworks such as [Nyx](https://github.com/mburakmmm/nyx), database layers, utilities — comes from packages: see [Packages](https://noxlang.com/docs/tools/packages/) and the [noxpkg registry](https://noxlang.com/docs/tools/noxpkg/). --- # nox.strings Function-style string utilities. Everything here is also available as methods on `str` (`s.upper()`, `s.split(",")`, …; see [Strings](https://noxlang.com/docs/language/strings/)); the module form is useful when you want to pass an operation as a function value or you need the byte-level helpers. ```text import nox.strings # then: nox.strings.upper(s) ``` **Capability:** none (available in every profile). ## Functions | Function | Description | |---|---| | `split(s, sep)` | splits `s` on every occurrence of `sep`; empty fields are kept (`"a,b,,c"` → `['a','b','','c']`) | | `splitn(s, sep, n)` | at most `n` splits: the last element holds the remainder | | `rsplit(s, sep)` | splits like `split` but returns the pieces **from the right** (`"a,b,c"` → `['c','b','a']`) | | `join(parts, sep)` | joins a `list[str]` with `sep` | | `trim(s)`, `trim_start(s)`, `trim_end(s)` | removes surrounding / leading / trailing whitespace | | `upper(s)`, `lower(s)` | ASCII case conversion | | `replace(s, old, new)` | replaces every occurrence | | `starts_with(s, prefix)`, `ends_with(s, suffix)` | prefix / suffix tests | | `index_of(s, needle)` | **byte** offset of the first occurrence, or `-1` | | `contains(s, needle)` | substring test | | `repeat(s, n)` | `s` repeated `n` times | | `eq_ignore_case(a, b)` | ASCII case-insensitive equality | | `pad_left(s, width, ch)`, `pad_right(s, width, ch)` | pads to `width` with the one-character string `ch` | | `zfill(s, width)` | left-pads with `"0"` | | `byte_at(s, idx)` | the byte value (0–255) at byte offset `idx` | | `char_from_byte(b)` | a one-byte string from a byte value | | `byte_len(s)` | length in **bytes** (`len(s)` counts code points) | ```nox import nox.strings print(nox.strings.split("a,b,,c", ","), nox.strings.splitn("a,b,c,d", ",", 2), nox.strings.rsplit("a,b,c", ",")) print(nox.strings.trim(" hi \n"), "|", nox.strings.trim_start(" hi "), "|", nox.strings.trim_end(" hi "), "|") print(nox.strings.upper("abc"), nox.strings.lower("ABC"), nox.strings.replace("aXbXc", "X", "-")) print(nox.strings.byte_at("A", 0), nox.strings.char_from_byte(66), nox.strings.byte_len("héllo"), len("héllo")) print(nox.strings.join(["a", "b"], "+"), nox.strings.starts_with("hello", "he"), nox.strings.ends_with("hello", "lo")) print(nox.strings.index_of("hello", "l"), nox.strings.index_of("hello", "z"), nox.strings.contains("hello", "ell")) print(nox.strings.repeat("ab", 3), nox.strings.eq_ignore_case("AbC", "aBc")) print(nox.strings.pad_left("7", 3, "0"), nox.strings.pad_right("7", 3, "."), nox.strings.zfill("7", 3)) ``` ```output ['a', 'b', '', 'c'] ['a', 'b,c,d'] ['c', 'b', 'a'] hi | hi | hi | ABC abc a-b-c 65 B 6 5 a+b True True 2 -1 True ababab True 007 7.. 007 ``` ## Notes - Positions returned by `index_of` and taken by `byte_at` are **byte** offsets; the `str` methods `find`/`index` and `s[i]` use **code points**. For ASCII text they agree. - Case conversion and whitespace trimming follow ASCII rules; non-ASCII letters are left unchanged. - For everyday work prefer the string methods: they are available without an import and cover more (`capitalize`, `partition`, `splitlines`, …). --- # nox.math Floating-point mathematics backed by the C library's `libm`. ```text import nox.math from nox.math import sqrt, pi ``` **Capability:** `libc_math` — hosted programs only. For code that must run in a freestanding profile use [`nox.mathx`](https://noxlang.com/docs/stdlib/mathx/), the same functions with no libc dependency. ## Calling convention — read this first The `libm` functions are bound with `extern def`, which is never name-mangled, so they are called **unqualified** after the import: ```nox import nox.math print(sqrt(16.0), pow(2.0, 10.0), floor(2.7), ceil(2.1)) ``` ```output 4.0 1024.0 2.0 3.0 ``` The pure-Nox helpers (`ln`, `pi`, `e`, `min`, `max`, `abs`) are ordinary functions and are called **qualified**: `nox.math.pi()`, `nox.math.ln(x)`. `from nox.math import sqrt, pi` imports both kinds by name. ## Functions | Function | Description | Call as | |---|---|---| | `sqrt(x)` | square root | `sqrt(x)` | | `pow(x, y)` | `x` raised to `y` | `pow(x, y)` | | `floor(x)`, `ceil(x)` | round down / up to a whole number (still a `float`) | `floor(x)` | | `sin(x)`, `cos(x)`, `tan(x)` | trigonometric functions (radians) | `sin(x)` | | `atan2(y, x)` | the angle of the point `(x, y)` | `atan2(y, x)` | | `exp(x)` | *e* to the power `x` | `exp(x)` | | `log(x)` | natural logarithm (the libm name) | `log(x)` | | `ln(x)` | natural logarithm (alias of `log`) | `nox.math.ln(x)` | | `pi()` | π | `nox.math.pi()` | | `e()` | Euler's number | `nox.math.e()` | | `min(a, b)`, `max(a, b)`, `abs(x)` | `float` versions of the built-ins | `nox.math.min(a, b)` | All arguments and results are `float`. Domain errors follow IEEE-754 (`sqrt(-1.0)` is `nan`; `log(0.0)` is `-inf`) — nothing raises. ```nox import nox.math print(nox.math.pi() > 3.14159, nox.math.e() > 2.71828, nox.math.ln(1.0), nox.math.min(2.0, 3.0), nox.math.abs(-2.5)) print(sin(0.0), cos(0.0), atan2(1.0, 1.0) > 0.78, exp(0.0), log(1.0)) ``` ```output True True 0.0 2.0 2.5 0.0 1.0 True 1.0 0.0 ``` ## Choosing `nox.math` or `nox.mathx` | | `nox.math` | `nox.mathx` | |---|---|---| | Backed by | the platform `libm` | Zig's own math (no libc) | | Freestanding | no | yes | | Call style | `sqrt(x)` (unqualified externs) | `nox.mathx.sqrt(x)` (always qualified) | Use `nox.mathx` for new code, and for anything that may run without a C library. Results may differ in the last bit between the two for some inputs. --- # nox.mathx The same mathematical functions as [`nox.math`](https://noxlang.com/docs/stdlib/math/), implemented without any C library. They are ordinary Nox functions, so they are always called **qualified**, and the module works in every profile — including freestanding builds where no libc exists. ```text import nox.mathx ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `sqrt(x)` | square root | | `pow(x, y)` | `x` raised to `y` | | `floor(x)`, `ceil(x)` | round down / up (result is a `float`) | | `sin(x)`, `cos(x)`, `tan(x)` | trigonometry, radians | | `atan2(y, x)` | the angle of the point `(x, y)` | | `exp(x)` | *e* to the power `x` | | `log(x)`, `ln(x)` | natural logarithm (`ln` is an alias) | | `pi()`, `e()` | the constants π and *e* | | `min(a, b)`, `max(a, b)`, `abs(x)` | `float` helpers | ```nox import nox.mathx print(nox.mathx.sqrt(16.0), nox.mathx.pow(2.0, 10.0), nox.mathx.floor(2.7), nox.mathx.ceil(2.1)) print(nox.mathx.sin(0.0), nox.mathx.cos(0.0), nox.mathx.exp(0.0), nox.mathx.log(1.0), nox.mathx.pi() > 3.14159) print(nox.mathx.min(2.0, 3.0), nox.mathx.max(2.0, 3.0), nox.mathx.abs(-1.5), nox.mathx.atan2(1.0, 1.0) > 0.78) ``` ```output 4.0 1024.0 2.0 3.0 0.0 1.0 1.0 0.0 True 2.0 3.0 1.5 True ``` Edge cases follow IEEE-754: `sqrt` of a negative number is `nan`, `log(0.0)` is `-inf`, and nothing raises. ## Which one? Prefer `nox.mathx` in new code. `nox.math` remains for existing code that calls the unqualified libm names. See [`nox.math`](https://noxlang.com/docs/stdlib/math/#choosing-noxmath-or-noxmathx) for the comparison. --- # nox.bigint Arbitrary-precision integers with Python semantics. ```text import nox.bigint from nox.bigint import BigInt, BigIntError, big, from_int, parse, factorial ``` **Capability:** none. The arithmetic is done by the runtime (Zig's `std.math.big`), so the module also works on freestanding, wasm and mobile targets. A `BigInt` is an immutable value; operators return new values. `//` and `%` round towards negative infinity like Python (the remainder takes the divisor's sign), `>>` is an arithmetic shift, and `&`, `|`, `^` behave as on infinitely sign-extended two's complement. ## Creating values | Function | Description | |---|---| | `big(x)` / `from_int(x)` | from an `int` | | `parse(s, base=10)` | from text with an optional `+`/`-` sign and `_` separators, base 2–36; `ValueError` for invalid text | | `factorial(n)` | `n!` | ## Operators and methods | Syntax | Meaning | |---|---| | `a + b`, `a - b`, `a * b`, `-a` | arithmetic | | `a // b`, `a % b` | floor division and modulo; `ZeroDivisionError` when `b` is zero | | `a ** e` | power with an `int` exponent `0 <= e < 2**32`; `BigIntError` otherwise | | `a << n`, `a >> n` | shifts by an `int` (`BigIntError` when negative or too large) | | `a & b`, `a \| b`, `a ^ b` | bitwise operations | | `a == b`, `<`, `<=`, `>`, `>=` | comparisons | | `a.divmod(b)` | `(a // b, a % b)` | | `a.abs()`, `a.sign()`, `a.is_zero()`, `a.is_odd()`, `a.is_even()` | basic queries (`sign()` is -1, 0 or 1) | | `a.bit_length()` | bits needed for `abs(a)` (0 for zero) | | `a.gcd(b)` | greatest common divisor (non-negative) | | `a.pow_mod(e, m)` | `a ** e mod m` for `e >= 0` and `m > 0`, result in `[0, m)` | | `a.isqrt()` | integer square root of a non-negative value | | `a.is_probable_prime(rounds=8)` | Miller–Rabin with the first twelve primes as bases (exact below 3.3e24) plus `rounds` more | | `a.to_str(base=10)` | text in base 2–36 (lower case) | | `a.fits_int()`, `a.to_int()` | conversion to a 64-bit `int`; `to_int()` raises `BigIntError` when it does not fit | ```nox import nox.bigint from nox.bigint import BigInt, big, parse, factorial a: BigInt = parse("123456789012345678901234567890") b: BigInt = parse("-987654321098765432109876543210") print(a + b) print(a * b) print(big(-7) // big(2), big(-7) % big(2), big(7) // big(-2), big(7) % big(-2)) print(factorial(30)) print(big(2) ** 100) print(big(3).pow_mod(big(200), big(1000000007))) print(big(255).to_str(16), parse("ff", 16)) print(big(97).is_probable_prime(), big(91).is_probable_prime()) ``` ```output -864197532086419753208641975320 -121932631137021795226185032733622923332237463801111263526900 -4 1 -4 -1 265252859812191058636308480000000 1267650600228229401496703205376 136318165 ff 255 True False ``` ## Notes - The internal representation is a `str` (a sign byte followed by the little-endian magnitude), so copying a `BigInt` is cheap and there is nothing to release. - Multiplication and division are schoolbook/Knuth algorithms: fine for thousands of digits, not tuned for millions. - The type is strict about operands: `a + 5` is a type error; write `a + big(5)`. --- # nox.decimal Exact decimal numbers for money and measurements, built on [`nox.bigint`](https://noxlang.com/docs/stdlib/bigint/). ```text import nox.decimal from nox.decimal import Decimal, DecimalError, parse, from_int, from_bigint ``` **Capability:** none (pure Nox on top of `nox.bigint`). A `Decimal` is `coefficient × 10^exponent` with a `BigInt` coefficient. Addition, subtraction and multiplication are **exact** (no rounding, no precision limit). Division and rounding take an explicit number of decimal places and a rounding mode; there is deliberately no global context, so a calculation never depends on hidden state. **Rounding modes** (same meaning as Python's `decimal`): `"half_even"` (default), `"half_up"` (ties away from zero), `"half_down"` (ties toward zero), `"down"` (toward zero), `"up"` (away from zero), `"floor"`, `"ceiling"`. | Function / method | Description | |---|---| | `parse(s)` | from `"12.345"`, `"-0.5"`, `"1e3"`, `"2.5E-4"`; `ValueError` for invalid text | | `from_int(x)`, `from_bigint(x)` | from integers | | `a + b`, `a - b`, `a * b`, `-a` | exact arithmetic | | `a == b`, `<`, `<=`, `>`, `>=`, `a.compare(b)` | numeric comparison (`1.0 == 1.00`); `compare` returns -1, 0 or 1 | | `a.quantize(places, mode="half_even")` | round to `places` decimal places (negative `places` rounds to tens, hundreds, ...); the result has exponent `-places` | | `a.div(b, places, mode="half_even")` | `a / b` rounded to `places` decimal places; `ZeroDivisionError` if `b` is zero | | `a.normalize()` | remove trailing zeros (`1.500` becomes `1.5`) | | `a.abs()`, `a.sign()`, `a.is_zero()`, `a.scale()` | basic queries (`scale()` is the number of decimal places) | | `a.to_bigint()` | integer part, truncated toward zero | | `a.to_float()` | nearest `float` | | `str(a)` | plain notation, never an exponent: `12.345`, `-0.001`, `1200` | An unknown rounding mode raises `DecimalError`. Zero has no sign (`-0.00` prints as `0.00`). ```nox import nox.decimal from nox.decimal import Decimal, parse price: Decimal = parse("19.99") qty: Decimal = parse("3") total: Decimal = price * qty print(total) print(total.div(parse("7"), 4)) print(parse("2.675").quantize(2), parse("2.675").quantize(2, "half_up"), parse("-2.5").quantize(0, "floor")) print(parse("0.1") + parse("0.2") == parse("0.3"), parse("1.500").normalize()) ``` ```output 59.97 8.5671 2.68 2.68 -3 True 1.5 ``` --- # nox.fraction Exact rational numbers, built on [`nox.bigint`](https://noxlang.com/docs/stdlib/bigint/). ```text import nox.fraction from nox.fraction import Fraction, make, from_ints, parse_fraction ``` **Capability:** none (pure Nox on top of `nox.bigint`). A `Fraction` is always in lowest terms with a positive denominator, so `==` compares numerators and denominators directly. | Function / method | Description | |---|---| | `from_ints(p, q=1)` | `p/q` from two `int`s; `ZeroDivisionError` when `q` is zero | | `make(p, q)` | the same from two `BigInt`s | | `parse_fraction(s)` | from `"3/4"`, `"-7"`, `"0.125"`, `"1e-3"`; `ValueError` for invalid text | | `a + b`, `a - b`, `a * b`, `a / b`, `-a`, `a ** e` | exact arithmetic (`e` is an `int`, may be negative) | | `a == b`, `<`, `<=`, `>`, `>=` | comparisons | | `a.numerator()`, `a.denominator()` | the parts, as `BigInt` | | `a.floor()`, `a.ceil()`, `a.trunc()`, `a.round()` | to a `BigInt`; `round` ties to even like Python | | `a.abs()`, `a.sign()`, `a.is_integer()`, `a.reciprocal()` | basic operations | | `a.to_float()` | nearest `float` | | `str(a)` | `"3/4"`, or `"3"` for integers | ```nox import nox.fraction from nox.fraction import Fraction, from_ints, parse_fraction a: Fraction = from_ints(1, 3) b: Fraction = from_ints(-5, 10) print(a + b, a * b, a / b) print(b.floor(), b.ceil(), from_ints(5, 2).round(), from_ints(7, 2).round()) print(parse_fraction("0.125"), from_ints(2, 3) ** -3) ``` ```output -1/6 -1/6 -2/3 -1 0 2 4 1/8 27/8 ``` --- # nox.argparse Command-line argument parsing, modelled on Python's `argparse`. ```text import nox.argparse from nox.argparse import ArgumentParser, Namespace, ArgumentError ``` **Capability:** none. The parser works on a `list[str]`, so it is pure; pass it the program's arguments yourself (for example from `nox.os.arg_count()` / `nox.os.arg(i)`). Types are static, so the result is a `Namespace` you query by name instead of an object with dynamic attributes. An option's name (its *dest*) is the long name without the dashes, with `-` turned into `_` (`--max-count` is `max_count`); a positional's name is the name you gave it. ## Declaring arguments | Method | Meaning | |---|---| | `ArgumentParser(prog, description="")` | a new parser | | `add_flag(short, long, help="")` | boolean flag (`-v`, `--verbose`); pass `""` to omit a form | | `add_option(short, long, default="", help="", required=False)` | string option: `-o FILE`, `-oFILE`, `--output FILE`, `--output=FILE` | | `add_choice_option(short, long, choices, default="", help="")` | string option restricted to `choices` | | `add_int_option(short, long, default=0, help="", required=False)` | integer option | | `add_float_option(short, long, default=0.0, help="", required=False)` | floating-point option | | `add_multi_option(short, long, help="")` | repeatable option, collected in order | | `add_positional(name, help="")` | required positional argument | | `add_optional_positional(name, default="", help="")` | optional positional (after the required ones) | | `add_rest(name, help="")` | all remaining positionals (zero or more); declare it last | | `add_command(name, parser, help="")` | sub-command: when the first positional is `name`, the rest is parsed by `parser` | ## Parsing `parser.parse(args)` returns a `Namespace` or raises `ArgumentError` with a message such as `unrecognized arguments: --bogus`, `argument -n/--count: invalid int value: 'x'` or `the following arguments are required: file`. Short flags can be combined (`-vq`), an attached value works (`-n5`), `--` ends option parsing, negative numbers are positionals, and `-h`/`--help` stops parsing and sets `help_requested`. Long option abbreviations are **not** accepted. Behaviour matches Python's `parse_intermixed_args` on the supported feature set (checked against Python by a randomised golden test). | `Namespace` member | Meaning | |---|---| | `flag(name)` | value of a flag | | `get_str(name)`, `get_int(name)`, `get_float(name)` | option or positional value (the default when not given) | | `get_list(name)` | values of a multi option or `add_rest` | | `has(name)` | `True` when the argument was given explicitly | | `command` | the sub-command name, or `""` | | `help_requested` | `True` when `-h` or `--help` was seen | `parser.usage()` and `parser.help_text()` build the help text. ```nox import nox.argparse from nox.argparse import ArgumentParser, Namespace, ArgumentError p: ArgumentParser = ArgumentParser("tool", "Copy files.") p.add_flag("-v", "--verbose", "chatty output") p.add_int_option("-n", "--count", 1, "repeat count") p.add_positional("src", "source file") p.add_optional_positional("dst", "out.txt", "destination") ns: Namespace = p.parse(["-v", "-n", "3", "a.txt"]) print(ns.flag("verbose"), ns.get_int("count"), ns.get_str("src"), ns.get_str("dst")) try: p.parse(["-n", "x", "a.txt"]) except ArgumentError as e: print(e) print(p.usage()) ``` ```output True 3 a.txt out.txt argument -n/--count: invalid int value: 'x' usage: tool [-h] [-v] [-n COUNT] src [dst] ``` --- # nox.fnmatch Shell-style file name matching. ```text import nox.fnmatch from nox.fnmatch import fnmatch, filter_names, has_magic, escape ``` **Capability:** none (pure Nox). Matching is **case-sensitive** and works on bytes, so it is exact for ASCII names. | Pattern | Matches | |---|---| | `*` | any run of characters, including none | | `?` | exactly one character | | `[abc]`, `[a-z]` | one character from the set or range | | `[!abc]` | one character not in the set | A `[` without a closing `]` is an ordinary character. Unlike [`nox.glob`](https://noxlang.com/docs/stdlib/glob/), `fnmatch` treats a leading `.` like any other character (`*` matches `.hidden`). | Function | Description | |---|---| | `fnmatch(name, pattern)` | whether `name` matches `pattern` entirely | | `filter_names(names, pattern)` | the names that match, in order | | `has_magic(pattern)` | whether `pattern` contains `*`, `?` or `[` | | `escape(s)` | wrap special characters in `[...]` so they match literally | ```nox import nox.fnmatch from nox.fnmatch import fnmatch, filter_names print(fnmatch("report.txt", "*.txt"), fnmatch("a1", "a[0-9]"), fnmatch("ab", "a[!b]")) print(filter_names(["a.py", "b.txt", "c.py"], "*.py")) ``` ```output True True False ['a.py', 'c.py'] ``` --- # nox.glob Expand file name patterns against the file system. ```text import nox.glob from nox.glob import glob ``` **Capability:** `filesystem`. Directories are read with [`nox.fs`](https://noxlang.com/docs/stdlib/fs/). `glob(pattern, root_dir="", recursive=False)` returns the matching paths as a **sorted** `list[str]` (Python's order is unspecified). Patterns use the [`nox.fnmatch`](https://noxlang.com/docs/stdlib/fnmatch/) syntax per path component; components are separated by `/`. - `*`, `?` and `[...]` do not match names that start with `.` unless the pattern component itself starts with `.`. - With `recursive=True`, a `**` component matches zero or more directories (hidden directories are not entered). A trailing `**` also matches every file and directory below, and `dir/**` includes `dir/` itself. - A trailing `/` keeps directories only and keeps the slash in the result. - With `root_dir`, relative patterns are resolved there and the results stay relative to it. - The behaviour matches Python's `glob.glob(pattern, root_dir=..., recursive=...)` on the covered feature set (a randomised golden test compares them on a fixed tree). > **Security.** Like `nox.fs`, `glob` does no sandboxing. If the pattern or `root_dir` comes from an untrusted source, confine it first with [`nox.path.safe_join`](https://noxlang.com/docs/stdlib/path/#confining-untrusted-paths). ```nox import nox.fs import nox.tempfile from nox.tempfile import TemporaryDirectory from nox.glob import glob with TemporaryDirectory("glob-demo-") as t: nox.fs.create_dir_all(t.path + "/src/util") nox.fs.write_string(t.path + "/src/main.nox", "") nox.fs.write_string(t.path + "/src/util/io.nox", "") nox.fs.write_string(t.path + "/notes.txt", "") print(glob("*", t.path)) print(glob("src/*.nox", t.path)) print(glob("**/*.nox", t.path, True)) ``` ```output ['notes.txt', 'src'] ['src/main.nox'] ['src/main.nox', 'src/util/io.nox'] ``` --- # nox.tempfile Temporary files and directories. ```text import nox.tempfile from nox.tempfile import TemporaryDirectory, TempFileError, mkdtemp, mkstemp, gettempdir ``` **Capability:** `filesystem` (it also reads environment variables and draws random names, which are allowed wherever the file system is). | Function / class | Description | |---|---| | `gettempdir()` | the directory for temporary files: `TMPDIR`, `TEMP`, `TMP` in that order, else `/tmp` | | `mkdtemp(prefix="tmp", suffix="", dir="")` | creates a new empty directory and returns its path | | `mkstemp(prefix="tmp", suffix="", dir="")` | creates a new empty file and returns its path | | `TemporaryDirectory(prefix, suffix, dir)` | a directory removed with its contents on leaving a `with` block; `.path` is its path, `.cleanup()` removes it early | Names are `prefix` + 12 random hex digits + `suffix`, drawn from the operating system's secure random source. Directory creation is atomic (an existing name is retried); file creation is `exists` followed by a write. `TempFileError` is raised if no unique name is found after 100 tries. File permissions are the operating system defaults (not forced to `0600`). `mkstemp` returns only the path: remove the file yourself with `nox.fs.remove_file`. ```nox import nox.fs import nox.tempfile from nox.tempfile import TemporaryDirectory kept: str = "" with TemporaryDirectory("demo-") as t: nox.fs.write_string(t.path + "/data.txt", "hello") print(nox.fs.read_to_string(t.path + "/data.txt")) kept = t.path print(nox.fs.exists(kept)) ``` ```output hello False ``` --- # nox.random A fast general-purpose pseudo-random number generator (xoshiro256). Suitable for simulations, games, shuffling and tests. > **Not for security.** Use [`nox.crypto`](https://noxlang.com/docs/stdlib/crypto/) for tokens, salts, keys and anything an attacker must not be able to guess. ```text import nox.random ``` **Capability:** none. The generator is seeded from the system at start-up; call `seed` for a reproducible sequence. ## Functions | Function | Description | |---|---| | `seed(s)` | seeds the generator; the same seed gives the same sequence | | `randint(lo, hi)` | a uniform integer in `[lo, hi]` — **both ends inclusive** | | `random()` | a uniform `float` in `[0.0, 1.0)` | | `normal()` | a standard normal (Gaussian) variate: mean 0, standard deviation 1 | | `exponential(rate)` | an exponentially distributed variate with the given `rate` (mean `1 / rate`) | | `shuffle(xs)` | shuffles a `list[T]` in place (Fisher–Yates) | ```nox import nox.random nox.random.seed(42) a: int = nox.random.randint(1, 6) nox.random.seed(42) b: int = nox.random.randint(1, 6) print(a == b, a >= 1 and a <= 6) x: float = nox.random.random() print(x >= 0.0 and x < 1.0) xs: list[int] = [1, 2, 3, 4, 5] nox.random.shuffle(xs) print(len(xs), sum(xs)) print(nox.random.exponential(2.0) >= 0.0) ``` ```output True True True 5 15 True ``` ## Notes - The generator state is per program (per worker under the multi-core scheduler); seeding in one worker does not affect another. - `randint` requires `lo <= hi`. - `shuffle` works for any element type, including classes and nested lists. --- # nox.time Wall-clock time, sleeping, calendar date-times and monotonic interval measurement. ```text import nox.time ``` **Capability:** none for the module; the functions that actually read the clock — `now_ms`, `sleep_ms`, `now`, `instant_now` and the `Instant` methods — require the `clock` capability and are unavailable in freestanding profiles. The calendar arithmetic (`DateTime`, `from_epoch_ms`) is pure and available everywhere. ## Functions | Function | Description | |---|---| | `now_ms()` | milliseconds since the Unix epoch (wall clock; can jump if the system clock is changed) | | `boot_ms()` | a monotonic millisecond counter that **includes time the device spent suspended**; only differences are meaningful | | `now_ns()` | Unix time in **nanoseconds** (wall clock; resolution is platform dependent: about 1 ns on Linux/macOS, 100 ns on Windows, 1 ms in WebAssembly) | | `monotonic_ns()` | a nanosecond monotonic counter for measuring durations (only differences are meaningful; it never goes backwards) | | `sleep_ms(ms)` | waits `ms` milliseconds: inside a task it suspends only that task (other tasks keep running), elsewhere it blocks the thread. `sleep_ms(0)` inside a task is a short (about 1 ms) cooperative sleep so other tasks and timers can run | | `now()` | the current time as a `DateTime` (UTC) | | `from_epoch_ms(ms)` | converts epoch milliseconds to a `DateTime` (UTC) | | `instant_now()` | a monotonic `Instant` for measuring intervals (see "Clocks and device sleep") | | `pad2(n)` | formats `n` with at least two digits (`7` → `"07"`) | ## Clocks and device sleep | Clock | Source | While the device is suspended | |---|---|---| | `now_ms()` | wall clock (`CLOCK_REALTIME`) | keeps the real time of day; jumps if the system clock is changed | | `instant_now()` / `Instant` | `CLOCK_MONOTONIC` | **Linux and Android: not counted. macOS and iOS: counted** (`mach_continuous_time`) | | `boot_ms()` | `CLOCK_BOOTTIME` (Linux/Android), `CLOCK_MONOTONIC` (Darwin) | counted on every platform | The monotonic `Instant` is therefore *awake time* on Android and *elapsed time* on iOS. When you need the same answer on both — for example "how long ago did the user last open the app", a cache lifetime or a timeout that must expire while the phone sleeps — use `boot_ms()` differences (or the wall clock for calendar time). Suspending only the **process** (the app moving to the background and being frozen) does not stop any of these clocks: a 4-second sleep that is frozen for 3 seconds still reports about 4 seconds on all three. Real device suspend cannot be reproduced in an emulator or simulator, so the table above is the documented platform behaviour, not a measurement. ## `DateTime` A calendar date and time (UTC): fields `year`, `month`, `day`, `hour`, `minute`, `second`. | Member | Description | |---|---| | `DateTime(year, month, day, hour, minute, second)` | constructor | | `to_str()` | `"YYYY-MM-DD HH:MM:SS"` | | `to_epoch_ms()` | back to epoch milliseconds (a proleptic-Gregorian civil-date algorithm, exact for all dates) | ```nox import nox.time dt: nox.time.DateTime = nox.time.from_epoch_ms(1700000000000) print(dt.to_str(), dt.year, dt.month, dt.day, dt.to_epoch_ms()) made: nox.time.DateTime = nox.time.DateTime(2024, 2, 29, 12, 30, 5) print(made.to_str(), made.to_epoch_ms() > 0, nox.time.pad2(7)) ``` ```output 2023-11-14 22:13:20 2023 11 14 1700000000000 2024-02-29 12:30:05 True 07 ``` ## `Instant` and `Duration` `Instant` reads a **monotonic** clock — it never goes backwards — and is the right tool for measuring how long something took (prefer it to subtracting two `now_ms()` values). | Member | Description | |---|---| | `instant_now()` | captures the current monotonic time | | `Instant.elapsed_ms()` | milliseconds since the instant was captured | | `Instant.elapsed()` | the same as a `Duration` | | `Duration(ms)`, `Duration.as_ms()` | a length of time in milliseconds | ```nox import nox.time start: nox.time.Instant = nox.time.instant_now() nox.time.sleep_ms(30) took: nox.time.Duration = start.elapsed() print(took.as_ms() >= 25, nox.time.now_ms() > 1700000000000) ``` ```output True True ``` ## Notes - `sleep_ms` inside a task suspends only that task on both backends; outside a task (top-level code of a plain thread, Windows) it blocks the thread ([Concurrency](https://noxlang.com/docs/language/concurrency/#the-scheduler)). - There is no time-zone support: `DateTime` is UTC. Format with `nox.time.pad2` or [f-string](https://noxlang.com/docs/language/strings/#f-strings) format specs. --- # nox.tasks Task groups: a dynamic number of tasks with a common result type, with waiting, limiting and cancelling. ```text import nox.tasks from nox.tasks import TaskGroup, TaskHandle ``` **Capability:** none. `list[Task[T]]` cannot be written directly. `TaskGroup[T]` keeps each task in a small `TaskHandle[T]` class (field `task`); releasing the group releases the tasks. | Member | Description | |---|---| | `TaskGroup[T]()` | an empty group for tasks that return `T` | | `add(t)` | adds a task, e.g. `g.add(spawn work(i))` | | `size()`, `finished()` | how many tasks were added / have finished | | `wait_all(timeout_ms)` | waits cooperatively until every task has finished; `True` if they all did before the timeout | | `wait_below(limit, timeout_ms)` | waits until fewer than `limit` tasks are still running (call it before `add` to bound concurrency) | | `cancel_all()` | requests cancellation of every task (cooperative: a task sees `CancelledError` at its next `await`) | | `handles()` | the `TaskHandle[T]` list in insertion order; `await h.task` yields the result | `await` can only be written in an `async def` and only on a `Task` value, so collecting results is a loop in your code. An exception raised by a task is re-raised by the `await` of that task. ```nox import nox.tasks import nox.time from nox.tasks import TaskGroup, TaskHandle async def work(i: int) -> int: nox.time.sleep_ms(5 * i) return i * 2 async def run() -> None: g: TaskGroup[int] = TaskGroup[int]() for i in range(4): g.add(spawn work(i)) print(g.wait_all(5000)) out: list[int] = [] for h in g.handles(): out.append(await h.task) print(out) t0: Task[None] = spawn run() await t0 ``` ```output True [0, 2, 4, 6] ``` ## Cancelling CPU-bound work Cancellation is cooperative, so a loop that never awaits needs a checkpoint: ```text import nox.tasks import nox.time async def crunch(n: int) -> int: total: int = 0 for i in range(n): total += heavy(i) nox.tasks.checkpoint() # raises CancelledError if cancellation was requested if i % 1000 == 0: nox.time.sleep_ms(0) # let other tasks and timers run return total ``` | Function | Description | |---|---| | `checkpoint()` | raises `CancelledError` if the current task (or the thread's entry task) was cancelled with `Task.cancel()` / `ThreadHandle.cancel()`; otherwise a cheap flag read. Outside a task it does nothing | | `is_cancelled()` | the same flag without raising, to clean up and return your own way | Nothing is stopped forcibly, so no resource is leaked and no ARC state is corrupted. A thread started with `nox.thread.start` is cancelled with `h.cancel()`. ## Notes - Tasks are started with `spawn`; the group does not start them. Cancelling does not interrupt a task that never awaits (see [Concurrency](https://noxlang.com/docs/language/concurrency/#cancellation)). - To wait for a single task with a timeout use `t.wait(ms)` / `t.wait_any(other, ms)` ([Concurrency](https://noxlang.com/docs/language/concurrency/#timeouts-and-waiting-for-the-first-of-two-tasks)). --- # nox.property Seeded property-based testing: generate many random inputs, check a property, and get a reproducible, size-reduced failure. ```text import nox.property from nox.property import Rng, PropertyFailed ``` **Capability:** none. A property is a function `(Rng) -> bool` that draws its inputs from the `Rng` and returns whether the property holds. `check` runs it many times; each run has its own seed (`seed + run`) and a **size** that grows from 1 to `max_size`, which bounds list lengths, string lengths and integer magnitudes. When a run fails, `check` re-runs the same seed with smaller and smaller sizes, keeps the smallest size that still fails, and raises `PropertyFailed` with a replay hint. An exception raised by the property also counts as a failure. | Member | Description | |---|---| | `check(name, prop, runs=100, seed=12345, max_size=100)` | runs the property; raises `PropertyFailed(message, seed, size, run)` on the first failure | | `replay(prop, seed, size)` | one run with an exact seed and size; returns whether the property held (an exception counts as `False`) — use it to reproduce a CI failure locally | | `Rng(seed, size)` | the generator; `size` is a public field | | `r.int_range(lo, hi)` | an integer in `[lo, hi]`, with the upper bound capped at `lo + size` | | `r.boolean()` | a random `bool` | | `r.int_list(max_len, lo, hi)` | a list of 0..`max_len` integers (length also bounded by `size`) | | `r.ascii_str(max_len)` | a lowercase ASCII string of 0..`max_len` characters | | `r.choice_str(items)` | a random item of a non-empty `list[str]` | | `r.next_raw()` | the next raw value in `[0, 2147483646)` | The generator is a Park–Miller linear congruential generator: not cryptographic, free of overflow, and identical on every platform, so a seed always reproduces the same values. ```nox import nox.property from nox.property import Rng, PropertyFailed def reverse_twice(r: Rng) -> bool: xs: list[int] = r.int_list(r.size, -100, 100) ys: list[int] = xs.copy() ys.reverse() ys.reverse() return xs == ys def too_big(r: Rng) -> bool: return r.int_range(0, 1000) < 50 nox.property.check("reverse twice", reverse_twice) try: nox.property.check("too big", too_big, 50, 1) except PropertyFailed as e: print("failed, replay still fails:", not nox.property.replay(too_big, e.seed, e.size)) ``` ```output failed, replay still fails: True ``` ## Notes - Shrinking reduces the **size**, not individual values: generators draw smaller structures at a smaller size, so the reported counterexample comes from the smallest size that still fails. - Print `e.seed` and `e.size` (they are in the message) in CI so a failure can be replayed with `replay`. --- # nox.collections Data structures beyond the built-in `list`, `dict` and `set`: stacks, queues, deques, counters, ordered maps, an LRU cache, a binary heap and a priority queue. All are generic classes — you name the element type: `Stack[int]()`, `OrderedDict[str, int]()`. ```text from nox.collections import Stack, Queue, Deque, Set, Counter, OrderedDict, LRUCache, Heap, PriorityQueue ``` **Capability:** none. Operations that cannot succeed on an empty or missing element raise: `IndexError` for `pop`/`peek` on an empty container, `KeyError` for `OrderedDict.get` of a missing key. ## Reference ### `Stack[T]` — last in, first out | Method | Description | |---|---| | `Stack[T]()` | an empty stack | | `push(v)` | adds `v` on top | | `pop()` | removes and returns the top element | | `peek()` | returns the top element without removing it | | `is_empty()`, `size()` | emptiness and element count | ### `Queue[T]` — first in, first out | Method | Description | |---|---| | `Queue[T]()` | an empty queue | | `push(v)` | adds `v` at the back | | `pop()` | removes and returns the front element | | `peek()` | returns the front element | | `is_empty()`, `size()` | emptiness and element count | ### `Deque[T]` — double-ended queue | Method | Description | |---|---| | `Deque[T]()` | an empty deque | | `push_front(v)`, `push_back(v)` | add at either end | | `pop_front()`, `pop_back()` | remove and return from either end | | `peek_front()`, `peek_back()` | look at either end | | `is_empty()`, `size()` | emptiness and element count | ### `Set[T]` A class-based set with explicit set algebra (the language also has the built-in `set[T]` type with literals and operators — see [Types](https://noxlang.com/docs/language/types/#collection-types)). | Method | Description | |---|---| | `Set[T]()` | an empty set | | `add(v)` | inserts `v` (a no-op if present) | | `contains(v)` | membership | | `remove(v)` | removes `v` in amortised O(1); returns whether it was present. Insertion order of the remaining elements is kept | | `size()`, `is_empty()` | count and emptiness | | `to_list()` | the elements as a list, in insertion order | | `union(other)`, `intersection(other)`, `difference(other)` | new sets | ### `Counter[T]` | Method | Description | |---|---| | `Counter[T]()` | an empty counter | | `add(v)` | increments the count of `v` | | `count(v)` | the count of `v` (`0` if never added) | | `total()` | the sum of all counts | | `size()` | the number of distinct values | ### `OrderedDict[K, V]` — insertion-ordered map | Method | Description | |---|---| | `OrderedDict[K, V]()` | an empty map | | `set(k, v)` | inserts or replaces (replacing keeps the original position) | | `get(k)` | the value for `k`; `KeyError` if absent | | `contains(k)` | key membership | | `remove(k)` | removes `k`; returns whether it was present | | `keys_list()`, `values_list()` | keys / values in insertion order | | `size()` | number of entries | ### `LRUCache[K, V]` — least-recently-used cache | Method | Description | |---|---| | `LRUCache[K, V](capacity)` | a cache holding at most `capacity` entries | | `put(k, v)` | inserts or updates; evicts the least recently used entry when full | | `get(k)` | the value, marking it most recently used | | `contains(k)` | membership (does not change recency) | | `size()` | number of entries | ### `Heap[T]` — binary min-heap | Method | Description | |---|---| | `Heap[T]()` | an empty heap of `int`, `float` or `str` elements | | `push(v)` | inserts | | `pop_min()` | removes and returns the smallest element | | `peek_min()` | the smallest element | | `size()`, `is_empty()` | count and emptiness | ### `PriorityQueue[T]` | Method | Description | |---|---| | `PriorityQueue[T]()` | an empty queue | | `push(priority, v)` | inserts `v` with an `int` priority (smaller is served first) | | `pop_min()` | removes and returns the value with the smallest priority | | `peek_min()`, `peek_min_priority()` | the next value and its priority | | `size()`, `is_empty()` | count and emptiness | ## Examples ```nox from nox.collections import Stack, Queue, Deque s: Stack[int] = Stack[int]() s.push(1) s.push(2) print(s.peek(), s.pop(), s.size(), s.is_empty()) q: Queue[str] = Queue[str]() q.push("a") q.push("b") print(q.pop(), q.peek(), q.size()) d: Deque[int] = Deque[int]() d.push_back(1) d.push_front(0) d.push_back(2) print(d.pop_front(), d.pop_back(), d.peek_front(), d.peek_back(), d.size()) ``` ```output 2 2 1 False a b 1 0 2 1 1 1 ``` ```nox from nox.collections import Set, Counter, OrderedDict, LRUCache, Heap, PriorityQueue st: Set[int] = Set[int]() st.add(1) st.add(2) st.add(2) ot: Set[int] = Set[int]() ot.add(2) ot.add(3) print(st.size(), st.contains(2), st.remove(9), st.remove(1), st.to_list()) print(st.union(ot).to_list(), st.intersection(ot).to_list(), st.difference(ot).to_list()) c: Counter[str] = Counter[str]() c.add("a") c.add("b") c.add("a") print(c.count("a"), c.count("z"), c.total(), c.size()) od: OrderedDict[str, int] = OrderedDict[str, int]() od.set("x", 1) od.set("y", 2) od.set("x", 3) print(od.get("x"), od.contains("y"), od.keys_list(), od.values_list(), od.remove("y"), od.size()) lru: LRUCache[str, int] = LRUCache[str, int](2) lru.put("a", 1) lru.put("b", 2) lru.get("a") lru.put("c", 3) print(lru.contains("a"), lru.contains("b"), lru.contains("c"), lru.size()) h: Heap[int] = Heap[int]() h.push(5) h.push(1) h.push(3) print(h.peek_min(), h.pop_min(), h.pop_min(), h.size()) pq: PriorityQueue[str] = PriorityQueue[str]() pq.push(2, "two") pq.push(1, "one") print(pq.peek_min_priority(), pq.pop_min(), pq.pop_min(), pq.is_empty()) ``` ```output 2 True False True [2] [2, 3] [2] [] 2 0 3 2 3 True ['x', 'y'] [3, 2] True 1 True False True 2 1 1 3 1 1 one two True ``` ## Notes - Empty-container operations raise instead of returning a sentinel: ```nox from nox.collections import Stack s: Stack[int] = Stack[int]() try: s.pop() except IndexError as e: print("empty stack") ``` ```output empty stack ``` - The classes are ordinary Nox code; they are not thread-safe. Share a container between tasks through a [channel](https://noxlang.com/docs/language/concurrency/#channels), not by sharing the object. --- # nox.bits Bit manipulation on fixed-width integers: rotations, byte swaps, endianness conversion, and single-bit helpers. Pure functions with no operating-system dependency — usable in every profile, including freestanding kernels. ```text import nox.bits ``` **Capability:** none. ## Rotations `rotl_uN(x, n)` and `rotr_uN(x, n)` rotate the `N`-bit unsigned value `x` left or right by `n` bits (`n` is reduced modulo `N`). Available for `N` = 8, 16, 32, 64: `rotl_u8`, `rotr_u8`, `rotl_u16`, `rotr_u16`, `rotl_u32`, `rotr_u32`, `rotl_u64`, `rotr_u64`. ## Byte order | Function | Description | |---|---| | `swap16(x)`, `swap32(x)`, `swap64(x)` | reverse the bytes of a `u16` / `u32` / `u64` | | `to_le16`, `to_le32`, `to_le64` | convert a host-order value to little-endian | | `from_le16`, `from_le32`, `from_le64` | convert a little-endian value to host order | | `to_be16`, `to_be32`, `to_be64` | convert a host-order value to big-endian | | `from_be16`, `from_be32`, `from_be64` | convert a big-endian value to host order | The `le`/`be` conversions are no-ops where the host byte order already matches (every supported platform is little-endian today, so `to_be*` swaps and `to_le*` does nothing). ## Single bits (on `int`) | Function | Description | |---|---| | `mask(n)` | an integer with the low `n` bits set (`mask(5)` is `31`) | | `test_bit(x, pos)` | whether bit `pos` of `x` is set | | `set_bit(x, pos)`, `clear_bit(x, pos)`, `toggle_bit(x, pos)` | a copy of `x` with that bit set / cleared / flipped | ```nox import nox.bits print(nox.bits.rotl_u8(u8(129), 1), nox.bits.rotr_u8(u8(129), 1), nox.bits.rotl_u32(u32(1), 31)) print(nox.bits.swap16(u16(0x1234)), nox.bits.swap32(u32(0x12345678)), nox.bits.to_be16(u16(0x1234)), nox.bits.to_le16(u16(0x1234))) print(nox.bits.mask(5), nox.bits.test_bit(5, 0), nox.bits.test_bit(5, 1), nox.bits.set_bit(0, 3), nox.bits.clear_bit(15, 0), nox.bits.toggle_bit(5, 1)) ``` ```output 3 192 2147483648 13330 2018915346 13330 4660 31 True False 8 14 7 ``` (`0x1234` is `4660`; swapped it becomes `0x3412`, `13330`.) ## Related The operators `& | ^ ~ << >>` ([Expressions](https://noxlang.com/docs/language/expressions/)) are built into the language; `nox.bits` supplies the fixed-width rotations and byte-order helpers that have no operator. For reading and writing whole binary structures see [`nox.binary`](https://noxlang.com/docs/stdlib/binary/). --- # nox.buffer Fixed-size byte buffers for systems and protocol code: network packets, file blocks, device buffers. A `Buffer` owns its bytes; a `Span` is a bounded window onto a part of one. ```text from nox.buffer import Buffer, Span ``` **Capability:** none. A `Buffer` is a thin wrapper over `list[u8]` with a fixed length — it does not grow or shrink — and uses no raw pointers. ## `Buffer` | Member | Description | |---|---| | `Buffer(n)` | a new buffer of `n` zero bytes | | `len()` | its length in bytes | | `get(i)` | the byte at index `i` (`u8`); `IndexError` out of range | | `set(i, v)` | stores the byte `v` (`u8`) at index `i` | | `fill(v)` | sets every byte to `v` | | `copy_from(other)` | copies the bytes of another `Buffer` (the lengths must match) | | `span(start, end)` | a `Span` viewing bytes `[start, end)` | ## `Span` A `Span` borrows part of a `Buffer`; writes through the span are visible in the buffer. `Span(buf, start, end)` constructs one directly. | Member | Description | |---|---| | `len()` | number of bytes in the window | | `get(i)`, `set(i, v)` | access relative to the window's start; bounds are those of the window | ```nox from nox.buffer import Buffer, Span b: Buffer = Buffer(8) b.fill(u8(7)) b.set(0, u8(255)) print(b.len(), b.get(0), b.get(1)) c: Buffer = Buffer(8) c.copy_from(b) sp: Span = c.span(0, 4) print(sp.len(), sp.get(0)) sp.set(1, u8(9)) print(c.get(1)) ``` ```output 8 255 7 4 255 9 ``` ## Notes - Elements are `u8`; use `int(x)` to compute with them ([Numbers](https://noxlang.com/docs/language/numbers/#fixed-width-integers)). - Byte-oriented parsing and generation of structured data (integers of every width, both endiannesses) lives in [`nox.binary`](https://noxlang.com/docs/stdlib/binary/), built on top of `Buffer`. - A `Span` does not extend the lifetime guarantees of C pointers: it is an ordinary reference to its buffer, kept alive automatically. --- # nox.binary Cursor-based readers and writers for binary formats — file headers, network packets, on-disk structures — without raw pointers. Every integer width and both byte orders are supported, with exact types (`u16`, `i32`, …). ```text from nox.binary import BinaryReader, BinaryWriter, span_reader, span_writer ``` **Capability:** none. ## `BinaryWriter` Writes into a `Buffer` ([`nox.buffer`](https://noxlang.com/docs/stdlib/buffer/)) starting at position 0 and advances after every write. Writing past the end raises `IndexError`. | Member | Description | |---|---| | `BinaryWriter(buf)` | a writer over `buf` | | `position()` | the current offset | | `seek(pos)` | moves the cursor | | `write_u8(v)`, `write_i8(v)` | one byte | | `write_u16_le(v)`, `write_u16_be(v)`, `write_i16_le(v)`, `write_i16_be(v)` | 16-bit, little / big endian | | `write_u32_le(v)`, `write_u32_be(v)`, `write_i32_le(v)`, `write_i32_be(v)` | 32-bit | | `write_u64_le(v)`, `write_u64_be(v)`, `write_i64_le(v)`, `write_i64_be(v)` | 64-bit | ## `BinaryReader` Reads from a `Buffer` and advances after every read. Reading past the end raises `IndexError`. | Member | Description | |---|---| | `BinaryReader(buf)` | a reader over `buf` | | `position()` | the current offset | | `remaining()` | bytes left to read | | `seek(pos)` | moves the cursor | | `read_u8()`, `read_i8()` | one byte | | `read_u16_le()`, `read_u16_be()`, `read_i16_le()`, `read_i16_be()` | 16-bit | | `read_u32_le()`, `read_u32_be()`, `read_i32_le()`, `read_i32_be()` | 32-bit | | `read_u64_le()`, `read_u64_be()`, `read_i64_le()`, `read_i64_be()` | 64-bit | ## Spans `span_reader(sp)` and `span_writer(sp)` create a reader or writer that is confined to a [`Span`](https://noxlang.com/docs/stdlib/buffer/#span): its `position()` and `remaining()` are relative to the window, and it cannot touch bytes outside it. ```nox from nox.buffer import Buffer, Span from nox.binary import BinaryReader, BinaryWriter, span_reader b: Buffer = Buffer(8) w: BinaryWriter = BinaryWriter(b) w.write_u8(u8(1)) w.write_u16_be(u16(0x0203)) w.write_u32_le(u32(0x04050607)) print(w.position()) r: BinaryReader = BinaryReader(b) print(r.read_u8(), r.read_u16_be(), r.read_u32_le(), r.position(), r.remaining()) r.seek(0) print(r.read_i8(), r.position()) sp: Span = b.span(0, 4) rs: BinaryReader = span_reader(sp) print(rs.read_u8(), rs.remaining()) ``` ```output 7 1 515 67438087 7 1 1 1 1 3 ``` ## Notes - Values are assembled byte by byte, so the module is independent of the host's byte order and alignment. - Signed reads reinterpret the bits: `read_i8()` of byte `255` is `-1`. - Strings are not part of this module; encode them to bytes explicitly with `nox.strings.byte_at` / `char_from_byte`. --- # nox.bytes The bridge between a `str` and a raw byte buffer. ```text import nox.bytes from nox.buffer import Buffer ``` **Capability:** none. Hosted targets only: the module uses `nox.strings`, which freestanding profiles do not link. A `str` holds UTF-8, and it keeps its length in its header, so it also stores embedded `\x00` bytes and bytes that are not valid UTF-8 exactly as they arrived (a binary HTTP body, the contents of a file). `from_str` copies those bytes into a [`Buffer`](https://noxlang.com/docs/stdlib/buffer/). | Function | Description | |---|---| | `from_str(s)` | a new `Buffer` holding the bytes of `s` | | `str_from_list(data)` | a byte-exact `str` from a `list[int]` of values 0-255 (e.g. the output of [`nox.gzip`](https://noxlang.com/docs/stdlib/gzip/)); `BytesError` for a value outside 0..255. Usable as a binary HTTP body or protobuf payload | | `list_from_str(s)` | the bytes of `s` as a `list[int]` | | `to_list(buf)`, `from_list(data)` | `Buffer` ↔ `list[int]` | | `to_str(buf)` | a byte-exact `str` from a `Buffer` | ```nox import nox.bytes from nox.buffer import Buffer b: Buffer = nox.bytes.from_str("a\x00b") print(b.len()) print(b.get(0)) print(b.get(1)) print(b.get(2)) ``` ```output 3 97 0 98 ``` --- # nox.protobuf The Protocol Buffers **wire format**: a writer and a reader for the byte encoding, in pure Nox. There is no schema compiler: you give the field numbers, which is all that OTLP, gRPC payloads or your own messages need. ```text import nox.protobuf from nox.protobuf import Writer, Reader, ProtobufError ``` **Capability:** none (works on every target, including mobile and WebAssembly). ```text w: Writer = nox.protobuf.writer() w.varint(1, 150) # int32 / int64 / uint32 / uint64 / enum w.string(2, "testing") inner: Writer = nox.protobuf.writer() inner.sint(1, -5) # sint32 / sint64 (zigzag) w.message(3, inner) # nested message body: str = w.to_str() # byte-exact str, e.g. an HTTP request body data: list[int] = w.to_bytes() r: Reader = nox.protobuf.reader(data) while r.next_field(): if r.field == 1: print(r.read_varint()) elif r.field == 2: print(r.read_string()) else: r.skip() # unknown fields are skipped (forward compatible) ``` ## Writer | Method | Proto type | Wire type | |---|---|---| | `varint(field, v)` | `int32`, `int64`, `uint32`, `uint64`, `enum` | 0 | | `boolean(field, v)` | `bool` | 0 | | `sint(field, v)` | `sint32`, `sint64` (zigzag) | 0 | | `fixed64(field, v)` / `fixed32(field, v)` | `fixed64`, `sfixed64` / `fixed32`, `sfixed32` | 1 / 5 | | `double(field, v)` / `float32(field, v)` | `double` / `float` | 1 / 5 | | `string(field, s)` | `string` (UTF-8) | 2 | | `bytes_field(field, data)` | `bytes` (`list[int]`) | 2 | | `message(field, inner)` | nested message (`inner` is another `Writer`) | 2 | | `packed_varints(field, values)` | packed `repeated` varint field | 2 | `to_bytes()` returns the encoding as `list[int]`, `to_str()` as a byte-exact `str`, `size()` the length. Negative `int32`/`int64` values are written as 10-byte varints, as the specification requires. ## Reader `nox.protobuf.reader(data)` (or `reader_from_str(s)`) reads a message. `next_field()` reads the next tag and returns `False` at the end; `field` and `wire_type` describe it. Then call the matching reader for the field, or `skip()`: `read_varint`, `read_bool`, `read_sint`, `read_fixed64`, `read_fixed32` (zero-extended), `read_sfixed32` (sign-extended), `read_double`, `read_float32`, `read_string`, `read_bytes`, `read_message` (a `Reader` over the nested bytes), `read_packed_varints`. ## Notes - Numbers are Nox `int` (64-bit signed): the upper half of `uint64` appears negative, with the bit pattern preserved. - A wire-type mismatch, a truncated value, a varint longer than 10 bytes or field number 0 raises `ProtobufError`. Groups (wire types 3 and 4) are not supported. - Together with [`nox.gzip`](https://noxlang.com/docs/stdlib/gzip/) and [`nox.bytes`](https://noxlang.com/docs/stdlib/bytes/) this is enough for OTLP/HTTP: encode the request, compress it, send it as the body. --- # nox.fs Files and directories: read, write, append, copy, rename, delete, list, and inspect. ```text import nox.fs from nox.fs import FsError, FileMetadata, FileReader, FileWriter ``` **Capability:** `filesystem` (unavailable in freestanding profiles). On `wasm32-freestanding` it works on an in-memory virtual file system instead of the real disk; see [WASM](https://noxlang.com/docs/tools/wasm/#virtual-file-system-wasm32-freestanding). > **Security.** `nox.fs` passes paths straight to the operating system. It does **no** validation, canonicalisation or sandboxing: `..` segments, symbolic links > and absolute paths all work. If a path comes from an untrusted source (user input, a network request), you must confine it yourself — for example by > confining it with [`nox.path.safe_join`](https://noxlang.com/docs/stdlib/path/#confining-untrusted-paths), which rejects anything that would leave an allowed root. See [Security](https://noxlang.com/docs/reference/security/). ## Reading and writing | Function | Description | |---|---| | `read_to_string(path)` | the whole file as a `str`; raises `FsError` if it cannot be read | | `write_string(path, content)` | creates or **truncates** the file and writes `content` | | `write_string_atomic(path, content)` | writes to `path + ".nox-tmp"` and renames it over `path`: a failed write leaves the old contents intact and removes the temporary file | | `append_string(path, content)` | appends `content`, creating the file if needed | Files are read and written as text bytes; `content` is written exactly as given (no newline translation). ## Querying | Function | Description | |---|---| | `exists(path)` | whether anything exists at `path` (never raises) | | `is_file(path)`, `is_dir(path)` | type tests (never raise; `False` when absent) | | `metadata(path)` | a `FileMetadata`; raises `FsError` if absent | | `read_dir(path)` | the entry **names** of a directory (not full paths, unspecified order); raises `FsError` | `FileMetadata` has two fields: `size` (bytes) and `modified_ms` (modification time, milliseconds since the Unix epoch). ## Changing the file system | Function | Description | |---|---| | `copy(src, dst)` | copies a file; raises `FsError` on failure | | `rename(old, new)` | renames or moves; raises `FsError` on failure | | `remove_file(path)` | deletes a file; raises `FsError` on failure | | `create_dir(path)` | creates one directory (the parent must exist); raises `FsError` on failure | | `create_dir_all(path)` | `mkdir -p`: also creates missing parents; does nothing if the directory exists; raises `FsError` if a path component is a file | | `remove_dir(path)` | removes an **empty** directory; raises `FsError` if it is not empty, missing, or not a directory | | `remove_dir_all(path)` | removes a directory and everything under it (`rm -r`; symbolic links are not distinguished); raises `FsError` on failure | ## Streaming large files `read_to_string` and `write_string` hold the whole file in memory. For large files open a handle and move the content in chunks; memory use is bounded by the chunk size. | Function / method | Description | |---|---| | `open_read(path)` | a `FileReader`; raises `FsError` if the file cannot be opened | | `open_write(path)` | a `FileWriter` that creates or **truncates** the file | | `open_append(path)` | a `FileWriter` that appends (creating the file if needed) | | `reader.read_chunk(n)` | up to `n` bytes as a `str`: exactly `n` unless the end of the file is reached, then the remaining bytes, then `""` | | `reader.seek(offset)` | moves to `offset` bytes from the start (for resuming a transfer) | | `reader.size()` | the current size of the file in bytes | | `writer.write(content)` | writes every byte of `content` (unbuffered: each call goes straight to the operating system) | | `close()` | closes the file; calling it twice is harmless | A chunk is a `str` that carries **raw bytes** (including `\x00` and bytes that are not valid UTF-8, see [`nox.bytes`](https://noxlang.com/docs/stdlib/bytes/)), so a chunk can end in the middle of a multi-byte UTF-8 character, and `len(chunk)` counts code points: use `nox.strings.byte_len(chunk)` for the number of bytes. The end of the file is the empty chunk. A handle owns an operating-system file descriptor and is **not** closed automatically: use `with` (which closes it even when the body raises) or call `close()`. Using a closed handle raises `FsError`. The security note above applies to `open_*` paths too. ```nox import nox.fs import nox.strings import nox.path import nox.os from nox.fs import FsError, FileReader, FileWriter p: str = nox.path.join(nox.os.current_dir(), "streamdemo.bin") with nox.fs.open_write(p) as w: for i in range(1000): w.write("row " + str(i) + "\n") total: int = 0 chunks: int = 0 r: FileReader = nox.fs.open_read(p) while True: c: str = r.read_chunk(4096) n: int = nox.strings.byte_len(c) if n == 0: break total = total + n chunks = chunks + 1 print(total, chunks, r.size()) r.seek(4) print(r.read_chunk(5) == "0\nrow") r.close() try: r.read_chunk(1) except FsError: print("closed") nox.fs.remove_file(p) ``` ```output 7890 2 7890 True closed ``` ## Errors `FsError` (a subclass of `Exception`) is raised by every operation that can fail. `exists`, `is_file` and `is_dir` never raise. ```nox import nox.fs import nox.path import nox.os from nox.fs import FsError, FileMetadata d: str = nox.path.join(nox.os.current_dir(), "fsdemo") nox.fs.create_dir(d) f: str = nox.path.join(d, "a.txt") nox.fs.write_string(f, "hello") nox.fs.append_string(f, " world") print(nox.fs.read_to_string(f), nox.fs.exists(f), nox.fs.is_file(f), nox.fs.is_dir(d), nox.fs.exists(d + "/nope")) m: FileMetadata = nox.fs.metadata(f) print(m.size, m.modified_ms > 0) nox.fs.copy(f, nox.path.join(d, "b.txt")) nox.fs.rename(nox.path.join(d, "b.txt"), nox.path.join(d, "c.txt")) print(sorted(nox.fs.read_dir(d))) nox.fs.remove_file(nox.path.join(d, "c.txt")) print(sorted(nox.fs.read_dir(d))) try: nox.fs.read_to_string(d + "/missing") except FsError as e: print("FsError") ``` ```output hello world True True True False 11 True ['a.txt', 'c.txt'] ['a.txt'] FsError ``` ## Notes - There is no recursive delete or recursive create; walk with `read_dir` and `is_dir`. - `read_to_string` reads the whole file into memory; for large files use the streaming handles above. - Operations are synchronous; under the multi-core scheduler they block only their worker. - Catch the exception with `from nox.fs import FsError` — qualified names such as `nox.fs.FsError` are not accepted in an `except` clause. --- # nox.path Lexical operations on file-system path strings. Nothing here touches the disk except `canonicalize`. ```text import nox.path from nox.path import PathError ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `join(a, b)` | joins two parts with exactly one `/` between them (`join("a/", "b")` is `a/b`; an empty `a` gives `b`; an absolute `b` is appended, not treated specially) | | `basename(p)` | the last component (`"/x/y/z.txt"` → `"z.txt"`) | | `dirname(p)` | everything before the last component (`"/x/y/z.txt"` → `"/x/y"`) | | `extension(p)` | the part after the last dot of the last component (`"z.tar.gz"` → `".gz"`), or `""` | | `is_absolute(p)` | whether `p` starts at the root | | `components(p)` | the non-empty components as a list (`"/x/y/z"` → `['x','y','z']`) | | `strip_prefix(p, prefix)` | `p` without the leading `prefix` and the separator after it; if `prefix` is not a prefix of `p` **at a component boundary** (`/srv/dataevil` does not start with `/srv/data`) it is returned unchanged | | `canonicalize(p)` | the absolute path with `.`, `..` and symbolic links resolved; **the path must exist** (`PathError` otherwise) | | `safe_join(root, requested)` | `requested` resolved under `root`, or `PathError` if the result would leave `root` (see [Confining untrusted paths](#confining-untrusted-paths)) | ```nox import nox.path print(nox.path.join("a", "b"), nox.path.basename("/x/y/z.txt"), nox.path.dirname("/x/y/z.txt"), nox.path.extension("z.tar.gz"), nox.path.is_absolute("/x")) print(nox.path.strip_prefix("/x/y/z", "/x"), nox.path.components("/x/y/z")) print(nox.path.canonicalize(".") != "") try: nox.path.canonicalize("/definitely/not/here") except Exception as e: print("no such path") ``` ```output a/b z.txt /x/y .gz True y/z ['x', 'y', 'z'] True no such path ``` ## Confining untrusted paths `safe_join` is the standard way to turn a path that came from outside (a request, a form, a configuration file) into one that is guaranteed to stay under a root directory: ```nox import nox.path from nox.path import PathError def open_upload(name: str) -> str: try: return nox.path.safe_join("/srv/uploads", name) except PathError: return "" ``` It canonicalises `root` (which must exist), joins `requested`, resolves `..` and symbolic links, and compares **path components**, not string prefixes: `/srv/dataevil` is not inside `/srv/data`. An absolute `requested` is treated as relative to `root` (`/etc/passwd` becomes `/etc/passwd`). A target that does not exist yet (a file you are about to write) is allowed: its parent directory is resolved and checked instead. Anything that would end up outside `root` raises `PathError`. Do not confine a path with `starts_with(canonicalize(...), root)`: that accepts siblings such as `/srv/dataevil` and misjudges a root that is itself a symbolic link. `safe_join` does neither. --- # nox.os Process-level information and control: command-line arguments, environment variables, the working directory and exit. ```text import nox.os from nox.os import OsError ``` **Capability:** `process`. ## Functions | Function | Description | |---|---| | `arg_count()` | the number of command-line arguments, **including** the program name at index 0 | | `arg(i)` | argument `i` as a `str` | | `getenv(name)` | the value of an environment variable; raises `OsError` if it is not set | | `environ()` | every environment variable of this process as a `dict[str, str]` | | `env_names()` | the names of those variables as a `list[str]` | | `set_var(name, value)` | sets an environment variable for this process and its children | | `current_dir()` | the current working directory | | `exit(code)` | terminates the program immediately with exit status `code` | Arguments given to `noxc run file.nox -- a b c` (or to a compiled program) appear as `arg(1)`, `arg(2)`, `arg(3)`. ```nox import nox.os from nox.os import OsError print(nox.os.arg_count() >= 1, nox.os.getenv("HOME") != "") try: nox.os.getenv("NOX_SURELY_UNSET_VAR") except OsError as e: print("not set") nox.os.set_var("NOX_DEMO", "42") print(nox.os.getenv("NOX_DEMO"), nox.os.current_dir() != "") ``` ```output True True not set 42 True ``` ## Notes - `exit` ends the process without running `finally` blocks or `defer`s that are still pending — flush and close what you need first. A normal return from the top level exits with status 0, an uncaught exception with status 1. - `getenv` has no default-value form; test for absence with `try`/`except OsError`. - On Windows `set_var(name, "")` deletes the variable (Win32 `_putenv_s`), so an empty-valued variable never appears in `environ()` there. - Environment changes made with `set_var` are visible to child processes started with [`nox.process`](https://noxlang.com/docs/stdlib/process/). --- # nox.process Run external programs and capture their output. ```text from nox.process import Command, Output, ProcessError ``` **Capability:** `process`. > **Security.** A `Command` runs exactly the program and arguments you give it, with the full authority of your process. There is no shell: arguments are passed > as an array, so they are never re-interpreted — but never build the *program* name from untrusted input. ## `Command` A builder: every setter returns the same `Command`, so calls chain. | Member | Description | |---|---| | `Command(program)` | prepares to run `program` (looked up on `PATH`) | | `arg(v)` | appends one argument | | `arg_list(xs)` | appends several arguments from a `list[str]` | | `set_cwd(path)` | runs the program in a different working directory | | `set_timeout(ms)` | kills the program if it runs longer than `ms` milliseconds (`0` means no limit) | | `run()` | runs it **synchronously** and returns an `Output` | ## `Output` | Field / method | Description | |---|---| | `status` | the exit status (`int`) | | `stdout`, `stderr` | everything the program wrote, as `str` | | `success()` | `True` when `status == 0` | A program that exits with a non-zero status is **not** an error — inspect `status`. `run()` raises `ProcessError` only when the program could not be run at all: not found, an argument containing a NUL byte, or the timeout expired. ```nox from nox.process import Command, Output, ProcessError out: Output = Command("echo").arg("hi").arg_list(["a", "b"]).run() print(out.status, out.stdout.strip(), out.success(), out.stderr == "") failed: Output = Command("sh").arg("-c").arg("echo err >&2; exit 3").run() print(failed.status, failed.success(), failed.stderr.strip()) try: Command("definitely-not-a-program-xyz").run() except ProcessError as e: print("could not run") ``` ```output 0 hi a b True True 3 False err could not run ``` ## Notes - `run()` blocks until the program ends and buffers all output in memory. - Standard input of the child is empty. - To run a command in parallel with other work, `spawn` a task that calls it ([Concurrency](https://noxlang.com/docs/language/concurrency/)). --- # nox.signal Subscribe to process signals: `SIGINT`, `SIGTERM`, `SIGHUP`, `SIGUSR1`, `SIGUSR2`. ```text import nox.signal ``` **Capability:** `process`. The handler does exactly one async-signal-safe thing: it sets a flag. Your code reads the flag from its own task, so a signal never interrupts Nox code in the middle of a statement. A typical graceful-shutdown loop: ```text nox.signal.install(nox.signal.sigterm()) while not nox.signal.take(nox.signal.sigterm()): ...do work... nox.time.sleep_ms(50) # inside a task this suspends only that task ...drain active work and exit... ``` | Function | Description | |---|---| | `sigint()`, `sigterm()`, `sighup()`, `sigusr1()`, `sigusr2()` | the platform's signal number (`0` where signals do not exist) | | `install(sig)` | routes the signal to the flag-setting handler; `True` on success | | `pending(sig)` | is the flag set? (does not clear it) | | `take(sig)` | reads **and clears** the flag: `True` once per delivered signal | | `wait(sig, timeout_ms)` | cooperatively waits until the signal arrives or the timeout expires; `True` if it arrived (and clears the flag) | | `send_self(sig)` | sends the signal to this process (tests, self-shutdown) | | `service_run(name)` | Windows: connect to the Service Control Manager when started as a service (`True`), `False` in a console / on other systems; see Notes | | `service_stopped(code)` | Windows service: report `SERVICE_STOPPED` before exiting (`code != 0`: service-specific exit code) | ```nox import nox.signal s: int = nox.signal.sigusr1() print(nox.signal.install(s)) print(nox.signal.send_self(s)) print(nox.signal.take(s), nox.signal.take(s)) ``` ```output True True True False ``` ## Notes - **Windows** has no POSIX signals but has console events, and `nox.signal` maps them: `sigint()` (2) is Ctrl+C, `sigterm()` (15) is Ctrl+Break, closing the console, logging off and shutting down. `install`, `pending`, `take`, `wait` and `send_self` work as on POSIX, so a `while not take(sigterm())` loop is portable. Windows ends the process about 5 seconds after the handler returns for close/logoff/shutdown events: finish draining within that time. `sigusr1()`/`sigusr2()` do not exist there (0), a process without a console receives no events, and stopping a Windows *service* needs `service_run` (see below). `nox.http.serve*` shuts down gracefully on the same events. - **WebAssembly** (`wasm32-freestanding --asyncify`): the *host* delivers a stop request. The module exports `nox_host_signal(sig)`; the host calls it with 2 (SIGINT), 15 (SIGTERM) or 1 (SIGHUP) and gets `1` if the module had `install`ed that signal (the flag is set) or `0` if not (the host then applies its default, e.g. ends the process). `sigint()`/`sigterm()`/`sighup()` are 2/15/1, `sigusr1()`/`sigusr2()` are 0, `send_self` works on installed signals. `wait` suspends the whole program on a **host timer** (capability bit 16) so the host's event loop keeps running and can deliver the signal; a host that does not grant the timer blocks as before. With the Node command line (`node wasm_host.mjs prog.wasm`) `Ctrl+C`/`kill` are delivered this way; an embedder passes `runNox(bytes, io, { signalSource: (deliver) => { ...; return stop; } })`. No new `nox_host` import is needed. `wasm32-wasi`, plain freestanding and `--threads` modules, and non-WASM freestanding targets have no signals: `install` returns `False`, `take`/`pending` always `False`. - `nox.http.serve*` installs its own `SIGTERM`/`SIGINT` handler when it starts; the last installer wins, so do not combine the two on the same signal. Use `nox.http.shutdown()` to stop a server from code. - Signal numbers differ between platforms (`SIGUSR1` is 10 on Linux and 30 on macOS), which is why they come from functions rather than constants. - **Windows services (SCM):** `service_run(name)` connects a program started by the Service Control Manager: it returns `True` when it is running as a service and `False` in a console (or on other systems), so one binary works both ways. Call it once at the start; Nox code never runs on the SCM's threads. `sc stop` and a system shutdown then look like `SIGTERM` (`wait(sigterm(), ms)` / `take(sigterm())`), and when the program has finished it must call `service_stopped(code)` (non-zero `code` is reported as the service-specific exit code), otherwise the SCM treats the process as having ended unexpectedly. Wrapper tools such as NSSM or WinSW still work and need no code. The console fallback is covered by a real-Windows run; the SCM path is verified with `scripts/windows_service_probe.bat` (it installs a service, so run it only on your own development machine). --- # nox.terminal Terminal control for full-screen and interactive programs: TTY detection, size, raw mode, echo, non-blocking input and raw output. ```text import nox.terminal from nox.terminal import TerminalError, TerminalSize, TerminalCapabilities ``` **Capability:** `process`. | Function | Description | |---|---| | `is_tty(fd=1)` | is `fd` (0 stdin, 1 stdout, 2 stderr) attached to a terminal? | | `get_size()` | a `TerminalSize(cols, rows)`; falls back to `COLUMNS`/`LINES`, then 80x24, when the size cannot be read | | `get_capabilities()` | a `TerminalCapabilities(is_tty, supports_ansi, supports_truecolor, color_depth)` from `TERM`, `COLORTERM` and `NO_COLOR` (depth 0, 16, 256 or 16777216) | | `enable_raw_mode()` / `disable_raw_mode()` | puts stdin in raw mode (no line buffering, no echo, no signal keys, output post-processing off, reads never block) and back. Calls are counted: every `enable` needs a matching `disable`. `TerminalError` when stdin is not a terminal | | `is_raw_mode()` | whether raw mode is on | | `restore_state()` | restores the original terminal settings regardless of the counter — call it from a `finally` or a recovery path | | `set_echo(enabled)` | turns input echo off/on (password prompts); `TerminalError` when stdin is not a terminal | | `poll_input(timeout_ms)` | is input available? Waits at most `timeout_ms` (negative: forever). Inside a task only that task waits | | `read_raw(max_bytes=256)` | the bytes that are available right now (empty string if none); never waits | | `write_raw(s)` | writes `s` to stdout without a trailing newline; flushes pending `print` output first so the order is kept | | `flush()` | flushes buffered `print` output | `read_raw` returns a `str` that is byte-safe: NUL bytes and incomplete UTF-8 are preserved exactly. A multi-byte character (or an escape sequence such as `ESC [ A`) can arrive in more than one read, so key decoders should buffer the bytes. ```nox import nox.terminal nox.terminal.enable_raw_mode() try: while True: if nox.terminal.poll_input(100): chunk: str = nox.terminal.read_raw(32) if chunk == "q": break finally: nox.terminal.disable_raw_mode() ``` ## Notes - Windows, WebAssembly and freestanding targets have no terminal control: `is_tty` is `False`, `enable_raw_mode`/`set_echo` raise `TerminalError`, and `get_size` uses the environment fallbacks. `write_raw` and `flush` still work on Windows, including when stdout is redirected to a file or pipe. - The terminal belongs to the whole process, so raw-mode state is process-wide. Always restore it (`finally`) — a program that exits in raw mode leaves the user's shell without echo. --- # nox.timezone IANA time zones (`Europe/Istanbul`, `America/New_York`, …): UTC offset, abbreviation, daylight-saving flag, and conversion between UTC timestamps and local wall-clock time. ```text import nox.timezone ``` **Capability:** `filesystem` (the module reads the system's `tzdata` files). The zone data is read from the machine's own time-zone database (TZif v2+): `$TZDIR`, `/usr/share/zoneinfo`, macOS `/var/db/timezone/zoneinfo`, Android `/system/usr/share/zoneinfo`. For instants after a zone's last recorded transition the file footer's POSIX rule (for example `EST5EDT,M3.2.0,M11.1.0`) is evaluated, so dates far in the future are correct too. Nothing is cached: each call reads and parses one small file, so keep a `ZoneInfo` or an offset if you convert in a tight loop. ```text import nox.time import nox.timezone off: int = nox.timezone.utc_offset("Europe/Istanbul", 1721044800) # 10800 local: nox.time.DateTime = nox.timezone.to_local("America/New_York", 1721044800 * 1000) ms: int = nox.timezone.from_local("Europe/Berlin", local) # wall clock -> UTC epoch ms print(nox.timezone.format_iso("Asia/Tokyo", ms)) # 2024-07-15T...+09:00 ``` | Function | Description | |---|---| | `utc_offset(zone, unix_s)` | seconds east of UTC at that instant | | `is_dst(zone, unix_s)` | is daylight-saving time in effect? | | `abbreviation(zone, unix_s)` | `CET`, `EDT`, `+03`, … | | `zone_info(zone, unix_s)` | a `ZoneInfo` with `zone`, `offset_s`, `abbreviation`, `is_dst` | | `to_local(zone, epoch_ms)` | a `nox.time.DateTime` showing the zone's wall clock | | `from_local(zone, datetime)` | the UTC epoch milliseconds of a wall-clock time in the zone | | `format_iso(zone, epoch_ms)` | `2024-07-15T21:00:00+09:00` (the offset is always written) | | `is_supported()` | can the zone database be read on this machine? | `unix_s` is a UTC Unix timestamp in seconds, `epoch_ms` in milliseconds. ## Ambiguous and missing local times A wall-clock time can occur twice (clocks go back) or not at all (clocks go forward). `from_local` follows Python's `fold=0` rule: - **ambiguous** (Berlin 2024-10-27 02:30): the *first* occurrence, the daylight-saving one (`+02:00`); - **missing** (Berlin 2024-03-31 02:30): resolved with the offset *before* the gap, so the result is `03:30+02:00`. ## Errors and platforms - An unknown zone name raises `TimezoneError` (its `zone` field holds the name). Names are validated before use (no leading `/` or `.`, no `..`), so passing untrusted input is safe. - `UTC`, `Etc/UTC` and `GMT` never need the database. - On Windows, in WebAssembly, on iOS and in containers without `tzdata`, `is_supported()` is `False` and every zone except UTC raises `TimezoneError`. --- # nox.console Levelled message printing **without** timestamps or any operating-system dependency — safe in every profile, including freestanding kernels. ```text import nox.console ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `format(level, message)` | builds `"[LEVEL] message"` without printing | | `debug(message)`, `info(message)`, `warn(message)`, `error(message)` | prints `[DEBUG]`/`[INFO]`/`[WARN]`/`[ERROR]` followed by the message to standard output | ```nox import nox.console nox.console.info("server started") nox.console.warn("disk almost full") nox.console.error("boom") print(nox.console.format("INFO", "x")) ``` ```output [INFO] server started [WARN] disk almost full [ERROR] boom [INFO] x ``` Use [`nox.log`](https://noxlang.com/docs/stdlib/log/) when you want a timestamp on every line. --- # nox.log Levelled logging with a millisecond timestamp on every line. ```text import nox.log ``` **Capability:** `clock` (reads the system clock). ## Functions | Function | Description | |---|---| | `format(level, message)` | builds `"[LEVEL] [timestamp_ms] message"` without printing; the timestamp is milliseconds since the Unix epoch | | `redact(message, secrets)` | replaces every occurrence of each non-empty secret with `***` | | `mask_assignments(message, keys)` | masks the value of `key=value` pairs (`password=p4ss` → `password=***`); the key must start at a word boundary, the value ends at whitespace, `&`, `,`, `;` or a quote | | `set_level(name)` | sets the minimum level printed: `"DEBUG"` (default, everything), `"INFO"`, `"WARN"`, `"ERROR"` or `"OFF"`; an unknown name raises `ValueError` | | `level()` | the name of the current minimum level | | `enabled(name)` | `True` if a line at level `name` would be printed now (`False` for unknown names) | | `debug(message)`, `info(message)`, `warn(message)`, `error(message)` | prints the formatted line to standard output unless it is below the minimum level | Output looks like: ```text [INFO] [1791446397900] server started [WARN] [1791446397902] careful ``` The filter is a module-level setting (the default prints everything, as before); there is no file or network sink: the functions are thin wrappers around `print`. If you need to route logs elsewhere, wrap `format` in your own function; for timestamp-free output use [`nox.console`](https://noxlang.com/docs/stdlib/console/). ```nox import nox.log line: str = nox.log.format("INFO", "ready") print(line.startswith("[INFO] ["), line.endswith("] ready")) ``` ```output True True ``` --- # nox.json Parse and generate JSON. Parsing is done by a battle-tested native parser; the result is a tree of `JsonValue` nodes that you inspect with typed accessors. For generating JSON there are two styles: dump an existing tree, or build text incrementally with `JsonWriter`. ```text import nox.json from nox.json import JsonError, JsonWriter ``` **Capability:** none. `JsonValue` is part of the prelude (it needs no import); `JsonError` is raised on malformed input. ## Parsing | Function | Description | |---|---| | `parse(s)` | parses `s` into a `JsonValue`; raises `JsonError` for invalid JSON (any depth of nesting is supported) | ## Inspecting a `JsonValue` Every node is exactly one of null, boolean, number, string, array or object. Test the kind first, then read it: | Function | Description | |---|---| | `is_null(v)`, `is_bool(v)`, `is_number(v)`, `is_string(v)`, `is_array(v)`, `is_object(v)` | kind tests | | `as_bool(v)`, `as_number(v)`, `as_string(v)` | the value; `as_number` is a `float` (integers above 2^53 lose precision as a `float`: use `as_int`) | | `as_int(v)` | the exact `int` value of a number (a `JsonError` if it is not an integer or does not fit in `int`); integers of 2^53 and above keep their exact text, so `9007199254740993` is not rounded | | `number_text(v)` | the number's decimal text (the exact text for integers of 2^53 and above, and `1.0` / `100.0` for a number written with a fraction or exponent); `dump` writes such numbers unchanged | | `array_len(v)`, `array_get(v, i)` | array length and element | | `object_len(v)`, `object_key(v, i)`, `object_value(v, i)` | an object's `i`-th entry, **in document order** | ```nox import nox.json from nox.json import JsonError v: JsonValue = nox.json.parse("{\"name\": \"ada\", \"age\": 36, \"tags\": [\"a\", \"b\"], \"ok\": true, \"none\": null, \"pi\": 3.5}") print(nox.json.is_object(v), nox.json.object_len(v)) i: int = 0 while i < nox.json.object_len(v): k: str = nox.json.object_key(v, i) x: JsonValue = nox.json.object_value(v, i) if nox.json.is_string(x): print(k, "string", nox.json.as_string(x)) elif nox.json.is_number(x): print(k, "number", nox.json.as_number(x)) elif nox.json.is_bool(x): print(k, "bool", nox.json.as_bool(x)) elif nox.json.is_array(x): print(k, "array", nox.json.array_len(x), nox.json.as_string(nox.json.array_get(x, 1))) elif nox.json.is_null(x): print(k, "null") i += 1 try: nox.json.parse("{bad") except JsonError as e: print("JsonError") ``` ```output True 6 name string ada age number 36.0 tags array 2 b ok bool True none null pi number 3.5 JsonError ``` To look a key up by name use `get` (a linear scan in document order; there is no hash index). For large documents prefer the position-based functions below. ## Checked readers | Function | Description | |---|---| | `get(v, key)`, `get_or_null(v, key)` | an object's value by key (`JsonError` if missing / a JSON `null`) | | `expect_object(v, what)`, `expect_array(v)` | `JsonError` unless the node has that kind | | `read_int(v)`, `read_float(v)`, `read_bool(v)`, `read_str(v)` | the value, or `JsonError` when the node has another kind | They are what the code generated by [`@derive("json")`](https://noxlang.com/docs/language/classes/#generated-methods-dataclass-and-derive) calls; you can use them directly. ## Position-based traversal (no nodes) `array_get`, `object_key` and `object_value` build a `JsonValue` (and a `str` for keys) for every step. On large documents that allocation is the cost of a traversal. The `pos_*` functions walk the parsed document by **position** (an `int`) instead: nothing is allocated except the strings you ask for, so a traversal is several times faster. They do not replace the node API: `pos_value(v, p)` turns a position into a node whenever you need one. `v` is any node of the document (usually the `parse` result); positions are only valid in that document. A wrong position never crashes: it raises `JsonError("invalid position")`. A scalar root (`parse("5")`) has no positions: use `as_*`. | Function | Description | |---|---| | `pos_root(v)` | position of `v` itself | | `pos_kind(v, p)` | the kind: 0 null, 1 bool, 2 number, 3 string, 4 array, 5 object | | `pos_len(v, p)`, `pos_at(v, p, i)` | length of an array/object, and the position of the `i`-th element (for an object: of the `i`-th entry's **value**; a negative `i` counts from the end) | | `pos_get(v, p, key)`, `pos_find(v, p, key)` | the position of an object's value by key (`pos_get` raises `JsonError` if it is missing, `pos_find` returns `-1`) | | `pos_key_is(v, p, i, key)`, `pos_key(v, p, i)` | compare the `i`-th key with `key` without allocating, or read it as a `str` | | `pos_int`, `pos_number`, `pos_bool`, `pos_str` | the value at a position, with the same rules as `as_int` / `as_number` / `as_bool` / `as_string` (and a `JsonError` for another kind) | | `pos_value(v, p)`, `pos_dump(v, p)` | the node at a position, and its compact JSON text | ```nox import nox.json v: JsonValue = nox.json.parse("[{\"id\": 1, \"name\": \"ada\", \"score\": 2.5}, {\"id\": 2, \"name\": \"bob\", \"score\": 4.0}]") root: int = nox.json.pos_root(v) total: int = 0 best: str = "" i: int = 0 while i < nox.json.pos_len(v, root): row: int = nox.json.pos_at(v, root, i) total += nox.json.pos_int(v, nox.json.pos_get(v, row, "id")) if nox.json.pos_number(v, nox.json.pos_get(v, row, "score")) > 3.0: best = nox.json.pos_str(v, nox.json.pos_get(v, row, "name")) i += 1 print(total, best) print(nox.json.pos_dump(v, nox.json.pos_at(v, root, 0))) ``` ```output 3 bob {"id":1,"name":"ada","score":2.5} ``` ## Dumping a tree | Function | Description | |---|---| | `dump(v)` | compact JSON text. A number keeps the way it was written: `1` stays `1`, `1.0` and `1e2` come back as `1.0` and `100.0` (like Python's `json.dumps`), so a parse/dump round trip never turns a float into an int | | `dump_pretty(v, indent)` | indented JSON, `indent` spaces per level | | `dump_string(s)` | a JSON string literal for `s`, with all required escapes | | `dump_number(n)` | a JSON number for a `float` (whole values print without `.0`) | | `dump_array(v)`, `dump_object(v)` | compact dump of an array / object node | | `dump_pretty_at(v, indent, level)`, `dump_pretty_array(...)`, `dump_pretty_object(...)` | the recursive pretty-printing helpers behind `dump_pretty` | | `indent_str(indent, level)` | the indentation string for a level | ```nox import nox.json v: JsonValue = nox.json.parse("{\"name\": \"ada\", \"tags\": [\"a\", \"b\"], \"pi\": 3.5}") print(nox.json.dump(v)) print(nox.json.dump_pretty(v, 2)) print(nox.json.dump_string("a\"b\n"), nox.json.dump_number(3.0), nox.json.dump_number(2.5)) ``` ```output {"name":"ada","tags":["a","b"],"pi":3.5} { "name": "ada", "tags": [ "a", "b" ], "pi": 3.5 } "a\"b\n" 3 2.5 ``` ## `JsonWriter` — building JSON without a tree `JsonWriter` appends pieces and joins them once at the end, so building a large document is linear in its size. Open containers with `begin_object` / `begin_array` and close them in order; inside an object call `write_key` before each value. | Method | Description | |---|---| | `JsonWriter()` | an empty writer | | `begin_object()`, `end_object()`, `begin_array()`, `end_array()` | containers | | `write_key(key)` | the key of the next value (inside an object) | | `write_string(s)`, `write_int(n)`, `write_float(n)`, `write_bool(b)`, `write_null()` | scalar values | | `write_value(v)` | embeds an existing `JsonValue` subtree | | `build()` | the finished JSON text | ```nox from nox.json import JsonWriter w: JsonWriter = JsonWriter() w.begin_object() w.write_key("id") w.write_int(7) w.write_key("items") w.begin_array() w.write_string("x") w.write_float(1.5) w.write_bool(False) w.write_null() w.end_array() w.end_object() print(w.build()) ``` ```output {"id":7,"items":["x",1.5,false,null]} ``` The writer does not validate your nesting: mismatched `end_*` calls or a missing `write_key` produce malformed text. ## Notes - Numbers are doubles: integers above 2⁵³ lose precision. Strings are decoded to UTF-8 `str`. - The names `decode`, `encode`, `encode_pretty` and the other `encode_*` forms were removed in 2.0 ([Migrating](https://noxlang.com/docs/whatsnew/migrating/)). --- # nox.toml Parse and write TOML 1.0 documents. The parser is written in Nox; invalid input is rejected with a clear `TomlError` (including duplicate keys and tables defined twice) rather than silently misread. ```text import nox.toml from nox.toml import TomlValue, TomlError ``` **Capability:** none. The module works on text; read files with [`nox.fs`](https://noxlang.com/docs/stdlib/fs/). ## Functions | Function | Description | |---|---| | `parse(text)` | parses a document into a `TomlValue` (a table); raises `TomlError` on a syntax error | | `get(root, dotted_path)` | follows a dotted path through nested tables (`"server.tls.enabled"`); raises `TomlError` if a segment is missing or not a table | | `dump(v)` | writes a table back to TOML text | | `is_string(v)`, `is_int(v)`, `is_float(v)`, `is_bool(v)`, `is_array(v)`, `is_table(v)`, `is_datetime(v)` | kind tests | ## `TomlValue` A node has public fields; read the one that matches its kind: | Kind | Field | Type | |---|---|---| | string | `s` | `str` | | integer | `i` | `int` | | float | `f` | `float` | | boolean | `b` | `bool` | | array | `arr` | `list[TomlValue]` | | table | `tbl` | `dict[str, TomlValue]` | | date / time | `s` | `str` (the raw text, e.g. `1979-05-27T07:32:00-08:00`, `1979-05-27`, `07:32:00`) | ```nox import nox.toml from nox.toml import TomlValue, TomlError t: TomlValue = nox.toml.parse("title = \"demo\"\n[server]\nport = 8080\nhosts = [\"a\", \"b\"]\n[server.tls]\nenabled = true\nratio = 0.5\n") print(nox.toml.is_table(t), nox.toml.get(t, "title").s, nox.toml.get(t, "server.port").i, nox.toml.get(t, "server.tls.enabled").b, nox.toml.get(t, "server.tls.ratio").f) hosts: TomlValue = nox.toml.get(t, "server.hosts") print(nox.toml.is_array(hosts), len(hosts.arr), hosts.arr[1].s) print(nox.toml.dump(t)) try: nox.toml.get(t, "x.y") except TomlError as e: print("missing key") ``` ```output True demo 8080 True 0.5 True 2 b title = "demo" [server] port = 8080 hosts = ["a", "b"] [server.tls] enabled = true ratio = 0.5 missing key ``` ## Supported TOML Comments; `[table]` and `[[array of tables]]` headers (dotted, with quoted segments); bare, `"basic"` and `'literal'` keys and dotted keys on a `key = value` line (`a.b.c = 1`); basic, literal and multi-line (`"""`, `'''`) strings with all escapes (`\b \t \n \f \r \" \\ \uXXXX \UXXXXXXXX`, line-ending backslash); decimal, `0x`, `0o` and `0b` integers (with `_`); floats (exponents, `inf`, `nan`); booleans; arrays (mixed types, several lines); inline tables (`{k = v}`); and date/time values (offset date-time, local date-time, local date, local time), which are kept as their raw text (`is_datetime`). In an array of tables, `get` follows the **last** element. `dump` writes arrays of tables back as `[[name]]` blocks. ```nox import nox.toml from nox.toml import TomlValue t: TomlValue = nox.toml.parse("owner.name = \"Tom\"\nport = 0x1F90\nwhen = 1979-05-27\ninline = { x = 1, y = { z = \"deep\" } }\n[[servers]]\nname = \"a\"\n[[servers]]\nname = \"b\"\n") print(nox.toml.get(t, "owner.name").s, nox.toml.get(t, "port").i, nox.toml.get(t, "when").s, nox.toml.get(t, "inline.y.z").s) servers: TomlValue = nox.toml.get(t, "servers") print(len(servers.arr), servers.arr[1].tbl["name"].s) ``` ```output Tom 8080 1979-05-27 deep 2 b ``` --- # nox.yaml Parse and write a practical subset of YAML — enough for configuration files. The parser is written in Nox and rejects anything outside the supported subset with a `YamlError` instead of guessing. ```text import nox.yaml from nox.yaml import YamlValue, YamlError ``` **Capability:** none. The module works on text; read files with [`nox.fs`](https://noxlang.com/docs/stdlib/fs/). ## Functions | Function | Description | |---|---| | `parse(text)` | parses one document into a `YamlValue`; raises `YamlError` (also when the text holds several documents) | | `parse_all(text)` | parses every document of a `---` separated stream into a `list[YamlValue]` | | `get(root, dotted_path)` | follows a dotted path through nested mappings and sequences (`"nested.deep"`, `"servers.0.name"`); raises `YamlError` if a segment is missing | | `dump(v)` | writes a mapping or sequence as block-style YAML (strings are always double-quoted, aliases are written out in full) | | `dump_all(docs)` | writes several documents separated by `---` | | `is_string(v)`, `is_int(v)`, `is_float(v)`, `is_bool(v)`, `is_null(v)`, `is_sequence(v)`, `is_mapping(v)` | kind tests | ## `YamlValue` | Kind | Field | Type | |---|---|---| | string | `s` | `str` | | integer | `i` | `int` | | float | `f` | `float` | | boolean | `b` | `bool` | | null | — | — | | sequence | `arr` | `list[YamlValue]` | | mapping | `mapping` | `dict[str, YamlValue]` (keys are always strings) | Plain scalars are converted automatically: `36` is an integer, `1.5` a float, `true`/`false` booleans, `null` a null; anything else is a string. Quote a value (`"36"`) to force a string. ```nox import nox.yaml from nox.yaml import YamlValue, YamlError y: YamlValue = nox.yaml.parse("name: ada\nage: 36\nlangs:\n - nox\n - zig\nnested:\n deep: true\n ratio: 1.5\nnothing: null\n") print(nox.yaml.is_mapping(y), nox.yaml.get(y, "name").s, nox.yaml.get(y, "age").i, nox.yaml.get(y, "nested.deep").b, nox.yaml.is_null(nox.yaml.get(y, "nothing"))) langs: YamlValue = nox.yaml.get(y, "langs") print(nox.yaml.is_sequence(langs), len(langs.arr), langs.arr[0].s) print(nox.yaml.dump(y)) try: nox.yaml.get(y, "missing") except YamlError as e: print("missing key") ``` ```output True ada 36 True True True 2 nox name: "ada" age: 36 langs: - "nox" - "zig" nested: deep: true ratio: 1.5 nothing: null missing key ``` ## Supported YAML YAML 1.2 (core schema): block mappings and sequences (including `- key: value` items and a sequence at the same indent as its key); flow sequences and mappings (multi-line, nested); plain, single- and double-quoted scalars (all double-quote escapes: `\n \t \r \0 \" \\ \xHH \uHHHH \UHHHHHHHH`), multi-line plain and quoted scalars (line folding); block scalars `|` and `>` with chomping (`-`, `+`) and indentation indicators; explicit keys (`? key` followed by `: value`, for scalar keys); trailing comments; anchors (`&a`), aliases (`*a`) and merge keys (`<<: *a`, `<<: [*a, *b]`); the tags `!!str`, `!!int`, `!!float`, `!!bool` and `!!null` (other tags are ignored); several documents in one stream (`---`, `...`, see `parse_all`); `%` directives are skipped. Plain scalars follow the 1.2 core schema: `true`/`false`, `null`/`~`, decimal and `0x`/`0o` integers, floats (`1.5e3`, `.5`), `.inf`, `-.inf` and `.nan`; everything else (including `yes`, `no`, `1_000` and dates) is a string. Mapping keys are always stored as strings (a scalar key by its text). **Not supported:** collection keys (`? [a, b]`, `? - a`): keys are stored as strings, so a sequence or mapping key raises `YamlError`; complex tags and `!!binary`/`!!timestamp` types (a date stays a string), and `%TAG` handles. An alias is the **same** value as its anchor, not a copy. ```nox import nox.yaml from nox.yaml import YamlValue cfg: YamlValue = nox.yaml.parse("base: &b\n retries: 3\nprod:\n <<: *b\n host: example.org # live\nmsg: |\n hello\n world\n") print(nox.yaml.get(cfg, "prod.retries").i, nox.yaml.get(cfg, "prod.host").s, nox.yaml.get(cfg, "msg").s == "hello\nworld\n") docs: list[YamlValue] = nox.yaml.parse_all("---\na: 1\n---\nb: 2\n") print(len(docs), nox.yaml.get(docs[1], "b").i) ``` ```output 3 example.org True 2 2 ``` --- # nox.csv Read and write CSV text following RFC 4180: comma-separated fields, optional double-quoted fields that may contain commas, quotes and line breaks, and `""` as an escaped quote. ```text import nox.csv from nox.csv import CsvError ``` **Capability:** none. The module works on text; read files with [`nox.fs`](https://noxlang.com/docs/stdlib/fs/). ## Functions | Function | Description | |---|---| | `parse(text)` | parses the whole text into rows of fields (`list[list[str]]`); raises `CsvError` for an unterminated quoted field | | `parse_dicts(text)` | treats the first row as the header and returns one `dict[str, str]` per following row | | `dump_row(fields)` | formats one row, quoting fields that need it (no trailing newline) | | `dump(rows)` | formats all rows, one per line, each followed by `\n` | Input may use `\n` or `\r\n` line endings; output always uses `\n`. All values are strings — convert with `int(...)` / `float(...)` yourself. ```nox import nox.csv from nox.csv import CsvError rows: list[list[str]] = nox.csv.parse("a,b,c\n1,\"x,y\",3\n") print(rows, len(rows)) dicts: list[dict[str, str]] = nox.csv.parse_dicts("name,age\nada,36\nalan,41\n") print(dicts[1]["name"], len(dicts)) print(nox.csv.dump_row(["a", "b,c", "d\"e"])) print(nox.csv.dump([["x", "y"], ["1", "2"]]), end="") try: nox.csv.parse("a,\"unterminated") except CsvError as e: print("bad csv") ``` ```output [['a', 'b', 'c'], ['1', 'x,y', '3']] 2 alan 2 a,"b,c","d""e" x,y 1,2 bad csv ``` ## Out of scope Custom delimiters (`;`, tab), a byte-order mark, and reading files directly (pass the text from [`nox.fs.read_to_string`](https://noxlang.com/docs/stdlib/fs/)). The names `write` and `write_row` were removed in 2.0; use `dump` and `dump_row` ([Migrating](https://noxlang.com/docs/whatsnew/migrating/)). --- # nox.regex A backtracking regular-expression engine with the everyday subset of Python's `re`: groups and captures, alternation, counted and lazy repetition, escape classes, anchors, back-references and lookahead. Text is UTF-8; `.` and classes work on code points, while the `start`/`end` positions of a match are **byte** offsets. ```text import nox.regex ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `search(pattern, text, flags=0)` | the first match anywhere in `text` as a `Match`, or `None` | | `match(pattern, text, flags=0)` | a match that starts at the beginning of `text`, or `None` | | `full_match(pattern, text, flags=0)` | a match of the **whole** text, or `None`; `is_full_match(...)` returns a `bool` | | `find_matches(pattern, text, flags=0)` | every non-overlapping match as a `list[Match]` | | `find_all(pattern, text, flags=0)` | the text of every non-overlapping match | | `replace(pattern, repl, text, flags=0, count=0)` | replace matches; `repl` may use `\1`, `\g`, `\g<1>`, `\n`, `\t`, `\\`; `count > 0` limits the replacements | | `split(pattern, text, flags=0)` | split `text` at every match | | `escape(s)` | escape pattern metacharacters so `s` matches literally | | `is_match(pattern, text)`, `find(pattern, text)` | the original total functions: `bool` / byte index or `-1`; an invalid pattern gives `False` / `-1` instead of an error | The other functions raise `RegexError` for an invalid pattern. Flags are `IGNORECASE`, `MULTILINE` and `DOTALL` (combine with `|`); `(?i)`, `(?m)` and `(?s)` at the start of a pattern set the same flags. A `Match` has `start`, `end`, `text` (the searched text), and the methods `whole()`, `group(i)` (an unmatched group is `""`), `named(name)`, `groups()`, `matched(i)` and `count()`. ## Supported syntax | Syntax | Meaning | |---|---| | a literal character | matches itself | | `.` | any character except a newline (any character with `DOTALL`) | | `*`, `+`, `?`, `{m}`, `{m,}`, `{m,n}`, `{,n}` | repetition of the preceding item (greedy; add `?` for lazy) | | `[abc]`, `[a-z]`, `[^abc]`, `[\d_-]` | a class, a range, a negated class; escapes work inside classes | | `\d \D \w \W \s \S` | digit / word / space classes and their complements (Unicode-aware) | | `^`, `$`, `\A`, `\z`, `\Z` | start / end of the text (line start / end with `MULTILINE`) | | `\b`, `\B` | word boundary / not a word boundary | | `( )`, `(?: )`, `(?P )`, `(? )` | capturing group, non-capturing group, named group | | `a|b` | alternation | | `\1` ... `\99` | back-reference to a captured group | | `(?= )`, `(?! )` | positive / negative lookahead | | `\n \t \r \f \v \0 \xHH \uHHHH`, `\.` | escaped characters | **Not supported:** lookbehind `(?<= )`, atomic and possessive groups, conditional patterns and `\p{...}` property classes. Matching is bounded: a pattern that needs more than about twenty million steps (for example `(a+)+b` on a long run of `a`) reports "no match" instead of hanging. ```nox import nox.regex m: nox.regex.Match | None = nox.regex.search("(?P\\d{4})-(\\d{2})-(\\d{2})", "released 2026-10-29!") if m is not None: print(m.whole(), m.start, m.end, m.named("year"), m.groups()) print(nox.regex.find_all("\\b\\w+@\\w+\\.com\\b", "ada@lovelace.com, bob@example.com")) print(nox.regex.replace("(\\w+)@(\\w+)", "\\2 at \\1", "ada@lovelace")) print(nox.regex.split("\\s*,\\s*", "a , b,c")) print(nox.regex.is_full_match("[a-z]+\\d?", "abc1"), nox.regex.is_match("^colou?r$", "color")) ``` ```output 2026-10-29 9 19 2026 ['2026', '10', '29'] ['ada@lovelace.com', 'bob@example.com'] lovelace at ada ['a', 'b', 'c'] True True ``` ## Notes - Matching uses backtracking with an explicit stack, so long inputs do not exhaust the call stack. - The validator in [`nox.validate`](https://noxlang.com/docs/stdlib/validate/) uses this module for its `pattern` rule. --- # nox.unicode Unicode normalization (UAX #15) and locale-specific case mapping for Turkish and Azeri. `str` itself already follows Unicode for `upper()`, `lower()`, `casefold()` and the `is...()` tests (see [Strings](https://noxlang.com/docs/language/strings/#methods)); this module adds what a string method cannot express. ```text import nox.unicode ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `normalize(s, form="NFC")` | `s` in normalization form `"NFC"`, `"NFD"`, `"NFKC"` or `"NFKD"`; any other name raises `ValueError` | | `is_normalized(s, form="NFC")` | whether `normalize(s, form)` leaves `s` unchanged | | `upper_tr(s)` | `upper()` with the Turkish pairs `i`→`İ` and `ı`→`I` | | `lower_tr(s)` | `lower()` with the Turkish pairs `I`→`ı` and `İ`→`i` | The tables come from the same Unicode version as the `str` methods (17.0) and are checked against Python's `unicodedata` (`scripts/gen_unicode_tables.py`). Invalid UTF-8 bytes pass through unchanged and never combine with their neighbours. ```nox import nox.unicode composed: str = nox.unicode.normalize("e\u0301", "NFC") print(len(composed), composed == "\u00e9", nox.unicode.is_normalized("e\u0301")) print(len(nox.unicode.normalize("\u00e9", "NFD")), nox.unicode.normalize("\ufb01", "NFKC")) print(nox.unicode.upper_tr("istanbul"), nox.unicode.lower_tr("ISPARTA"), "istanbul".upper()) ``` ```output 1 True False 2 fi İSTANBUL ısparta ISTANBUL ``` ## Not covered Text shaping (ligatures, Arabic joining, bidirectional ordering) and grapheme-cluster segmentation are rendering concerns and are not part of the string library. `len(s)` counts code points, not user-perceived characters; normalize first when comparing text that may be composed differently. --- # nox.template A minimal text template engine: `{{ name }}` placeholders replaced from a dictionary. By default every value is **HTML-escaped**, which is the basic defence against cross-site scripting. `render` / `render_unescaped` only substitute placeholders; `render_blocks` / `render_blocks_unescaped` also understand `{% for %}` and `{% if %}`. ```text import nox.template from nox.template import TemplateError ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `render(tmpl, context)` | replaces each `{{ name }}` with the HTML-escaped value from `context`; raises `TemplateError` for an unterminated placeholder or an unknown name | | `render_unescaped(tmpl, context)` | the same, but inserts values verbatim — for fragments you built yourself and know to be safe | | `escape_html(s)` | escapes `&`, `<`, `>`, `"` and `'` | Whitespace inside the braces is ignored (`{{name}}` and `{{ name }}` are equal). ```nox import nox.template print(nox.template.render("Hello {{ name }}! {{ x }}", {"name": "", "x": "1"})) print(nox.template.render_unescaped("{{ html }}", {"html": "bold"})) print(nox.template.escape_html("a&\"'")) ``` ```output Hello <Ada>! 1 bold a<b>&"' ``` ## Building a list ```nox import nox.template items: list[str] = ["a", "b"] rows: str = "" for it in items: rows = rows + nox.template.render("
  • {{ v }}
  • ", {"v": it}) print(nox.template.render_unescaped("
      {{ rows }}
    ", {"rows": rows})) ``` ```output
    • a
    • b
    ``` ## Blocks: loops and conditions `render_blocks(template, scalars, lists)` adds two block tags. Data comes in two dictionaries: `scalars: dict[str, str]` for `{{ name }}` and conditions, and `lists: dict[str, list[dict[str, str]]]` for loops (each item is a dictionary of fields). | Syntax | Meaning | |---|---| | `{% for u in users %}…{% endfor %}` | repeats the body for each item of `lists["users"]`; `{{ u.name }}` reads the item's field `name` | | `loop.index`, `loop.index0`, `loop.first`, `loop.last` | inside a loop: 1-based and 0-based position, and `"true"`/`"false"` flags | | `{% if name %}…{% else %}…{% endif %}` | true when the scalar is non-empty and not `"0"`/`"false"`/`"False"`, or the named list is non-empty; an undefined name is false | | `{% if not name %}…{% endif %}` | negation | Blocks nest. A missing `endfor`/`endif`, a stray `endfor`/`endif`/`else`, an unknown tag, an undefined `{{ name }}` and an undefined loop list all raise `TemplateError`. Values are HTML-escaped by `render_blocks`; `render_blocks_unescaped` writes them as is. Plain `render` leaves `{% … %}` untouched. ```nox import nox.template users: list[dict[str, str]] = [{"name": "Ada"}, {"name": "Bob"}] html: str = nox.template.render_blocks("{% for u in users %}{{ loop.index }}:{{ u.name }}{% if loop.last %}.{% else %}, {% endif %}{% endfor %}", {}, {"users": users}) print(html) ``` ```output 1:Ada, 2:Bob. ``` ## Notes - Only `str` values are supported; convert numbers with `str(...)` first. - Escape for the context you are writing into: HTML-escaping protects HTML text and quoted attributes, not JavaScript or URL contexts. - Web frameworks such as Nyx provide richer view layers on top of the same idea. --- # nox.validate Validate JSON documents — typically HTTP request bodies — against a declarative schema. Validation returns a list of human-readable problems (empty means valid) instead of raising, so a handler can report every problem at once. ```text import nox.validate from nox.validate import Schema ``` **Capability:** none. ## Building a schema A `Schema` is a list of field rules. Add rules with `require` (the field must exist) or `optional`, naming the expected **kind**: `"string"`, `"number"`, `"bool"`, `"array"`, `"object"` or `"null"`. | Method | Description | |---|---| | `Schema()` | an empty schema | | `require(name, kind)`, `optional(name, kind)` | a required / optional field of that kind | | `require_object_schema(name, sub)`, `optional_object_schema(name, sub)` | a nested object validated against `sub` | | `require_array_of_kind(name, elem_kind)`, `optional_array_of_kind(name, elem_kind)` | an array whose elements are all of one kind | | `require_array_of_schema(name, sub)`, `optional_array_of_schema(name, sub)` | an array of objects, each validated against `sub` | Constraints are attached to an already-added rule by name; applying one to a rule of the wrong kind (or naming an unknown rule or format) raises `ValueError` so typos are not silently ignored: | Method | Applies to | Description | |---|---|---| | `min(name, v)`, `max(name, v)` | `number` | inclusive bounds | | `min_length(name, n)`, `max_length(name, n)` | `string` | length bounds (code points) | | `pattern(name, regex)` | `string` | must match the [`nox.regex`](https://noxlang.com/docs/stdlib/regex/) pattern | | `format(name, fmt)` | `string` | `"email"` or `"uuid"` | `FieldRule` is the internal record that `Schema` keeps for each rule; you normally never construct one yourself. ## Validating | Function | Description | |---|---| | `validate(v, schema)` | validates a parsed `JsonValue`; returns the list of problems | | `validate_json_str(s, schema)` | parses `s` first; invalid JSON yields a single problem | Problem messages name the field by its full path — `address.city`, `tags[1]`. They are English. Test for emptiness or count, and show the list to the user rather than matching text. ```nox import nox.validate from nox.validate import Schema addr: Schema = Schema() addr.require("city", "string") s: Schema = Schema() s.require("name", "string") s.min_length("name", 2) s.require("age", "number") s.min("age", 0.0) s.max("age", 150.0) s.optional("email", "string") s.format("email", "email") s.require_object_schema("address", addr) s.require_array_of_kind("tags", "string") bad: list[str] = nox.validate.validate_json_str("{\"name\": \"a\", \"age\": 200, \"email\": \"bad\", \"address\": {}, \"tags\": [\"x\", 1]}", s) print(len(bad)) good: list[str] = nox.validate.validate_json_str("{\"name\": \"ada\", \"age\": 36, \"address\": {\"city\": \"x\"}, \"tags\": []}", s) print(len(good), len(nox.validate.validate_json_str("not json", s))) ``` ```output 5 0 1 ``` ## Use in a web handler ```nox-fragment errors: list[str] = nox.validate.validate_json_str(ctx.request.body, schema) if len(errors) > 0: return HttpResponse(400, nox.strings.join(errors, "; "), {"Content-Type": "text/plain"}) ``` --- # nox.url Parse URLs, percent-encode and decode text, and build or read query strings. ```text import nox.url from nox.url import URL, UrlError ``` **Capability:** none. ## `URL` and `parse` `parse(s)` splits an absolute URL into a `URL` with these fields: | Field | Type | Example for `https://user:pw@example.com:8443/a/b?x=1&y=two#frag` | |---|---|---| | `scheme` | `str` | `https` | | `userinfo` | `str` | `user:pw` | | `host` | `str` | `example.com` | | `port` | `int` | `8443` (0 when absent) | | `path` | `str` | `/a/b` | | `query` | `dict[str, str]` | `{'x': '1', 'y': 'two'}` (decoded) | | `fragment` | `str` | `frag` | A malformed URL raises `UrlError`. ## Functions | Function | Description | |---|---| | `parse(s)` | see above | | `percent_encode(s)` | encodes every byte outside the unreserved set (`A–Z a–z 0–9 - _ . ~`) as `%XX`, operating on UTF-8 bytes | | `percent_decode(s)` | the inverse | | `query_encode(params)` | `k=v&k2=v2` with both parts percent-encoded | | `query_decode(s)` | parses a query string into a dictionary (decoded) | | `query_int(q, key)`, `query_float(q, key)`, `query_bool(q, key)` | typed access to a decoded query dictionary; a missing key or a value of the wrong form raises `ValueError` | | `join(base, relative)` | resolves a relative reference against a base URL (it replaces the last path segment; `..` segments are kept as written) | ```nox import nox.url from nox.url import URL u: URL = nox.url.parse("https://user:pw@example.com:8443/a/b?x=1&y=two#frag") print(u.scheme, u.userinfo, u.host, u.port, u.path, u.query["y"], u.fragment) print(nox.url.percent_encode("a b&c/é"), nox.url.percent_decode("a%20b%26c")) print(nox.url.query_encode({"q": "a b", "n": "1"}), nox.url.query_decode("a=1&b=x%20y")) q: dict[str, str] = {"n": "42", "f": "2.5", "b": "true"} print(nox.url.query_int(q, "n"), nox.url.query_float(q, "f"), nox.url.query_bool(q, "b")) print(nox.url.join("https://example.com/a/", "d?e=1")) try: nox.url.query_int(q, "missing") except ValueError as e: print("missing or malformed") ``` ```output https user:pw example.com 8443 /a/b two frag a%20b%26c%2F%C3%A9 a b&c q=a%20b&n=1 {'a': '1', 'b': 'x y'} 42 2.5 True https://example.com/a/d?e=1 missing or malformed ``` ## Notes - Percent-encoding works on bytes, so non-ASCII text round-trips exactly. - Query dictionaries keep one value per key (the last one wins for repeated keys). --- # nox.base64 Base64 encoding and decoding of text, in the standard and the URL-safe alphabets. ```text import nox.base64 from nox.base64 import Base64Error ``` **Capability:** none registered; the module is pure Nox and works wherever the compiler's hosted profile does (it is not on the freestanding allow-list). ## Functions | Function | Description | |---|---| | `encode(data)` | standard Base64 (`+`, `/`) with `=` padding | | `encode_url(data)` | URL-safe Base64 (`-`, `_`) **without** padding, as used in JWTs | | `decode(s)` | decodes either alphabet, with or without padding; raises `Base64Error` for invalid input | Input and output are `str`. The data is processed as the UTF-8 bytes of the string. ```nox import nox.base64 print(nox.base64.encode("hello"), nox.base64.decode("aGVsbG8=")) print(nox.base64.encode_url("??>>"), nox.base64.decode("Pz8-Pg")) ``` ```output aGVsbG8= hello Pz8-Pg ??>> ``` For binary data, convert bytes to a string with `nox.strings.char_from_byte` first, or use [`nox.gzip`](https://noxlang.com/docs/stdlib/gzip/)'s `list[int]` byte API for compression. --- # nox.uuid Random (version 4) and time-ordered (version 7) UUIDs. ```text import nox.uuid ``` **Capability:** none. UUIDs are generated from the operating system's secure random source. ## Functions | Function | Description | |---|---| | `uuid4()` | a new random UUID as a 36-character lowercase string (`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`) | | `uuid7()` | a time-ordered UUID (RFC 9562 version 7): the first 48 bits are the Unix time in milliseconds, so lexicographic order follows creation time (UUIDs created within the same millisecond are not ordered among themselves) | | `uuid7_at(unix_ms)` | `uuid7` with an explicit timestamp (deterministic tests, importing records) | | `uuid7_timestamp_ms(s)` | the timestamp embedded in a version 7 UUID; `ValueError` for anything else | | `is_valid(s)` | whether `s` is a well-formed UUID string (any version) | ```nox import nox.uuid x: str = nox.uuid.uuid4() print(len(x), nox.uuid.is_valid(x), nox.uuid.is_valid("nope")) ``` ```output 36 True False ``` --- # nox.crypto Hashes, message authentication, secure randomness and password hashing — built on the Zig standard library's cryptography, with no external dependency. ```text import nox.crypto from nox.crypto import CryptoError ``` **Capability:** none for the module; functions that need operating-system entropy — `secure_random_hex`, `argon2_hash`, `bcrypt_hash`, `scrypt_hash` (which generate a random salt) — are marked `entropy` and are unavailable in freestanding profiles. Hashing and verification of existing data are pure. ## Hashes All return a lowercase hexadecimal string of the digest of the UTF-8 bytes of `data`. | Function | Digest | |---|---| | `sha256(data)` | SHA-256 (64 hex characters) | | `sha512(data)` | SHA-512 (128 hex characters) | | `sha384(data)` | SHA-384 (96 hex characters) | | `sha3_256(data)`, `sha3_512(data)` | SHA-3 (64 / 128 hex characters) | | `blake3(data)` | BLAKE3 with a 32-byte output (64 hex characters) | | `md5(data)` | MD5 (32 hex characters). **Not collision resistant**: use it only for checksums and legacy compatibility, never for security | | `sha1(data)` | SHA-1 — **broken for security** (practical collisions exist); only for legacy interoperability | ## Message authentication and comparison | Function | Description | |---|---| | `hmac_sha256(key, data)` | HMAC-SHA-256 as hex | | `constant_time_eq(a, b)` | equality that takes time independent of where the strings differ — use it to compare secrets, MACs and tokens | ## Randomness | Function | Description | |---|---| | `secure_random_hex(n_bytes)` | `n_bytes` cryptographically secure random bytes as `2 * n_bytes` hex characters | Use this (never [`nox.random`](https://noxlang.com/docs/stdlib/random/)) for session ids, tokens, salts and keys. ## Password hashing Each scheme has a `*_hash(password)` that generates a random salt and returns a self-describing string, and a `*_verify(hash, password)` that checks a candidate: | Hash | Verify | Notes | |---|---|---| | `argon2_hash(password)` | `argon2_verify(hash, password)` | Argon2id, the recommended default | | `bcrypt_hash(password)` | `bcrypt_verify(hash, password)` | bcrypt | | `scrypt_hash(password)` | `scrypt_verify(hash, password)` | scrypt | Store the returned string as is. Verification is constant-time with respect to the password. Hashing is deliberately slow (tens of milliseconds); do not call it in a hot loop. ```nox import nox.crypto print(nox.crypto.sha256("abc")) print(nox.crypto.sha1("abc")) print(nox.crypto.sha512("abc")[0:16]) print(nox.crypto.hmac_sha256("key", "data")) print(nox.crypto.constant_time_eq("a", "a"), nox.crypto.constant_time_eq("a", "b"), len(nox.crypto.secure_random_hex(8))) h: str = nox.crypto.argon2_hash("hunter2") print(nox.crypto.argon2_verify(h, "hunter2"), nox.crypto.argon2_verify(h, "wrong"), h.startswith("$argon2id$")) ``` ```output ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad a9993e364706816aba3e25717850c26c9cd0d89d ddaf35a193617aba 5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0 True False 16 True False True ``` ## Authenticated encryption (AEAD) | Function | Description | |---|---| | `aead_seal(key_hex, nonce_hex, plaintext, aad="", algorithm="chacha20-poly1305") -> str` | encrypts and authenticates; returns `hex(ciphertext \|\| 16-byte tag)` | | `aead_open(key_hex, nonce_hex, sealed_hex, aad="", algorithm="chacha20-poly1305") -> str` | verifies and decrypts; raises `CryptoError` for a wrong key, nonce, `aad`, a modified or truncated seal | Algorithms (Zig `std.crypto.aead`): `"chacha20-poly1305"` (32-byte key, 12-byte nonce), `"xchacha20-poly1305"` (32-byte key, **24-byte** nonce, safe to pick at random), `"aes-256-gcm"` (32, 12), `"aes-128-gcm"` (16, 12). Keys and nonces are hex strings (`secure_random_hex(32)` makes a key, `secure_random_hex(12)` a nonce). **Never reuse a nonce with the same key.** `aad` is authenticated but not encrypted (use it to bind a seal to its context: a user id, a record name). `plaintext`, `aad` and the opened result are `str` values, so they hold valid UTF-8; encode binary data (hex/base64) before sealing it. Binary data: `aead_seal_bytes(key, nonce, plaintext, aad, algorithm=...)` and `aead_open_bytes(key, nonce, sealed, aad, algorithm=...)` take and return `Buffer`s (`nox.buffer`), so keys, nonces and plaintext need no hex and the plaintext may hold any byte, NUL included. The seal is the same `ciphertext || tag` as the `str` functions produce, so the two families open each other's output. The known-answer tests are RFC 8439 §2.8.2 (ChaCha20-Poly1305) and McGrew–Viega test case 16 (AES-256-GCM). ## Notes - `nox.crypto` offers primitives, not protocols: there is no encryption cipher, signature scheme or TLS here (TLS is [`nox.tls`](https://noxlang.com/docs/stdlib/tls/)); JSON Web Tokens are [`nox.jwt`](https://noxlang.com/docs/stdlib/jwt/). - Strings are hashed as UTF-8 bytes; for binary data build the string from bytes first. --- # nox.ed25519 Ed25519 detached-signature **verification** (RFC 8032), built on the Zig standard library. Signing is done by `noxc sign` / `noxc publish`; this module lets Nox programs (for example the package registry server) check signatures. ```text import nox.ed25519 ``` **Capability:** none (pure computation). | Function | Meaning | |---|---| | `verify(pub_hex, msg, sig_hex) -> bool` | `True` when `sig_hex` (128 hex characters) is a valid signature of `msg` under the public key `pub_hex` (64 hex characters). Any malformed input (wrong length, non-hex, invalid curve point) returns `False`; nothing raises. | | `fingerprint(pub_hex) -> str` | The 32-character key fingerprint used by `noxc sign` (first 16 bytes of the SHA-256 of the raw key, in hex); `""` for invalid input. | ```text pk: str = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a" sg: str = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" print(nox.ed25519.verify(pk, "", sg)) # True (RFC 8032, test vector 1) ``` --- # nox.jwt JSON Web Tokens signed with HMAC-SHA-256 (`HS256`). ```text import nox.jwt from nox.jwt import JwtError ``` **Capability:** none registered (pure Nox over [`nox.crypto`](https://noxlang.com/docs/stdlib/crypto/), [`nox.base64`](https://noxlang.com/docs/stdlib/base64/) and [`nox.json`](https://noxlang.com/docs/stdlib/json/)); not on the freestanding allow-list. ## Functions | Function | Description | |---|---| | `sign(payload_json, secret)` | returns `header.payload.signature` for the JSON text `payload_json`, signed with `secret` | | `verify(token, secret)` | checks the signature (in constant time) and returns the payload JSON text; raises `JwtError` for a malformed token, a wrong algorithm or a bad signature | | `verify_claims(token, secret, now_s, leeway_s)` | `verify`, then enforces the time claims against `now_s` (Unix seconds) with `leeway_s` seconds of clock skew: `exp` (expired when now ≥ exp), `nbf` (not valid yet when now < nbf) and `iat` (issued in the future). Absent claims are skipped; a non-numeric one or a non-object payload raises `JwtError` | | `verify_now(token, secret, leeway_s)` | `verify_claims` with the current wall clock | The token is three Base64url parts separated by dots. `verify` does **not** interpret claims: use `verify_claims`/`verify_now` for `exp`, `nbf` and `iat`; `aud`, `iss` and the rest are yours to enforce — parse the returned payload with [`nox.json`](https://noxlang.com/docs/stdlib/json/). ```nox import nox.jwt from nox.jwt import JwtError tok: str = nox.jwt.sign("{\"sub\":\"ada\"}", "secret") print(tok.count("."), nox.jwt.verify(tok, "secret")) try: nox.jwt.verify(tok, "wrong-secret") except JwtError as e: print("rejected") ``` ```output 2 {"sub":"ada"} rejected ``` ## Notes - Only `HS256` is implemented; tokens that declare another algorithm (including `none`) are rejected. - Use a secret of at least 32 random bytes (`nox.crypto.secure_random_hex(32)`) and keep it out of source control. --- # nox.gzip Compress and decompress gzip data (RFC 1952). ```text import nox.gzip from nox.gzip import GzipError ``` **Capability:** none. ## Functions | Function | Description | |---|---| | `compress(text)` | gzips the UTF-8 bytes of `text`; returns the compressed bytes as a `list[int]` (values 0–255) | | `decompress(data)` | gunzips to a `str`; raises `GzipError` for corrupt or non-gzip input | | `compress_bytes(data)` | gzips a `list[int]` of byte values | | `decompress_bytes(data)` | gunzips to a `list[int]` | Bytes are represented as `list[int]` here. For fixed-size binary work see [`nox.buffer`](https://noxlang.com/docs/stdlib/buffer/). ```nox import nox.gzip from nox.gzip import GzipError c: list[int] = nox.gzip.compress("hello hello hello hello") print(len(c) > 0, nox.gzip.decompress(c)) print(nox.gzip.decompress_bytes(nox.gzip.compress_bytes([1, 2, 3, 4]))) try: nox.gzip.decompress([1, 2, 3]) except GzipError as e: print("not gzip") ``` ```output True hello hello hello hello [1, 2, 3, 4] not gzip ``` ## Notes - `nox.http` decompresses gzip and deflate response bodies automatically; use this module for your own data. - Whole inputs are processed in memory. - On macOS and Linux the codec is [libdeflate](https://github.com/ebiggers/libdeflate) (vendored, MIT); other targets use Zig's `std.compress.flate`. Output is standard gzip either way. --- # nox.tar Read and write tar archives (ustar). ```text import nox.tar from nox.tar import TarEntry, TarError, file_entry, dir_entry, pack, unpack ``` **Capability:** none. Archive contents are `str` values holding raw bytes (binary safe). For a `.tar.gz`, compress the result of `pack` with [`nox.gzip`](https://noxlang.com/docs/stdlib/gzip/). | Function / type | Description | |---|---| | `file_entry(name, data)` | a file entry | | `dir_entry(name)` | a directory entry (a trailing `/` is added if missing) | | `pack(entries)` | the archive bytes as a `str`; `TarError` for an empty name or a name that cannot be split into a 155-byte prefix and a 100-byte name | | `unpack(data)` | a `list[TarEntry]`; `TarError` for a corrupt (bad checksum) or truncated archive | | `TarEntry` | `name`, `data` and `is_dir()` (a name ending in `/`) | `pack` produces exactly what Python's `tarfile` writes in `USTAR_FORMAT` with zero timestamps and ids (mode `0644` for files, `0755` for directories), padded to 10240 bytes. `unpack` also understands GNU long names and PAX headers (`path`, `size`); entries other than regular files and directories (links, devices) are skipped. > **Security.** `unpack` works in memory only. When you write the entries to disk, confine each name with [`nox.path.safe_join`](https://noxlang.com/docs/stdlib/path/#confining-untrusted-paths): archive names may contain `..` or absolute paths. ```nox import nox.strings import nox.tar from nox.tar import TarEntry, file_entry, dir_entry, pack, unpack entries: list[TarEntry] = [dir_entry("docs"), file_entry("docs/hello.txt", "hello tar")] blob: str = pack(entries) print(nox.strings.byte_len(blob)) for e in unpack(blob): print(e.name, e.is_dir(), e.data) ``` ```output 10240 docs/ True docs/hello.txt False hello tar ``` --- # nox.zip Read and write ZIP archives. ```text import nox.zip from nox.zip import ZipEntry, ZipError, file_entry, dir_entry, pack, unpack ``` **Capability:** none. Archive contents are `str` values holding raw bytes (binary safe). Compression is deflate, the same engine as [`nox.gzip`](https://noxlang.com/docs/stdlib/gzip/). | Function / type | Description | |---|---| | `file_entry(name, data)` | a file entry | | `dir_entry(name)` | a directory entry (a trailing `/` is added if missing) | | `pack(entries, compress=True)` | the archive bytes as a `str`; each entry is deflated when that makes it smaller, otherwise stored. `ZipError` for an empty name or more than 65535 entries | | `unpack(data)` | a `list[ZipEntry]` read through the central directory; CRC-32 and sizes are verified. `ZipError` for corrupt, encrypted, ZIP64 or unsupported-method archives | | `ZipEntry` | `name`, `data` and `is_dir()` (a name ending in `/`) | `pack` writes the 1980-01-01 timestamp and Unix permissions (`0644` files, `0755` directories); names that are not ASCII are flagged as UTF-8. Archives written by `pack` are read by Python's `zipfile` and standard `unzip`; archives created by Python's `zipfile` (stored or deflated) are read by `unpack`. Not supported: ZIP64 (archives or entries of 4 GiB and more), encryption and methods other than stored and deflate. Each unpacked entry is limited to 1 GiB. > **Security.** `unpack` works in memory only. When you write the entries to disk, confine each name with [`nox.path.safe_join`](https://noxlang.com/docs/stdlib/path/#confining-untrusted-paths): archive names may contain `..` or absolute paths ("zip slip"). ```nox import nox.strings import nox.zip from nox.zip import ZipEntry, file_entry, dir_entry, pack, unpack entries: list[ZipEntry] = [dir_entry("docs"), file_entry("docs/hello.txt", "hello zip " * 100)] blob: str = pack(entries) for e in unpack(blob): print(e.name, e.is_dir(), nox.strings.byte_len(e.data)) ``` ```output docs/ True 0 docs/hello.txt False 1000 ``` --- # nox.wasm Run a WebAssembly module from Nox, with a persistent instance handle. ```text import nox.wasm from nox.wasm import Instance, WasmError, open, open_with_limits, from_bytes ``` **Capability:** `filesystem` (it reads a module file; `from_bytes` needs no file). It is not `dynamic_code`: nothing is loaded natively, the module only runs inside the sandboxed interpreter, so the module is available on mobile targets too. It is not available on `--target wasm32-*` (the wasm runtime has no embedded engine) or on freestanding targets. The engine is Nox's own pure-Zig validator and interpreter (no JIT, no third-party code, so it behaves the same on every host including iOS and Android). The module runs **sandboxed**: it has no file, network or process access. A module that imports functions needs a `Host` (below); a module that imports host memory, tables or globals cannot be opened. Two limits stop runaway modules: a **fuel** budget (instructions executed; default 2 billion) and a **memory ceiling** (default 4096 pages of 64 KiB = 256 MiB). A trap, an exhausted budget or an invalid module raises `WasmError`. The handle is opaque (Nox never receives the module's raw memory, only bounds-checked copies through `read_*`/`write_*`). An `Instance` works in a `with` block and `close()` is idempotent. ## Opening | Function | Meaning | |---|---| | `open(path)` | read and instantiate a `.wasm` file | | `open_with_limits(path, fuel, max_pages)` | same with an instruction budget and a memory page ceiling (`<= 0` keeps the default) | | `from_bytes(data)` | instantiate from a `list[int]` of byte values (0..255) | | `from_bytes_with_limits(data, fuel, max_pages)` | `from_bytes` with the same limits | | `open_limited(path, limits)` / `from_bytes_limited(data, limits)` | same with a full `Limits` quota set (see below) | | `Host.open_limited(path, limits)` / `Host.open_bytes_limited(data, limits)` | `Host` (WASI / host functions) with a `Limits` quota set | ### Quotas and the strict preset An instance runs inside the interpreter, so a hostile module can only waste the resources you allow it. `Limits` bundles every ceiling; `0` keeps the runtime default. | Field | Default | `strict_limits()` | Meaning | |---|---|---|---| | `fuel` | 2 000 000 000 | 100 000 000 | instruction/branch budget (stops infinite loops) | | `max_pages` | 4096 (256 MiB) | 256 (16 MiB) | linear memory ceiling, 64 KiB pages; `memory.grow` beyond it returns -1 | | `max_depth` | 16384 | 1024 | call depth (stops runaway recursion) | | `max_table` | 10 000 000 | 100 000 | table elements | | `max_stack` | 262144 | 32768 | value-stack slots | | `max_output` | 16 MiB | 1 MiB | captured WASI stdout/stderr bytes; further writes fail with `ENOSPC` | `default_limits()` returns the all-zero set (runtime defaults); `strict_limits()` returns the preset above. Fields are plain attributes, so a preset can be tightened or loosened one field at a time: ```nox import nox.wasm # (module (memory 1) (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) code: list[int] = [0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 5, 3, 1, 0, 1, 7, 13, 2, 3, 97, 100, 100, 0, 0, 3, 109, 101, 109, 2, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11] lim: nox.wasm.Limits = nox.wasm.strict_limits() lim.max_pages = 64 # tighten one field m: nox.wasm.Instance = nox.wasm.from_bytes_limited(code, lim) print(m.call("add", [40, 2])) m.close() ``` Use `strict_limits()` for untrusted modules (plugins, user uploads); the defaults favour compatibility with large trusted modules. ## Calling | Method | Meaning | |---|---| | `call(name, args)` | call an exported function with integer arguments (at most 16); returns the first result (0 if none). `i32` results are sign-extended | | `call_f(name, args)` | call with `float` arguments (`f32`/`f64` parameters take the value; integer parameters truncate); returns the first result as `float` | | `result(i)` / `result_count()` | raw 64-bit pattern of result `i` from the last call (multi-value) | | `exports()` | names of the exported functions | | `signature(name)` | `"i32,i32->i32"`, or `""` when there is no such export | `f64_bits`, `f64_from_bits`, `f32_bits` and `f32_from_bits` convert between a `float` and the raw bit pattern, for modules that pass floats through integer slots. ## Linear memory | Method | Meaning | |---|---| | `memory_size()` | size in bytes (0 without a memory) | | `read_bytes(offset, length)` / `write_bytes(offset, data)` | copy bytes as a `list[int]` | | `read_str(offset, length)` / `write_str(offset, text)` | UTF-8 text (a `str` cannot contain NUL, so a read stops at the first NUL) | | `load(offset, width)` / `store(offset, width, value)` | little-endian unsigned integer of 1, 2, 4 or 8 bytes | Every access is bounds-checked against the module's current memory; an out-of-range access raises `WasmError` and never touches memory outside the module. ```nox import nox.wasm # (module (memory 1) (func (export "add") (param i32 i32) (result i32) local.get 0 local.get 1 i32.add)) code: list[int] = [0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1, 0, 5, 3, 1, 0, 1, 7, 13, 2, 3, 97, 100, 100, 0, 0, 3, 109, 101, 109, 2, 0, 10, 9, 1, 7, 0, 32, 0, 32, 1, 106, 11] with nox.wasm.from_bytes(code) as m: print(m.call("add", [40, 2])) print(m.signature("add")) m.write_str(64, "hello wasm") print(m.read_str(64, 10)) m.store(16, 4, 305419896) print(m.load(17, 2)) ``` ```output 42 i32,i32->i32 hello wasm 13398 ``` ## Host functions (imports) A module's imported functions are answered with Nox functions through a `Host`: ```text h: Host = nox.wasm.host() h.func1("env", "twice", twice) # func0 .. func4 by number of parameters inst: Instance = h.open(path) # or h.open_bytes(data), h.open_with_limits(path, fuel, max_pages) ``` A host function takes up to **4 parameters and returns 1 result, all `int`**: `i32` arrives sign-extended, `i64` as is, `f32`/`f64` as raw bit patterns (convert with `f64_from_bits`/`f32_from_bits`). A lambda works. If the host function raises an exception, execution stops and the call raises `WasmError`; the instance stays usable. A missing import is reported by name before the module runs. The dispatcher exists only for the duration of each call (there are no stored callbacks). ```nox import nox.wasm # (module (import "env" "twice" (func (param i32) (result i32))) (func (export "run") (param i32) (result i32) local.get 0 call 0 i32.const 1 i32.add)) code: list[int] = [0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 1, 127, 1, 127, 2, 13, 1, 3, 101, 110, 118, 5, 116, 119, 105, 99, 101, 0, 0, 3, 2, 1, 0, 7, 7, 1, 3, 114, 117, 110, 0, 1, 10, 11, 1, 9, 0, 32, 0, 16, 0, 65, 1, 106, 11] h: nox.wasm.Host = nox.wasm.host() h.func1("env", "twice", lambda x: x * 2) inst: nox.wasm.Instance = h.open_bytes(code) print(inst.call("run", [20])) inst.close() ``` ```output 41 ``` ## WASI preview1 subset (opt-in) WASI is **off by default**; `h.enable_wasi(args)` turns on a small, capability-based subset: `fd_write` to stdout/stderr (captured in memory and read with `stdout()`/`stderr()`; `h.inherit_output()` also writes to the real streams on Unix), `args_get`/`args_sizes_get`, empty `environ_*`, `proc_exit`, `sched_yield` and inert `fd_*` calls (no file system, no stdin, no network). The clock and randomness are separate capabilities: `h.allow_clock()` enables `clock_time_get` and `h.allow_random()` enables `random_get`; without them the call returns the `EPERM` errno. `proc_exit(code)` stops the module; `inst.run_start()` runs `_start` and returns the exit code (0 on a normal return), and a plain `call` raises `WasmExit` instead. A WASI function that the engine does not implement is reported by name when the module is opened. ## SIMD (v128) The engine runs the fixed-width SIMD proposal (the `0xFD` prefix: loads/stores, lane operations, shuffle/swizzle, integer and float arithmetic, comparisons, narrowing/widening, conversions; everything except the relaxed-SIMD extension). Compilers such as `clang -msimd128` or Rust with `+simd128` emit it, and a module that uses it validates and runs like any other. A `v128` value is 128 bits wide and cannot be represented as a Nox `int`, so it **never crosses the Nox boundary**: an export whose parameters or results include `v128` is reported by `signature()` but `call` raises `WasmError`, a host import with a `v128` signature is rejected when the module is opened, and `v128` globals are not supported (the module is rejected). Pass vectors through linear memory or as an `i64` pair in a thin wrapper export (`(i64 lo, i64 hi)`), which is also how the test-suite drives every instruction. Vectors live in a shadow stack next to the value stack, allocated only for modules that use SIMD, so a module without SIMD pays nothing. Float `min`/`max`/`nearest` follow the scalar rules (NaN, signed zero, ties-to-even); the payload of a produced NaN is unspecified, as the specification allows. ## Threads (atomics, shared memory and wasi-threads) The threads proposal's instruction set runs: shared memories (`(memory 1 2 shared)`), every atomic load, store, read-modify-write and compare-exchange (`i32/i64.atomic.*`, including the 8/16/32-bit forms), `atomic.fence`, `memory.atomic.wait32/wait64` and `memory.atomic.notify`. Atomic accesses must be naturally aligned (a misaligned address traps, as the specification says). **By default an instance runs on one thread**, so the operations are plain, correct reads and writes: `notify` wakes 0 waiters, `wait` returns `1` when the value differs, returns `2` (timed out, without sleeping) when the timeout is `>= 0`, and traps when the timeout is infinite (no other thread could ever wake it). `wait` on a non-shared memory traps. **Real threads (opt-in, since v2.1.155).** `h.enable_threads(max_threads)` on a `Host` (1 to 256) binds the module's `wasi::thread-spawn` import — the [wasi-threads](https://github.com/WebAssembly/wasi-threads) contract that `wasi-libc`'s `pthread_create` uses — and lets the module run up to `max_threads` operating-system threads at once on **one shared linear memory**: ```text h: nox.wasm.Host = nox.wasm.Host([], [], []) h.enable_threads(8) inst: nox.wasm.Instance = h.open("app.wasm") # imports `wasi::thread-spawn` and a shared memory print(inst.call("run", [4])) inst.close() # cancels and joins every thread ``` - `thread-spawn(start_arg)` returns a positive thread id, or a negative number when `max_threads` live threads already exist (or the OS refuses); the new thread runs the module's exported `wasi_thread_start(tid, start_arg)` in a fresh execution state (own stacks, globals and table copy; active data/element segments and `start` are not run again). - Shared-memory atomics are real hardware atomics; `memory.atomic.wait/notify` really block and wake (a waiter polls with short sleeps, so wake-up latency is about 1 ms; it burns no CPU). `memory.grow` on a shared memory grows in place up to the declared maximum (the address range is reserved once, never moved). - **Host functions are callable only from the main execution state**: a thread that calls an imported host function (or WASI) traps. A trap in any thread, or `close()`, cancels all the others (they stop at their next branch/call or blocking `wait`) and `close()` joins them before it returns. - Fuel is counted per thread; `max_pages`, `max_threads` and the instance's own limits apply. A non-shared memory cannot be used with threads. - **Not available on iOS and Android** (and WebAssembly hosts): opening a module with `enable_threads` raises `WasmError`. ## Speed The engine is a plain interpreter (no JIT, by design: the same code runs on iOS and Android). Measured on an Apple M4, ReleaseFast: a recursive `fib(32)` takes about 170 ms (V8's JIT: 9 ms) and a 100-million-iteration `i64` loop about 1.3 s (V8: 0.12 s), roughly 10-20 times slower than a JIT. It is meant for plugins, sandboxed helpers and portable modules, not for heavy numeric kernels; for those compile the code natively or use `extern def`. The fuel budget counts branches and calls. ## Robustness The binary parser, the instantiation step (imports, memory and table setup, `start` function) and the execution of exported functions are fuzzed (`tests/fuzz/wasm_parser_fuzz.zig`), and every single-byte mutation and every prefix of five small valid modules (one SIMD, one atomics) is checked on each test run: no input may crash, hang or leak. Differential tests compare 36 904 numeric vectors and 9 330 SIMD vectors and 5 109 atomics vectors (the SIMD set including `v128` blocks, branches, calls, `select` and recursion) and real compiled programs against Node's WebAssembly engine on every CI run. --- # nox.ffi Closures and lambdas as C callbacks, and `errno` helpers for C error conventions. ```text import nox.ffi from nox.ffi import Callback ``` **Capability:** none. Not available on `wasm32` targets (a wasm module does not link native code). [`@ffi.callback`](https://noxlang.com/docs/language/ffi/#callbacks) lets a C library call back into a top-level `def`. A top-level `def` has no state of its own; when the callback needs to **capture variables** (a lambda, a nested function, a bound method), wrap it in a **`Callback[F]`** handle. `F` is the callback's function type *without* the trailing `userdata` parameter: ```text @ffi.callback("cb", "userdata") extern def reg_set(cb: (int, ptr) -> int, userdata: ptr) -> None from "libreg.o" total: int = 0 cb: Callback[(int) -> int] = Callback[(int) -> int](lambda x: x + total) reg_set(cb) # the handle goes where the callback goes; `userdata` is filled in by the compiler ... cb.close() # when the library will not call it any more ``` | Member | Meaning | |---|---| | `Callback[F](f)` | pins the function value `f` (an ARC reference is held for as long as the handle is open) and prepares what C needs | | `cb.close()` | releases the pinned function; calling it again does nothing. The 16-byte handle block stays allocated until the program ends so that a late call from the library stops the program with a clear message instead of crashing | | `with cb as h:` | closes the handle when the block ends | | `cb.live` | `False` after `close()` | Rules: - The handle must be a **variable or a field** at the call (`reg_set(cb)`), not a temporary expression: the library may keep the callback after the call, so the handle has to outlive it. - The type of `F` must match the callback type exactly (every parameter and the result are `int`, `float`, `bool`, `ptr` or a fixed-width integer). - ARC never frees the handle while C still holds it, so **`close()` is explicit**; a handle that is never closed stays alive until the program ends. - Call the stored callback **only from a thread Nox started** and **never after `close()`** (the pinned function is gone): the library's own OS threads and late "shutdown" callbacks are not supported. - An exception that escapes the callback terminates the program (there is no exception channel through C). ## Callbacks from a library thread `@ffi.callback` runs your function on the thread that called into C. Some libraries (audio, networking, event loops) call the callback from a thread of their own, where Nox code cannot run safely. `EventQueue` solves that: the C library is given a tiny C function that only writes the arguments into a locked queue, and your Nox code reads them in an ordinary task. ```nox-fragment import nox.ffi q: nox.ffi.EventQueue = nox.ffi.EventQueue(4096) lib_on_event(q.callback(1), q.userdata()) # void cb(int level, void *ud, double value): userdata is integer-class argument 1 while q.wait(1000): level: int = q.int_arg(0) # userdata is left out; the integer-class arguments follow in order value: float = q.float_arg(0) # double arguments, in order q.close() # after unregistering the callback in the library ``` | Member | Meaning | |---|---| | `EventQueue(capacity = 1024)` | a queue of `capacity` events | | `callback(ud_index)` | the C function pointer to give the library; `ud_index` (0 to 5) says which integer-class argument is the userdata | | `userdata()` | the queue handle to pass as the callback's userdata | | `poll()` / `wait(timeout_ms)` | fetch the next event (`wait` waits cooperatively in a task); `True` when there is one | | `int_arg(i)` / `float_arg(i)` / `float32_arg(i)` | argument `i` of the fetched event: integer-class (integers, pointers, `bool`, enums), `double`, or `float` (f32) | | `set_return(v)` | the value the callback returns to C (ignored by `void` callbacks) | | `pending()` / `dropped()` | queued events / events discarded because the queue was full (the library's thread is never blocked) | | `close()` | stop accepting events; unregister the callback in the library first | `EventQueue(...)` and `callback(...)` raise `FfiError` when the platform does not support queues (Windows), the queue cannot be allocated, or `ud_index` is outside 0 to 5. Limits: at most 6 integer-class and 4 `double` arguments, no struct arguments by value, macOS and Linux only (the C function relies on the System V / AAPCS64 argument registers). With `noxc bindgen`, list the function under `event_callbacks` in the config so its callback parameter stays a plain `ptr`. ## errno helpers | Function | Meaning | |---|---| | `errno()` | the current C `errno` (0 on Windows) | | `errno_text()` | its `strerror` text (`"errno N"` when 0 or unsupported) | | `is_null(p)` | `True` when the `ptr` is NULL | | `null()` | the NULL `ptr` | | `cstr(p)` | copy a NUL-terminated C string (`char *`) into a Nox `str` (NULL gives `""`) | | `cstr_n(p, n)` | the same for an `n`-byte region | | `alloc(n)` / `release(p)` | `n` zeroed bytes of C memory (output parameters, structs) / free it | [`@ffi.errors(errno=True)`](https://noxlang.com/docs/language/ffi/#errors) uses `errno_text()` for you (it needs `import nox.ffi`); call them directly when you wrap an API yourself. --- # nox.zstd Zstandard **compression and decompression**. ```text import nox.zstd from nox.zstd import ZstdError, compress, decompress ``` **Capability:** none, but the module is not available on freestanding (bare-metal) targets, whose memory budget cannot hold the 8 MiB decoder window. `decompress(data)` decodes one or more concatenated Zstandard frames from a `str` of raw bytes and returns the original bytes as a `str`; it raises `ZstdError` for corrupt or unsupported input. Limits: the decoder window is 8 MiB (streams that need a larger window fail), the output is capped at 1 GiB, dictionaries are not supported, and checksums are not verified. `compress(data, level=3)` compresses a `str` of raw bytes into one Zstandard frame (level 1 to 19, negative levels are faster; out-of-range values are clamped). It uses the embedded C zstd library (BSD-3, `third_party/zstd`), shipped as a separate archive that is linked **only into programs that use `compress`**, so the feature is identical on macOS, Linux and Windows and costs nothing otherwise. Frames carry the content size and a checksum and use a window of at most 8 MiB, so they always decode with `decompress`. (`compress` does not exist on WebAssembly, mobile and bare-metal targets; programs there that only call `decompress` are unaffected.) On iOS and Android a call to `compress` is a compile-time error (the C library is not linked there); `decompress` works. ```nox import nox.base64 import nox.zstd # "hello hello hello hello" compressed by zstd packed: str = nox.base64.decode("KLUv/SAXZQAAMGhlbGxvIAEAmUsR") print(nox.zstd.decompress(packed)) ``` ```output hello hello hello hello ``` --- # nox.lz4 LZ4 **frame** compression: very fast, modest ratio (the same format as the `lz4` command-line tool). ```text import nox.lz4 from nox.lz4 import Lz4Error, compress, decompress, is_supported ``` **Capability:** none. The embedded C library (BSD-2, `third_party/lz4`) is shipped as a separate archive linked only into programs that import this module; it behaves identically on **macOS, Linux and Windows**. The module is not available on WebAssembly, mobile and bare-metal targets (the link fails with a clear message). - `compress(data, level=0)` returns an LZ4 frame for a `str` of raw bytes. `level` 0 is the fast default; 1 to 12 select the slower high-compression (HC) encoder. The frame stores the content size and a content checksum. - `decompress(data)` returns the original bytes; it raises `Lz4Error` for corrupt, truncated or trailing-garbage input and caps the output at 1 GiB. ```nox import nox.lz4 packed: str = nox.lz4.compress("hello hello hello hello") print(nox.lz4.decompress(packed)) ``` ```output hello hello hello hello ``` --- # nox.xxhash [xxHash](https://xxhash.com): extremely fast **non-cryptographic** hashes (cache keys, deduplication, sharding). For anything security-sensitive use `nox.crypto`. ```text import nox.xxhash from nox.xxhash import xxh32, xxh64, xxh3_64, xxh64_hex, xxh3_64_hex, xxh3_128_hex, is_supported ``` **Capability:** none. The embedded C xxHash (BSD-2, `third_party/xxhash`) is shipped as a separate archive linked only into programs that import this module; identical on **macOS, Linux and Windows** (not available on WebAssembly, mobile and bare-metal targets). The 64-bit results are returned as a signed `int` with the same bit pattern (the top bit set shows as negative); the `*_hex` functions show the unsigned value as 16 lower-case hex digits (`xxh3_128_hex`: 32 digits, canonical big-endian order). All functions take an optional `seed`. ```nox import nox.xxhash print(nox.xxhash.xxh64_hex(""), nox.xxhash.xxh3_64_hex("")) ``` ```output ef46db3751d8e999 2d06800538d394c2 ``` --- # nox.yyjson JSON reading and writing on top of [yyjson](https://github.com/ibireme/yyjson) (MIT), the fastest C JSON library. It lives **next to** `nox.json`, which is unchanged: the function names are the same (`parse`, `is_*`, `as_*`, `get`, `array_*`, `object_*`, `dump`, `dump_pretty`), but values are `YyValue` handles into the parsed document instead of `JsonValue` trees. ```text import nox.yyjson from nox.yyjson import YyValue, YyjsonError ``` **Capability:** none. The C library is shipped as a separate archive linked only into programs that import this module; it behaves identically on **macOS, Linux and Windows**. It is not available on WebAssembly, mobile and bare-metal targets (use `nox.json` there). ## Why a separate module The document stays in yyjson's own memory layout: nothing is copied into Nox objects up front, a `YyValue` is created only for the nodes you touch, and the typed shortcuts `get_int`, `get_float`, `get_bool`, `get_str` read a field without creating a node at all. Parsing a 2.9 MB array of 20 000 records and reading three fields of each takes about 1.5 ms (C with yyjson directly: 0.9 ms; `nox.json`: 5.3 ms); parse and write take about 1.3 ms (C: 1.2 ms; `nox.json`: 5.5 ms; CPython: 16 ms). See `benchmarks/yyjson/run.py`. A document is immutable, may be read from several threads, and lives as long as any `YyValue` taken from it (plain ARC; there is nothing to close). ## Functions - `parse(s)`, `parse_relaxed(s)` (comments and trailing commas), `parse_json5(s)`. Invalid input raises `YyjsonError` with the yyjson message and the byte position. - `is_null`, `is_bool`, `is_number`, `is_integer`, `is_string`, `is_array`, `is_object`; `as_bool`, `as_number`, `as_int` (exact int64, or an integral float such as `1e2`; anything else raises), `as_string`, `number_text`. - `get(v, key)` (raises when missing), `get_or_none(v, key)`, `has_key(v, key)`; typed shortcuts `get_int`, `get_float`, `get_bool`, `get_str`; `read_int`, `read_float`, `read_bool`, `read_str`. - `array_len`, `array_get(v, i)` (negative indexes count from the end, out of range raises `IndexError`); `object_len`, `object_key(v, i)`, `object_value(v, i)`. Sequential access is amortized O(1). - `dump(v)` (compact) and `dump_pretty(v, indent)`. - `is_supported()` returns `True` when the yyjson library is linked into the program (always, in a program that imports this module). - Internals you will see in stack traces and signatures: `YyDoc` owns the parsed document (released when the last reference goes), `YyValue` is a value that keeps its `YyDoc` alive; `open_doc(s, mode)` is what `parse*` call; `expect_object`, `expect_array` and `field` are the shared type checks behind `get*`/`array_*`. ## Differences from nox.json Duplicate object keys are accepted (`get` returns the first); there is no nesting depth limit; integers up to uint64 are read exactly (`as_int` raises outside int64); numbers are written in yyjson's shortest round-trip form. A document read with `parse_json5` that contains `Infinity` or `NaN` cannot be dumped. ```nox import nox.yyjson from nox.yyjson import YyValue v: YyValue = nox.yyjson.parse("{\"id\": 7, \"tags\": [\"a\", \"b\"]}") print(nox.yyjson.get_int(v, "id")) print(nox.yyjson.dump(nox.yyjson.get(v, "tags"))) ``` ```output 7 ["a","b"] ``` --- # nox.pcre2 Perl-compatible regular expressions on top of [PCRE2](https://github.com/PCRE2Project/pcre2) (BSD-3), with its JIT compiler. It lives **next to** `nox.regex`, which is unchanged (a Python `re` subset engine written in Zig): the surface is the same (`search`, `match`, `full_match`, `is_match`, `find_all`, `find_matches`, `split`, `replace`, `escape`, `Match`, the same flags, **byte** positions), plus a compiled-pattern class `Pcre2` and the full PCRE feature set: backreferences, lookahead and lookbehind, atomic groups, possessive and lazy quantifiers, Unicode properties (`\p{Lu}`), named groups (`(?P...)`). ```text import nox.pcre2 from nox.pcre2 import Pcre2, Match, Pcre2Error ``` **Capability:** `dynamic_code` (the JIT generates machine code at run time, so `--deny-capability dynamic_code` rejects this module; use `nox.regex` there). The C library is shipped as a separate archive linked only into programs that import this module; it behaves identically on **macOS, Linux and Windows**. It is not available on WebAssembly, mobile and bare-metal targets. ## Compiled patterns and the JIT `compile(pattern, flags=0, jit=True)` returns a `Pcre2`: immutable, usable from several threads, freed by ARC. JIT compilation costs more than a single match, so compile once and reuse; the one-shot module functions compile without JIT. If the JIT is unavailable or fails (hardened systems), matching silently uses the interpreter; results are always the same (`p.is_jit()` tells which is in use). A PCRE2 match limit turns catastrophic backtracking into a `Pcre2Error` instead of a hang. Methods: `search(text, start=0)`, `match(text, start=0)`, `full_match(text)`, `is_match(text)`, `is_full_match(text)`, `find_all(text)`, `find_matches(text)`, `count_matches(text)`, `split(text)`, `replace(repl, text, count=0)` (`\1`, `\g` in `repl`, like `nox.regex.replace`), `group_count()`. Flags: `IGNORECASE`, `MULTILINE`, `DOTALL`, `EXTENDED` (verbose patterns), `BYTES`. By default patterns are UTF-8 with Unicode properties (`\w`, `\d`, `\b` behave like Python 3 `str`), and the subject must be valid UTF-8; `BYTES` matches raw bytes instead. Invalid patterns raise `Pcre2Error` with the PCRE2 message and the byte offset. ## Speed `is_supported()` and `jit_supported()` report whether PCRE2 is linked for the target and whether JIT is available there. Internals you will see in stack traces: `build` (what `compile` calls), `names_of` (named groups), `expand` (replacement templates) and `fail` (error raising). On 1.3 MB of text (Apple M4; `benchmarks/pcre2/run.py`): | Task | `nox.regex` | `nox.pcre2` JIT | C PCRE2 JIT | CPython `re` | |---|---|---|---|---| | count `[0-9]+` (50 000 matches) | 3.4 ms | 0.8 ms | 0.7 ms | 4.4 ms | | count `\b(foo\|bar\|baz)\b` | 17.2 ms | 2.0 ms | 1.9 ms | 12.2 ms | | count `(\w+)@(\w+)\.com` | 28.5 ms | 2.1 ms | 2.0 ms | 27.1 ms | ```nox import nox.pcre2 from nox.pcre2 import Pcre2 p: Pcre2 = nox.pcre2.compile("(?<=\\$)\\d+") print(p.find_all("cost $15 and $200 or 30")) ``` ```output ['15', '200'] ``` --- # nox.brotli Brotli **decompression** (HTTP `Content-Encoding: br`, `.br` files, WOFF2 payloads). It uses the reference C decoder (MIT, `third_party/brotli`, including the built-in 122 KB dictionary). ```text import nox.brotli from nox.brotli import BrotliError, decompress, is_supported ``` **Capability:** none. The C library is shipped as a separate archive linked only into programs that import this module; it behaves identically on **macOS, Linux and Windows**. It is not available on WebAssembly, mobile and bare-metal targets. There is no compressor: use `nox.zstd.compress`, `nox.lz4.compress` or `nox.gzip` to produce data. - `decompress(data, max_output=0)` returns the original bytes of a brotli stream held in a `str`. It raises `BrotliError` for corrupt or truncated input, for bytes after the end of the stream, and when the output would exceed `max_output` bytes (0 means the 1 GiB default; a guard against decompression bombs). Speed: 4 MB of text from a 0.75 MB stream decodes in about 5.7 ms (the C decoder alone: 4.8 ms). ```nox import nox.brotli import nox.base64 data: str = nox.base64.decode("Hy4A+I2Ubt5EVYaWbCBvYU8cYOIA") print(nox.brotli.decompress(data)) ``` ```output hello hello hello hello hello hello hello hello ``` --- # nox.http An HTTP/1.1 client and server. The server is part of the language runtime: connections run on lightweight tasks, the I/O reactor never blocks a worker, and a pool of workers serves many cores. TLS and WebSocket upgrade are built in. ```text import nox.http from nox.http import HttpRequest, HttpResponse, HttpError ``` **Capability:** `network` (unavailable in freestanding profiles). ## Messages ### `HttpRequest` What a server handler receives. | Field | Type | Description | |---|---|---| | `method` | `str` | `"GET"`, `"POST"`, … | | `target` | `str` | the request target exactly as sent, **including the query string** (`/todos?x=1`) | | `body` | `str` | the request body (empty if none) | | `headers` | `dict[str, str]` | request headers, with the **names as the client wrote them** (`Content-Type`, `User-Agent`, …) — look up with the exact spelling, or loop | | `peer_addr` | `str` | the client's `ip:port` (IPv4 `a.b.c.d:port`; IPv6 clients appear as `[::1]:port`) | `req.read_chunk(n=65536) -> str` reads the body of a **streaming request**: over HTTP/2 a request with `content-type: application/grpc` reaches the handler before its body ends (`req.body` is empty) and the body arrives through `read_chunk` (it waits cooperatively for data and returns `""` when the body is complete). For every other request it returns `""` and the body is in `req.body`. `HttpRequest(method, target, body, headers, peer_addr="", conn=0)` can be constructed directly, which is how handlers are unit-tested (`conn` is the server's internal connection handle; leave it `0`). Constructor parameters are frozen; new ones are only ever added with defaults ([Stability](https://noxlang.com/docs/apis/stability/)). ### `HttpResponse` What a handler returns and what the client functions return. | Field | Type | Description | |---|---|---| | `status` | `int` | the HTTP status code | | `body` | `str` | the body | | `headers` | `dict[str, str]` | response headers | `HttpResponse(status, body, headers)`. The server adds `content-length` itself; set `Content-Type` and any other headers you need. ## Client | Function | Description | |---|---| | `get(url, headers)` | issues a GET and returns the `HttpResponse`; `http://` and `https://` are supported | | `post(url, body, headers)` | issues a POST with `body` | | `put(url, body, headers)`, `patch(url, body, headers)` | PUT / PATCH with `body` | | `delete(url, headers)`, `head(url, headers)`, `options(url, headers)` | bodyless requests | | `request(method, url, body, headers, timeout_ms=0, connect_ip="", ca_file="")` | any of GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS; optional timeout; optional pinned address and custom CA (see below) | **Concurrency.** Inside a task (`spawn`) or a `serve` handler, a request does not occupy an operating-system thread: the task is suspended while it waits for the network and the worker runs other tasks, so thousands of requests can be in flight at once on a few threads (about 110 KB of memory per request in flight). Outside a task (plain top-level code) and for `stream`/`stream_upload`, each request still uses a helper thread. Windows behaves like macOS and Linux (since v2.1.147). `headers` are *added* to the request (the client also sends its own `Host`, `User-Agent`, `Accept-Encoding` …). Redirects are **not** followed: a 3xx response is returned as it is, so you decide whether to follow `Location` (and whether to forward `Authorization`). gzip/deflate response bodies are decoded automatically. A non-2xx status is **not** an error: inspect `status`. `HttpError` is raised when the request could not be made at all (connection refused, DNS failure, TLS failure) or when the body arrives incomplete (the connection closed before the announced `Content-Length`). On the WebAssembly targets there are no sockets of the module's own: the network is a capability the host grants (default off). Without it, client calls raise `HttpCapabilityError`, a subclass of `HttpError`, so a plain `except HttpError` also catches it; see [WebAssembly](https://noxlang.com/docs/tools/wasm/#capability-model-and---deny-capability). ```nox import nox.http from nox.http import HttpResponse, HttpError def fetch(url: str) -> str: try: r: HttpResponse = nox.http.get(url, {"Accept": "text/plain"}) if r.status == 200: return r.body return "status " + str(r.status) except HttpError as e: return "unreachable" print(fetch("http://127.0.0.1:1/")) ``` ```output unreachable ``` ### Methods, timeouts and binary bodies `request` accepts exactly `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` and `OPTIONS` (upper case). Any other name raises `HttpError`; it is never turned into a GET. A request body can only be sent with `POST`, `PUT` and `PATCH`. `timeout_ms > 0` limits the DNS lookup, the TCP connect, and then the time spent sending the request and reading the response: when it runs out the connection is aborted and `HttpTimeoutError` (a subclass of `HttpError`) is raised. An unresolvable name or an address that never answers therefore fails after `timeout_ms` instead of waiting for the operating system's own limit (30 s for DNS and 75 s for a TCP connect on macOS, similar on Android). With `timeout_ms = 0` the lookup and the connect are not bounded. **Pinned address (`connect_ip`, SSRF / DNS-rebinding defence).** When `connect_ip` is a non-empty IPv4/IPv6 literal, the host name in the URL is **not resolved**: the connection goes to that address. The TLS server name (SNI) and certificate/host-name verification still use the **original** host name, so the usual flow is `ips = nox.dns.resolve(host)` → check every address against your policy → `request(..., connect_ip=ips[0])`, with no window for the name to resolve differently a second time. A pinned request does not use the connection pool, HTTP/3 or `HTTP_PROXY`/`HTTPS_PROXY`, and it does not follow redirects (the caller re-resolves and re-validates the new location). A malformed `connect_ip` raises `HttpError`; it never falls back to name resolution. **Custom CA (`ca_file`).** A path to a PEM file: the HTTPS server certificate is then verified against **only** the CAs in that file instead of the system store (a private or corporate CA, a local TLS test server). Verification is never switched off, so a self-signed server whose certificate is not in the file is still rejected; a missing or unreadable file fails the request. Relative paths are resolved against the working directory. Like `connect_ip`, it bypasses the connection pool and HTTP/3. It also works together with `connect_ip`. Names resolve with the system resolver for both IPv4 and IPv6 (the system's address order is tried in turn, so a dead IPv6 route falls back to IPv4), and IPv6 literals such as `http://[::1]:8080/` work on every platform. `nox.tls.connect`, `nox.websocket.connect` and `nox.smtp.connect` bound DNS and connect at 30 seconds. A response body may be binary. `resp.body` keeps every byte (including `\x00` and bytes that are not valid UTF-8); `nox.bytes.from_str(resp.body)` copies them into a `Buffer`. ```text r: HttpResponse = nox.http.request("PUT", "http://127.0.0.1:8080/items/1", "{\"n\": 2}", {"Content-Type": "application/json"}, 5000) png: Buffer = nox.bytes.from_str(nox.http.get("http://127.0.0.1:8080/logo.png", {}).body) ``` ### Connection pooling Outgoing requests share a process-wide pool of idle connections. When a request finishes, its connection goes back to the pool and the next request to the same scheme, host and port (from any task or worker) reuses it, so repeated calls to one API skip the TCP connect and, for `https`, the TLS handshake. Against a real HTTPS API this made back-to-back requests about 4× faster (336 ms → 82 ms each). Nothing changes in how you call the client. | Call | Meaning | |---|---| | `nox.http.client_pool(max_idle, idle_timeout_ms=...)` | the most idle connections kept (default `32`, at most `1024`); `0` turns pooling off: idle connections close at once and every request opens and closes its own. `idle_timeout_ms` is how long a connection may sit idle in the pool (default `90000`; `0` = no limit; leave it out to keep the current value) | | `nox.http.client_idle_connections()` | how many idle connections the pool holds right now | ```nox import nox.http print(nox.http.client_idle_connections()) nox.http.client_pool(0) nox.http.client_pool(32) print(nox.http.client_idle_connections()) ``` ```output 0 0 ``` #### A pool of your own: `nox.http.Pool` `client_pool` configures the one pool the whole process shares. When different callers must not share connections (separate tenants, credentials or proxies), give each its own pool: | Call | Meaning | |---|---| | `nox.http.new_pool(max_idle=32, idle_timeout_ms=90000) -> Pool` | an independent pool; its connections are never shared with the process-wide pool or with another `Pool` | | `pool.request(method, url, body, headers, timeout_ms=0)`, `pool.get(url, headers, timeout_ms=0)`, `pool.post(url, body, headers, timeout_ms=0)` | like `nox.http.request`, through this pool | | `pool.idle_connections()` | idle connections this pool holds right now | | `pool.close()` | closes the idle connections now and the in-flight ones when they finish; a request on a closed `Pool` raises `HttpError`. A `Pool` that is dropped closes itself | `max_idle` is at most `1024` (`0` keeps nothing). The idle lifetime is applied at each request and at `close` (there is no background thread for a custom pool). Requests with `connect_ip` or `ca_file` never use a pool, so `Pool.request` has neither parameter; HTTP/3 is not used with a `Pool`. ```nox import nox.http p: nox.http.Pool = nox.http.new_pool(8, 30000) print(p.idle_connections()) p.close() ``` ```output 0 ``` How stale connections are handled — a server may close an idle connection at any time: - Before a request, the pool checks the idle connection it is about to reuse; one the server has already closed is discarded and a fresh connection is opened. You never see an error for this. - If the connection dies in the instant between that check and the request, an **idempotent** request (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`, `TRACE`) that failed before any response arrived is retried **once** on a fresh connection. `POST` and `PATCH` are never retried automatically, because the server may already have acted on them; such a request fails with `HttpError` and your code decides. - Only responses that were read completely return their connection to the pool; a timeout, a truncated body or a `Connection: close` response closes it. A request with `timeout_ms` is cancelled by closing its connection, which is never reused. - Idle connections are closed after `idle_timeout_ms` (90 s by default, measured from when the pool first sees them idle, to within a fraction of a second), when the server closes them, when the pool is full (the oldest go first) or when `client_pool` shrinks the pool. A small background thread does the sweeping and exits on its own once the pool has been empty for a few seconds. Streaming calls (`nox.http.stream`, `stream_upload`) open their own connections and do not use the pool. - HTTPS certificate checks use the current time, refreshed every ten minutes. ### Proxies The client honours `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` (and the lower-case spellings), plus `NO_PROXY`. They are read when the first request is made; changing them later has no effect. - **`http://` targets** go through the proxy in the standard forward-proxy form (`GET http://host/path`). - **`https://` targets** are tunnelled with `CONNECT host:443`; TLS to the *target* (server name, certificate check) then runs inside the tunnel, so the proxy sees only encrypted bytes. If the proxy refuses the tunnel the request **fails**; it is never retried as a plain-text request to the proxy. Tunnelled connections are pooled like direct ones. The proxy URL itself must be `http://` (a TLS connection to the proxy is not supported; such a request fails rather than bypassing the proxy). - **`NO_PROXY`** is a comma-separated list: `*` for everything, `example.com` for the host and its subdomains, `.example.com` for subdomains only; a `:port` suffix is ignored and IP ranges (CIDR) are not understood (an exact IP matches). Matching hosts connect directly. - `user:password@` in the proxy URL is sent as `Proxy-Authorization: Basic`. On Windows they are read the same way (since v2.1.147). ### Streaming large bodies `get`, `post` and `request` keep the whole response body in memory. For large downloads and uploads use a stream: the body moves in chunks, memory use is bounded by the chunk size, and reading is pull-based (the network is read only when you ask for the next chunk, so a slow consumer applies back-pressure to the server). | Function / method | Description | |---|---| | `stream(method, url, headers, body="", timeout_ms=0)` | sends the request, waits for the response head and returns an `HttpStream` whose `status` and `headers` are set; `body` (optional, POST/PUT/PATCH only) is sent from memory | | `stream_upload(method, url, headers, content_length=-1, timeout_ms=0)` | opens a streamed **request** body (POST/PUT/PATCH): `content_length >= 0` sends a fixed `Content-Length` (you must write exactly that many bytes), `-1` uses chunked transfer encoding | | `s.read_chunk(n)` | up to `n` bytes of the response body as a `str`; returns as soon as at least one byte is available, `""` at the end of the body | | `s.write(chunk)` | sends one piece of an uploaded body | | `s.finish()` | ends the upload and reads the response head; afterwards `s.status`/`s.headers` are set and the response body is read with `read_chunk` | | `s.close()` | closes the connection (calling it twice is harmless) | ```text from nox.http import HttpStream with nox.http.stream("GET", "https://example.com/big.iso", {}) as s: if s.status == 200: while True: chunk: str = s.read_chunk(65536) if len(chunk) == 0: # end of the body break ... # write it somewhere, hash it, … up: HttpStream = nox.http.stream_upload("PUT", "https://example.com/data", {}, 11) up.write("hello ") up.write("world") up.finish() print(up.status, up.read_chunk(100)) up.close() ``` To move a body straight to or from a file, see [`nox.transfer`](https://noxlang.com/docs/stdlib/transfer/) (`download_to_file`, `upload_file`). Details: - A chunk is a `str` carrying **raw bytes** (binary data, `\x00` and invalid UTF-8 included; see [`nox.bytes`](https://noxlang.com/docs/stdlib/bytes/)); it can end in the middle of a multi-byte UTF-8 character and `len(chunk)` counts code points, so use `nox.strings.byte_len`. - The body is decoded according to `Content-Encoding` (gzip/deflate) as it is read. - A server that closes the connection before sending the whole `Content-Length` / chunked body makes `read_chunk` raise `HttpError`; a truncated body is never reported as a complete one. (`get`/`post`/`request` apply the same check.) - `timeout_ms > 0` is an **idle** timeout per operation (waiting for the response head, each `read_chunk`, each `write`), not a limit on the whole transfer; when it runs out the connection is aborted and `HttpTimeoutError` is raised. After any failure the stream is closed and further calls raise `HttpError`. - An `HttpStream` owns a network connection and a helper thread and is **not** closed automatically: use `with` or call `close()`. - Redirects are not followed, as for `request`. Streams can be read from lightweight tasks: waiting suspends only the calling task. ## Server The `serve` family are language-level entry points: the handler must be a plain function name (or, for `serve` and `serve_fd`, a closure of type `(HttpRequest) -> HttpResponse`) and **cannot be `async`** — each connection already runs on its own task. They block forever (or until `max_connections` have been served, when that optional argument is given). | Call | Description | |---|---| | `serve(port, handle[, max_connections])` | one listener, runs on the calling worker; handler may be a name or a closure | | `serve_fd(fd, handle[, max_connections])` | serve on an already-listening socket from `listen(port)` | | `serve_multicore(port, handle, num_threads[, max_connections])` | `num_threads` workers share the listening socket; `handle` must be a function **name**: either the handler itself or a **factory** (a function with no parameters that returns the handler closure), which every worker calls once in its own runtime to build its own state; `max_connections` must be an integer literal | | `serve_tls(port, handle, cert_path, key_path[, max_connections])` | HTTPS using PEM certificate and key files | | `serve_ws(port, handle, ws_handle[, max_connections])` | HTTP plus WebSocket upgrade; `ws_handle(conn: WebSocketServerConn) -> None` runs for upgraded connections | | `serve_ws_tls(port, handle, ws_handle, cert_path, key_path[, max_connections])` | WebSocket over TLS | | `serve_fd_tls`, `serve_fd_ws`, `serve_fd_ws_tls` | the `_fd` forms of the above | | `serve_multicore_tls`, `serve_multicore_ws`, `serve_multicore_ws_tls` | the multi-worker forms (`num_threads` follows `handle`) | | `listen(port)` | opens a listening socket and returns its descriptor; raises `HttpError` on failure | | `listen_v6(port, v6_only)` | an IPv6 (dual-stack unless `v6_only`) listening socket | ```nox import nox.http from nox.http import HttpRequest, HttpResponse def handle(req: HttpRequest) -> HttpResponse: return HttpResponse(200, req.method + " " + req.target + "\n", {"Content-Type": "text/plain"}) nox.http.serve(8080, handle) ``` A handler is an ordinary function: test it by calling it with a hand-built request. ```nox from nox.http import HttpRequest, HttpResponse def handle(req: HttpRequest) -> HttpResponse: return HttpResponse(200, req.method + " " + req.target, {"Content-Type": "text/plain"}) resp: HttpResponse = handle(HttpRequest("GET", "/hi?x=1", "", {}, "10.0.0.1:5555")) print(resp.status, resp.body) ``` ```output 200 GET /hi?x=1 ``` ### Several headers with the same name `HttpResponse.headers` is a `dict[str, str]`, so a name appears once. To send several lines with the same name (`Set-Cookie`, `Link`, `Vary`), join the values with `nox.http.multi`; the server writes each one as its own header line: ```text h: dict[str, str] = {} h["Set-Cookie"] = nox.http.multi(["session=abc; Path=/; HttpOnly", "theme=dark; Path=/"]) ``` On the request side, a header the client sent more than once arrives in `req.headers` as one entry with the values joined by `, ` (by `; ` for `Cookie`), as RFC 9110 describes. ### Streaming responses A handler normally returns one `HttpResponse`. To send a body over time — server-sent events, a long export, a progress feed — start a stream from the request. The status line and headers go out **immediately**, then every `send` reaches the client at once (chunked transfer encoding). The handler keeps its signature and ends with `return stream.end()`. | Call | Meaning | |---|---| | `req.stream(status, headers)` | start a streaming response; raises `HttpError` if it cannot (already started, status outside 200–599 or 204/304, invalid header) | | `req.sse()` | `stream(200, ...)` with `Content-Type: text/event-stream`, `Cache-Control: no-cache` and `X-Accel-Buffering: no` (stops reverse proxies from buffering) | | `stream.send(chunk)` | write a raw chunk; `False` once the client has gone or the stream has ended | | `stream.event(data, event="", id="")` | one SSE event; a multi-line `data` becomes one `data:` field per line; `event` and `id` have newlines removed | | `stream.comment(text="")` | an SSE comment line (`: text`): invisible to the client, keeps the connection alive and detects a broken one | | `stream.retry(ms)` | suggest the client's reconnect delay | | `stream.is_open()` | `False` after a write failed, after `end()`, or while the server is shutting down | | `stream.sleep_ms(ms)` | wait; cooperative (other connections keep running, also on the QBE backend) and returns early when the server shuts down. Use it instead of `nox.time.sleep_ms` in stream loops | | `stream.trailers(headers)` | set the response trailers (`grpc-status`, a checksum, ...): sent after the body, before `end()`; returns `False` if the stream already ended or the client speaks HTTP/1.0 | | `stream.end()` | finish the body and return the placeholder response the handler must return (its contents are ignored) | ```nox from nox.http import HttpRequest, HttpResponse, ResponseStream def handle(req: HttpRequest) -> HttpResponse: s: ResponseStream = req.sse() n: int = 0 while s.is_open() and n < 3: if not s.event("tick " + str(n), "tick", str(n)): break n = n + 1 s.sleep_ms(1000) return s.end() # A request built by hand has no connection: the stream collects what was sent, which is how handlers are unit-tested. test_req: HttpRequest = HttpRequest("GET", "/events", "", {}) s2: ResponseStream = test_req.sse() s2.event("hello", "greeting") s2.comment("ping") print(len(s2.sent)) print(s2.sent[0] == "event: greeting\ndata: hello\n\n") print(s2.sent[1] == ": ping\n\n") ``` ```output 2 True True ``` ### Trailers Trailing headers travel after the body: as a final `HEADERS` frame in HTTP/2, after the last chunk in chunked HTTP/1.1. Set them with `stream.trailers({...})` before `stream.end()`. For requests, `req.trailer(name)` returns a trailer sent after the body (chunked HTTP/1.1 or HTTP/2), or `""`; repeated values are joined with `, `. Trailers are only known once the request body has been read, which is when your handler runs. ```nox from nox.http import HttpRequest, ResponseStream req: HttpRequest = HttpRequest("GET", "/", "", {}) s: ResponseStream = req.stream(200, {}) s.send("body") print(s.trailers({"X-Checksum": "abc"})) print(s.sent_trailers["X-Checksum"]) s.end() print(s.trailers({"late": "x"})) print(req.trailer("X-Sum") == "") ``` ```output True abc False True ``` Things to know: - On HTTP/1.1 the connection **closes** after a stream (`Connection: close`); the next request opens a new one. The handler's return value is ignored, and an exception after the stream has started just ends it (the status line is already sent, so no `500` is possible). - A client that disconnects is noticed at the **next write**: `send`/`event`/`comment` return `False`. In a quiet stream send a `comment` every few seconds; it doubles as a heartbeat for proxies. - On `SIGTERM`/`SIGINT` or `nox.http.shutdown()`, `is_open()` turns `False` and `sleep_ms` returns, so a loop written as above ends by itself and the graceful shutdown completes; otherwise the server waits `drain_timeout_ms` and then closes the stream. - Each open stream holds one connection and one fiber. On the default backend streams are spread over the worker threads like any other connection ([Choosing a `serve` form](#choosing-a-serve-form)); the QBE backend serves all of them from one thread, so wait with `stream.sleep_ms`, never with a blocking call. - Behind a reverse proxy, keep `X-Accel-Buffering: no` (set by `sse()`) and make sure the proxy does not enforce a short read timeout shorter than your heartbeat interval. ### Configuration and graceful shutdown ```text nox.http.configure(max_body_bytes=0, max_header_bytes=0, read_timeout_ms=0, max_connections=0, drain_timeout_ms=0, ip_family=0) nox.http.shutdown() ``` `configure` sets process-wide server limits and must be called **before** `serve*` (an argument of `0` keeps the default). It applies to every worker. | Argument | Default | Effect | |---|---|---| | `max_body_bytes` | 10 MiB | a larger request body is answered with `413` | | `max_header_bytes` | 16 KiB (4 KiB – 1 MiB) | the request line plus all headers must fit; otherwise `431`. Browsers' cookies are the usual reason to raise it | | `read_timeout_ms` | 30000 | longest silence while waiting for a request or its body; the connection is then closed | | `max_connections` | 4096 | connections open at once; further ones get a `503 Service Unavailable` (`Retry-After: 1`) and are closed until some close | | `drain_timeout_ms` | 10000 | how long a graceful shutdown waits for requests that are still being handled | | `ip_family` | 0 | listening family of `serve_multicore*`: `0` IPv4, `1` IPv6 dual-stack (`::`, IPv4 clients still connect), `2` IPv6 only (on Windows the workers share one listening socket) | | `bind_address` | `""` | listen on **one** interface: an IPv4 or IPv6 literal (`"127.0.0.1"`, `"::1"`). Empty = all interfaces (`0.0.0.0`). An invalid value raises `HttpError` and never falls back to all interfaces; an IPv4 address combined with `ip_family` IPv6 makes the listener fail to start instead of widening it. The HTTP/3 UDP listener binds the same address. Call it before `serve*`/`listen*`; `nox.http.clear_bind_address()` goes back to all interfaces | **Graceful shutdown.** `SIGTERM` or `SIGINT` — on Windows Ctrl+C, Ctrl+Break and console close/logoff/shutdown events — (and `nox.http.shutdown()`, which you may call from a handler) stops the server cleanly: new connections are no longer accepted, requests that are already being handled finish and are answered with `Connection: close`, idle keep-alive connections are closed, and **`serve*` returns** — so the code after it (closing a database, flushing logs) runs and the program exits normally. A second signal exits immediately. After `drain_timeout_ms` the server stops waiting and also returns. On Windows only `nox.http.shutdown()` is available (there is no signal handler). A WebSocket connection already upgraded is not closed by a shutdown: close it from its handler, or rely on `drain_timeout_ms`. Malformed or hostile requests no longer drop the connection silently: `400` (bad request line or header, conflicting `Content-Length`/`Transfer-Encoding`, `Host` missing in HTTP/1.1), `413`, `431`, `501` (a `Transfer-Encoding` other than `chunked`). A handler that raises an uncaught exception is answered with `500`, the exception class and line are written to standard error, and the server keeps serving. ### Choosing a `serve` form - **`serve`** — one listening socket; simplest. On the QBE backend one thread handles every request and module-level state is shared. On the default LLVM backend the connection fibers can be picked up by any worker thread, and **each worker has its own copy of the module's variables** — build everything the handler needs in a variable initialiser (`router: Router = build_router()`, `db: Connection = open_db()`); `router.get(...)` calls directly after the router's declaration also run per worker, other statements placed after the last variable do not ([Modules](https://noxlang.com/docs/language/modules/#module-level-state-and-the-multi-core-runtime)). Keep data that must be shared in a database, `nox.atomic` or `nox.sharedmem`. - **`serve_multicore`** — scales across CPU cores. Each worker has its own copy of module-level state, so keep shared state in a database or in `nox.atomic` (`AtomicInt`, `AtomicBool`, and `AtomicRef` for a shared immutable snapshot) / `nox.sharedmem`. To give each worker its own application object, pass a **factory** instead of a handler: ```text def make_handler() -> (HttpRequest) -> HttpResponse: app: App = App() # built once per worker, inside that worker def handle(req: HttpRequest) -> HttpResponse: return app.dispatch(req) return handle nox.http.serve_multicore(8080, make_handler, 4) ``` A closure *value* from the main runtime is still rejected, because the workers use separate runtimes; the factory runs inside each worker, so its closure belongs to that worker. The `_tls`, `_ws` and `_ws_tls` forms accept a factory too. **How connections reach the workers.** On Linux every worker owns a `SO_REUSEPORT` listening socket and the kernel spreads new connections across them. On macOS (BSD) and Windows `SO_REUSEPORT` does **not** balance load, so the workers share **one** listening socket instead and take connections from it in turn. A keep-alive connection stays on the worker that accepted it. More workers help when handlers cost real CPU or wait on I/O; a handler that does almost nothing (a ping answered in a few microseconds) is limited by the accept path and the network stack, and one worker may already be the fastest configuration. Measure with your real handler (`wrk -t4 -c40`), not with an empty route. - **`_tls`** — pass paths to a PEM certificate chain and private key; clients that offer `h2` get [HTTP/2](#http2). Behind a reverse proxy that terminates TLS, plain `serve` is usually what you want. - **`_ws`** — use when the same port serves normal requests and WebSockets; see [`nox.websocket`](https://noxlang.com/docs/stdlib/websocket/). ### HTTP/2 The server speaks HTTP/2 as well as HTTP/1.1, with no change to your handler: the same `HttpRequest` goes in and the same `HttpResponse` comes out. - **Over TLS** (`serve_tls`, `serve_ws_tls`, ...) the protocol is negotiated with ALPN: a client that offers `h2` gets HTTP/2, every other client gets HTTP/1.1. - **Over plain TCP** a client that starts with the HTTP/2 connection preface ("prior knowledge", `curl --http2-prior-knowledge`, or a reverse proxy speaking cleartext HTTP/2 to its upstream) gets HTTP/2; ordinary HTTP/1.1 clients are unaffected. - **Multiplexing:** every request on a connection runs your handler on its own task, so one browser connection can have up to 100 requests in flight, slow ones do not hold up fast ones, and a long-lived `req.sse()` stream shares the connection with ordinary requests. Streaming responses ([Streaming responses](#streaming-responses)) work unchanged; unlike HTTP/1.1, only the stream ends, not the connection. - **Flow control** is handled for you: uploads and downloads are paced by the peer's windows (1 MiB per request and 4 MiB per connection on the receiving side), so a slow client cannot make the server buffer a whole response. What differs from HTTP/1.1, as your handler sees it: | | | |---|---| | Request header names | normalised to `Title-Case` (`content-type` arrives as `Content-Type`), so `req.headers["Content-Type"]` works for every client; `Host` is filled from `:authority` | | Response header names | sent in lower case, as the protocol requires; `Connection`, `Keep-Alive`, `Transfer-Encoding` and `Upgrade` response headers are dropped (they do not exist in HTTP/2) | | `Content-Length` | added for you when the handler does not set one | | WebSocket | works over HTTP/2 too ([RFC 8441](https://www.rfc-editor.org/rfc/rfc8441)) on `serve_ws*` servers: the server announces `SETTINGS_ENABLE_CONNECT_PROTOCOL`, and an extended `CONNECT` with `:protocol: websocket` runs your `ws_handle` on the stream; clients that use an HTTP/1.1 upgrade are served as before | | Trailers, `Expect: 100-continue` | supported: see [trailers](#trailers) below; the `100` interim response is sent for you | | Not supported (by design) | server push and the RFC 7540 priority tree: both are deprecated by RFC 9113 and gone from browsers; priority signals are accepted and ignored, which the protocol allows | Limits and protection: 100 concurrent requests per connection (further ones are refused and retried by the client), `max_body_bytes` and `max_header_bytes` apply as in HTTP/1.1, an incomplete request is cut after `read_timeout_ms`, an idle connection is closed after two minutes, and floods of control frames (`SETTINGS`, `PING`, resets — the "rapid reset" attack) end the connection with `ENHANCE_YOUR_CALM`. A request that was reset by the client keeps its slot until your handler returns, so resets cannot be used to start unbounded work. On `SIGTERM` or `nox.http.shutdown()` each HTTP/2 connection is sent `GOAWAY`, requests already running finish, and the connection closes ([Configuration and graceful shutdown](#configuration-and-graceful-shutdown)); a stream loop that checks `stream.is_open()` ends by itself. `nox.http.set_http2(False)` turns HTTP/2 off (TLS then offers only `http/1.1` and cleartext HTTP/2 is not detected); `True` turns it back on. It applies to connections accepted afterwards. On Windows, HTTP/2 works both as cleartext (h2c, since v2.1.143) and over TLS with ALPN (since v2.1.145; it needs OpenSSL's `libssl-3-x64.dll`/`libcrypto-3-x64.dll`). ```nox import nox.http nox.http.set_http2(False) nox.http.set_http2(True) print("http2 configurable") ``` ```output http2 configurable ``` Try it with `curl --http2 -k https://localhost:8443/` (TLS) or `curl --http2-prior-knowledge http://localhost:8080/` (cleartext); `curl -w '%{http_version}'` prints `2`. ### HTTP/3 (QUIC) `nox.http.set_http3(True)` turns HTTP/3 on in both directions. It is off by default and must be called before the servers or requests it should affect. **Server.** A TLS server (`serve_tls`, `serve_ws_tls`... started after the call) also listens on the **same port number over UDP** (IPv6 dual-stack, falling back to IPv4) and answers [HTTP/3](https://www.rfc-editor.org/rfc/rfc9114) requests with the same handler. HTTP/1.1 and HTTP/2 responses of that server carry `alt-svc: h3=":"; ma=86400` (unless your handler sets its own `alt-svc`), which is how browsers and the Nox client learn that HTTP/3 is available. Everything a handler can do on HTTP/2 works here too: buffered responses, streaming responses with `req.stream(...)` and `trailers(...)` (and Server-Sent Events), request `trailer(...)`, `HEAD`. A slow reader slows your `send` calls down instead of filling memory. On `SIGTERM` or `nox.http.shutdown()` the server sends `GOAWAY`, lets running requests finish (up to the drain timeout) and closes connections with `H3_NO_ERROR`; protocol violations close the connection with the matching HTTP/3 error code. QPACK dynamic table: the server accepts it from clients (table size 4096), which shrinks repeated headers such as cookies. **Client.** `nox.http.get`, `post`, `request`... keep using HTTP/1.1 or HTTP/2 over TCP at first. When an `https` origin answers with `alt-svc: h3=":"` (same host only; `ma` is honoured up to one day, `clear` forgets it), later requests to that origin go over HTTP/3. If the QUIC connection cannot be established the request silently falls back to TCP (nothing is sent twice); once the request has been sent over QUIC, failures are reported as for any other request. HTTP/3 connections are kept for reuse (up to the `client_pool` size, 60 seconds idle): a stale pooled connection is replaced transparently, and a request that is safe to repeat (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) is retried once on a fresh connection if the pooled one fails before any response byte arrives. IPv4 and IPv6 addresses are tried in resolver order. `Content-Encoding: gzip`/`deflate` is decoded and `accept-encoding: gzip, deflate` is sent unless you set your own, as on TCP. Certificates are checked against the OpenSSL trust store (`SSL_CERT_FILE` / `SSL_CERT_DIR` apply); a proxy (`HTTPS_PROXY`) makes requests use TCP. | | | |---|---| | Requires | OpenSSL 3.5 or newer (loaded at run time, like the TLS server); on macOS the Homebrew `openssl@3` package, on Linux a distribution that ships OpenSSL 3.5+. Without it, or when the UDP port cannot be opened, the server prints one line and keeps serving HTTP/1.1 and HTTP/2; the client simply stays on TCP | | Platforms | macOS, Linux and (since v2.1.146) Windows (needs `libssl-3-x64.dll`/`libcrypto-3-x64.dll` from OpenSSL 3.5+ on the `PATH`); not WebAssembly or freestanding | | Request bodies | buffered up to `max_body_bytes` (`413` beyond it); headers beyond `max_header_bytes` answer `431` | | `req.peer_addr` | empty on HTTP/3: OpenSSL 3.5 has no API that reports the peer address of a QUIC connection | | Not supported, by design | WebSocket and `CONNECT` over HTTP/3 ([RFC 9220](https://www.rfc-editor.org/rfc/rfc9220); no browser uses it), server push (deprecated, as on HTTP/2), 0-RTT (OpenSSL 3.5 QUIC does not offer it), HTTP/3 through proxies (MASQUE) | ```nox import nox.http nox.http.set_http3(True) nox.http.set_http3(False) print("http3 configurable") ``` ```output http3 configurable ``` ### Behaviour - Request bodies and headers are limited to sane sizes; a client that stalls on reading or writing is cut off by a write timeout (2.0 closes the slow-reader denial-of-service hole). - `HEAD`, `Connection: close` and keep-alive are handled by the runtime. A connection serves at most 1000 requests; the 1000th response carries `Connection: close` so clients reconnect cleanly instead of seeing an unexpected reset. - A client that disconnects while the server writes does not stop the process: `SIGPIPE` is ignored by the `serve*` functions and the write simply fails. - Routing is not part of the server: use [`nox.router`](https://noxlang.com/docs/stdlib/router/). ## Notes - Only the `serve*` functions listed above are intrinsics; everything else in the module (`get`, `post`, `listen`, `listen_v6`, `HttpRequest`, `HttpResponse`, `HttpError`) is ordinary Nox code. - For TLS client connections beyond HTTP see [`nox.tls`](https://noxlang.com/docs/stdlib/tls/). --- # nox.transfer Stream HTTP bodies to and from files without holding them in memory. ```text import nox.transfer ``` **Capability:** `network` and `filesystem` (unavailable in freestanding profiles). It is built on [`nox.http`](https://noxlang.com/docs/stdlib/http/)'s streams and [`nox.fs`](https://noxlang.com/docs/stdlib/fs/)'s file handles; use those directly when you need control over the chunks. The security note of `nox.fs` applies to `path`. | Function | Description | |---|---| | `download_to_file(url, path, headers, timeout_ms=0)` | downloads `url` into `path` and returns the HTTP status | | `upload_file(method, url, path, headers, timeout_ms=0)` | uploads the file at `path` as the request body (`POST`, `PUT` or `PATCH`) and returns the `HttpResponse` | Memory use is bounded by a 64 KiB chunk, so the file can be many gigabytes. - **`download_to_file`** writes to `path + ".nox-part"` and renames it over `path` only after a **2xx** response arrived completely. For any other status, or when the transfer fails (connection error, timeout, truncated body), `path` is left untouched, the temporary file is removed, and the status is returned (or `HttpError` / `HttpTimeoutError` raised for a failure). - **`upload_file`** sends a fixed `Content-Length` taken from the file size, reading the file in chunks. The response body is read into memory; for a large response open a stream with `nox.http.stream_upload` yourself. A file that shrinks while it is being sent raises `HttpError`. - `timeout_ms > 0` is the idle timeout per operation described in [`nox.http`](https://noxlang.com/docs/stdlib/http/#streaming-large-bodies). ```text import nox.transfer from nox.http import HttpResponse status: int = nox.transfer.download_to_file("https://example.com/big.iso", "big.iso", {}) if status != 200: print("download failed:", status) r: HttpResponse = nox.transfer.upload_file("PUT", "https://example.com/files/big.iso", "big.iso", {"Content-Type": "application/octet-stream"}) print(r.status) ``` --- # nox.router Path routing and middleware for `nox.http` handlers, written in Nox. A `Router` maps a method and a path pattern to a handler function; `dispatch` turns an `HttpRequest` into an `HttpResponse`. ```text from nox.router import Router, Context ``` **Capability:** none. ## Handlers and `Context` A handler has the type `(Context) -> HttpResponse`. The `Context` gives it everything about the request: | Member | Description | |---|---| | `request` | the underlying `HttpRequest` (`method`, `target`, `body`, `headers`, `peer_addr`) | | `params` | `dict[str, str]` of captured path parameters | | `param(name)` | one path parameter; `KeyError` if the pattern has no such name | | `query` | `dict[str, str]` of the decoded query-string parameters (`?q=a%20b&n=3` → `{'q': 'a b', 'n': '3'}`) | The query string is stripped before the path is matched, so `GET /search/books?q=x` matches the pattern `/search/:kind`. Read typed values with `nox.url.query_int(ctx.query, "n")`, `query_float`, `query_bool` ([`nox.url`](https://noxlang.com/docs/stdlib/url/)). ## Routes | Method | Description | |---|---| | `Router()` | an empty router | | `get(pattern, handler)`, `post(...)`, `put(...)`, `delete(...)` | register a route for that HTTP method | | `add(method, pattern, handler)` | register any method | | `dispatch(req)` | route a request; returns the handler's response, or `404` with body `not found` when nothing matches | **Patterns** are `/`-separated segments. A literal segment must match exactly; a segment starting with `:` captures that part of the path under the given name: `/users/:id/posts/:post`. A pattern matches only paths with the **same number of segments**. Routes are tried in registration order and the first match wins; the method must also match (a path match with the wrong method is a `404`). ```nox import nox.url from nox.http import HttpRequest, HttpResponse from nox.router import Router, Context router: Router = Router() def search(ctx: Context) -> HttpResponse: q: str = "" if "q" in ctx.query: q = ctx.query["q"] return HttpResponse(200, ctx.param("kind") + ":" + q + ":" + str(nox.url.query_int(ctx.query, "n")), {}) router.get("/search/:kind", search) print(router.dispatch(HttpRequest("GET", "/search/books?q=a%20b&n=3", "", {}, "")).body) print(router.dispatch(HttpRequest("GET", "/search/music?n=7", "", {}, "")).body) print(router.dispatch(HttpRequest("GET", "/nope?x=1", "", {}, "")).status) ``` ```output books:a b:3 music::7 404 ``` `Route` is the internal record (`method`, `pattern`, `handler`) a router keeps for each registered route; you normally never construct one. ## Middleware Three hooks, run around the matched handler (they do **not** run for a `404`): | Method | Signature | Description | |---|---|---| | `use_before(mw)` | `(Context) -> HttpResponse \| None` | runs first; returning a response **short-circuits** (the handler and the later hooks are skipped), returning `None` continues | | `use(mw)` | `(Context, (Context) -> HttpResponse) -> HttpResponse` | wraps the handler: call `next(ctx)` to continue and inspect or replace the result. Several `use` calls nest — the first registered is the outermost | | `use_after(mw)` | `(Context, HttpResponse) -> HttpResponse` | transforms the response after the handler | Order of execution: all `use_before` hooks → the `use` chain around the handler → all `use_after` hooks. ```nox from nox.http import HttpRequest, HttpResponse from nox.router import Router, Context router: Router = Router() def ping(ctx: Context) -> HttpResponse: return HttpResponse(200, "pong", {}) def secret(ctx: Context) -> HttpResponse: return HttpResponse(200, "classified", {}) def need_token(ctx: Context) -> HttpResponse | None: if "X-Token" not in ctx.request.headers: return HttpResponse(401, "unauthorized", {}) return None def tag(ctx: Context, nxt: (Context) -> HttpResponse) -> HttpResponse: resp: HttpResponse = nxt(ctx) return HttpResponse(resp.status, resp.body + "!", resp.headers) router.use_before(need_token) router.use(tag) router.get("/ping", ping) router.get("/secret", secret) print(router.dispatch(HttpRequest("GET", "/ping", "", {}, "")).status) authed: HttpRequest = HttpRequest("GET", "/ping", "", {"X-Token": "t"}, "") print(router.dispatch(authed).body) ``` ```output 401 pong! ``` ## Using a router with the server Build the router in a function and assign it to a module variable; the handler calls it: ```nox import nox.http from nox.http import HttpRequest, HttpResponse from nox.router import Router, Context def home(ctx: Context) -> HttpResponse: return HttpResponse(200, "hello", {"Content-Type": "text/plain"}) def build_router() -> Router: r: Router = Router() r.get("/", home) return r router: Router = build_router() def handle(req: HttpRequest) -> HttpResponse: return router.dispatch(req) nox.http.serve(8080, handle) ``` On the default LLVM backend connections run on several worker threads and each worker has its own copy of the module's variables ([Modules](https://noxlang.com/docs/language/modules/#module-level-state-and-the-multi-core-runtime)). The variable's initialiser therefore runs for every worker, and so do the `router.get(...)`-style calls that **directly follow** the declaration (only `def`, `class` and imports may sit between them), so this layout works too: ```nox from nox.http import HttpResponse from nox.router import Router, Context def home(ctx: Context) -> HttpResponse: return HttpResponse(200, "hello", {}) def create_item(ctx: Context) -> HttpResponse: return HttpResponse(201, "created", {}) router: Router = Router() router.get("/", home) router.post("/items", create_item) def count() -> int: return len(router.routes) print(count()) ``` ```output 2 ``` Keep the registrations together right after the declaration. A registration separated from it by any other statement (a `print`, an assignment) runs only on the main worker, and the other workers would answer `404` for those routes. Building the router in a function, as above, is immune to this and is the better choice for larger routers. `nox.reflect.router_from_decorators()` builds a router from `@get`/`@post`/`@put`/`@delete`-decorated functions ([Decorators](https://noxlang.com/docs/language/decorators/)). ## Limits - No wildcard or regular-expression segments, no per-route middleware, no automatic `405`/`OPTIONS` handling; implement those in a `use_before` hook. - Under `serve_multicore` each worker builds its own router (module-level state is per worker), which is what you want for a stateless routing table. --- # nox.web Production building blocks for a [`nox.http`](https://noxlang.com/docs/stdlib/http/) backend, written in Nox: cookies, CORS, a rate limiter, request ids, an access log, security headers and response helpers. They are plain functions and small classes you call from your `serve` handler (or from [`nox.router`](https://noxlang.com/docs/stdlib/router/) middleware) — there is no framework to buy into. ```text import nox.web from nox.web import Cors, RateLimiter ``` **Capability:** none for the module itself; `RateLimiter` and `access_log` read the clock (`nox.time`), `request_id` needs entropy (`nox.uuid`). ## Reference | Name | Description | |---|---| | `header(req, name)` | request header looked up **case-insensitively**; `""` when absent | | `bearer_token(req)` | the token of `Authorization: Bearer `, or `""` | | `parse_cookies(header_value)` | `Cookie` header → `dict[str, str]` (the first of a repeated name wins) | | `cookie(name, value, path="/", max_age=-1, http_only=True, secure=False, same_site="Lax")` | a `Set-Cookie` value. `ValueError` if the name, value or path contains `;`, `,`, a space, CR, LF or NUL, or for `SameSite=None` without `secure` | | `expire_cookie(name, path="/")` | a `Set-Cookie` value that deletes the cookie | | `Cors(allow_origins, allow_methods, allow_headers, max_age, allow_credentials)` | a cross-origin policy; `preflight(req)` answers an `OPTIONS` preflight (`204`, or `403` for a foreign origin) or returns `None`; `apply(req, resp)` adds the CORS headers to a real response | | `client_ip(req)` | the client's IP without the port (`203.0.113.7:51234` → `203.0.113.7`, `[::1]:80` → `::1`). **Use this, not `req.peer_addr`, as the rate-limit key** — the port changes on every connection | | `RateLimiter(limit, window_ms)` | fixed-window counter: `allow(key)` is `False` once `key` has made more than `limit` requests in the window; `too_many()` is the ready-made `429` with `Retry-After` | | `request_id(req)` | the client's `X-Request-Id` when it is safe (≤ 64 characters of letters, digits, `-`, `_`, `.`), else a fresh UUID | | `with_request_id(resp, rid)` | adds `X-Request-Id` to a response | | `access_log(req, resp, started_ms, rid)` | one `nox.log.info` line: `METHOD target status ms id peer` | | `with_security_headers(resp)` | adds `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` unless already set | | `text_response(status, body)`, `json_response(status, body_json)`, `redirect(location, status=302)` | small response constructors (`redirect` rejects CR/LF) | Several cookies in one response: join the `Set-Cookie` values with `nox.http.multi([...])` ([Several headers with the same name](https://noxlang.com/docs/stdlib/http/#several-headers-with-the-same-name)). ## Cookies ```nox import nox.web import nox.http print(nox.web.cookie("sid", "abc123")) print(nox.web.cookie("theme", "dark", "/app", 3600, False, True, "Strict")) print(nox.web.expire_cookie("sid")) jar: dict[str, str] = nox.web.parse_cookies("a=1; b=two; a=ignored") print(jar["a"] + " " + jar["b"]) print(nox.http.multi([nox.web.cookie("a", "1"), nox.web.cookie("b", "2")]).count("\n")) ``` ```output sid=abc123; Path=/; HttpOnly; SameSite=Lax theme=dark; Path=/app; Max-Age=3600; Secure; SameSite=Strict sid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax 1 two 1 ``` ## Putting it together The handler passed to `serve` is an ordinary function, so the pieces compose by calling them in order: id → rate limit → CORS preflight → route → CORS headers → id and security headers → log. ```nox import nox.http import nox.web from nox.http import HttpRequest, HttpResponse from nox.web import Cors, RateLimiter cors: Cors = Cors(["https://app.example"], "GET, POST", "Content-Type", 600, False) limiter: RateLimiter = RateLimiter(100, 60000) def route(req: HttpRequest) -> HttpResponse: if req.target == "/hello": return nox.web.text_response(200, "hello") return nox.web.text_response(404, "not found") def respond(req: HttpRequest) -> HttpResponse: if not limiter.allow(nox.web.client_ip(req)): return limiter.too_many() pre: HttpResponse | None = cors.preflight(req) if pre is not None: return pre return cors.apply(req, route(req)) def handle(req: HttpRequest) -> HttpResponse: rid: str = nox.web.request_id(req) resp: HttpResponse = nox.web.with_security_headers(nox.web.with_request_id(respond(req), rid)) return resp req: HttpRequest = HttpRequest("GET", "/hello", "", {"Origin": "https://app.example", "X-Request-Id": "r-1"}, "10.0.0.1:5000") out: HttpResponse = handle(req) print(out.status) print(out.headers["Access-Control-Allow-Origin"]) print(out.headers["X-Request-Id"]) print(out.headers["X-Frame-Options"]) ``` ```output 200 https://app.example r-1 DENY ``` In a real handler, add `nox.web.access_log(req, resp, started, rid)` before the `return` to write one log line per request (it goes to standard output through [`nox.log`](https://noxlang.com/docs/stdlib/log/)); it is left out here so the example's output stays deterministic. ## Reference application [`examples/todo-backend`](https://github.com/mburakmmm/nox-lang/tree/main/examples/todo-backend) is a complete small backend built from these pieces: registration and login (argon2id + JWT), a per-user todo list in SQLite, a server-sent-events endpoint ([streaming responses](https://noxlang.com/docs/stdlib/http/#streaming-responses)), CORS, rate limiting, request ids, access log, security headers and graceful shutdown on `SIGTERM`. `scripts/todo_backend_smoke.py` builds it and drives it end to end (authorisation isolation between two users, CORS, 429, 8 concurrent clients, clean shutdown) on both backends. ## Notes - **Module state is per worker on the default backend.** With the LLVM backend a `serve` connection may run on any worker thread, and each worker has its own copy of the module's variables. Build everything the handler needs *inside a variable initialiser* (`router: Router = build_router()`, `limiter: RateLimiter = RateLimiter(...)`). Route registrations directly after the router's declaration are replayed per worker too; other statements after the last variable run only on the main worker. Details: [Modules](https://noxlang.com/docs/language/modules/#module-level-state-and-the-multi-core-runtime). - **`serve_multicore`:** module-level state is per worker, so a `RateLimiter`'s counters are per worker (the effective limit is up to `limit` × workers; the same holds for plain `serve` on the LLVM backend). Use a database, [`nox.atomic`](https://noxlang.com/docs/stdlib/atomic/) or [`nox.sharedmem`](https://noxlang.com/docs/stdlib/sharedmem/) for a strict shared limit. - **Memory:** a `RateLimiter` forgets all counters at the end of each window and resets early when it has seen 100000 distinct keys, so it cannot grow without bound. - **CORS:** with `allow_credentials` the policy echoes the request's `Origin` (a `*` would be rejected by browsers). `Vary: Origin` is added whenever the origin is echoed. - Cookie *values* are not encoded for you: percent-encode arbitrary text with [`nox.url.percent_encode`](https://noxlang.com/docs/stdlib/url/) first. --- # nox.websocket WebSocket (RFC 6455) for both directions: a **client** that connects to `ws://` and `wss://` URLs, and the **server-side connection** object handed to a WebSocket handler by `nox.http.serve_ws*`. Messages are text. ```text from nox.websocket import connect, WebSocketClient, WebSocketServerConn, WebSocketError ``` **Capability:** `network`. ## Client | Function / method | Description | |---|---| | `connect(url)` | opens a connection (performing the handshake) and returns a `WebSocketClient`; `wss://` uses TLS. Raises `WebSocketError` if it cannot connect | | `send_text(data)` | sends one text message; returns the number of bytes sent; raises `WebSocketError` on failure | | `recv()` | blocks until the next message and returns it; pings and pongs are handled internally; returns the **empty string** when the connection has closed | | `is_open()` | whether the connection is still open | | `close()` | closes it (idempotent) | Using a client after `close()` raises `WebSocketError`. ```nox from nox.websocket import connect, WebSocketClient, WebSocketError def ask(url: str, question: str) -> str: try: ws: WebSocketClient = connect(url) ws.send_text(question) answer: str = ws.recv() ws.close() return answer except WebSocketError as e: return "no connection" print(ask("ws://127.0.0.1:1/", "hello")) ``` ```output no connection ``` ## Server side Pass a handler of type `(WebSocketServerConn) -> None` to `nox.http.serve_ws` (or the `_tls`, `_fd` and `_multicore` variants — see [`nox.http`](https://noxlang.com/docs/stdlib/http/#server)). It runs once per upgraded connection, on its own task, until it returns. `WebSocketServerConn` has the same four methods as the client: `send_text(data)`, `recv()`, `is_open()` and `close()`. ```nox import nox.http from nox.http import HttpRequest, HttpResponse from nox.websocket import WebSocketServerConn def page(req: HttpRequest) -> HttpResponse: return HttpResponse(200, "use a WebSocket client", {"Content-Type": "text/plain"}) def echo(conn: WebSocketServerConn) -> None: while conn.is_open(): msg: str = conn.recv() if msg == "": return conn.send_text("echo: " + msg) nox.http.serve_ws(8080, page, echo) ``` ## Notes - Operations block the calling task; the runtime keeps other tasks running while one waits. - Only text messages are exposed; binary frames are delivered as text bytes. - An empty message from the peer is indistinguishable from a close in `recv()`; use `is_open()` after an empty result if you need to tell them apart. --- # nox.udp UDP datagram sockets, for telemetry (statsd, syslog), discovery and simple request/response protocols. ```text import nox.udp ``` **Capability:** `network`. POSIX only (macOS, Linux, Android, iOS): on Windows and in WebAssembly `is_supported()` is `False`. ```text import nox.udp from nox.udp import UdpSocket, Datagram, UdpError rx: UdpSocket = nox.udp.bind("127.0.0.1", 0) # port 0: the OS picks one tx: UdpSocket = nox.udp.open() # a send-only socket tx.send_to("127.0.0.1", rx.local_port(), "ping") d: Datagram = rx.recv(2048, 1000) # at most 2048 bytes, 1 s timeout print(d.data, d.host, d.port) rx.send_to(d.host, d.port, "pong") # reply to the sender ``` | Function | Description | |---|---| | `bind(host, port, ipv6=False, reuse=False, broadcast=False)` | a socket bound to `host:port` (`""` = all interfaces, `0` = OS-chosen port) | | `open(ipv6=False, broadcast=False)` | a send-only socket on an OS-chosen port | | `is_supported()` | can UDP be used on this target? | `UdpSocket`: | Member | Description | |---|---| | `local_port()` | the bound port (useful after `bind(…, 0)`) | | `send_to(host, port, data)` | sends `data` (a `str`) as one datagram; returns the byte count | | `send_bytes_to(host, port, data)` | the same for a `list[int]` of byte values | | `recv(max_len=65507, timeout_ms=-1)` | receives one datagram as a `Datagram`; longer datagrams are truncated to `max_len` | | `close()` | closes the socket; calling it twice is harmless | `Datagram` has `data` (`str`), `host` (the sender's numeric address), `port` (the sender's port) and `to_bytes()` (`list[int]`). ## Behaviour - **Fibers.** `recv` inside a task suspends only that task; other tasks keep running. Outside a task it waits with `poll`. `timeout_ms < 0` waits forever, `0` polls. - **Bytes are exact.** A `str` carries every byte, NUL included, so binary payloads (protobuf, gzip output via `nox.bytes.str_from_list`) round-trip unchanged. The limit is 65507 bytes per datagram. - **Errors.** Everything raises `UdpError`; its `kind` is `"timeout"` (see `is_timeout()`), `"closed"` or `"io"`. - **Address family.** It is chosen when the socket is opened (IPv4 by default, `ipv6=True` for a dual-stack IPv6 socket). Sending to a name resolves it with a *blocking* `getaddrinfo`; IP literals and `localhost` resolve immediately. - **UDP is unreliable.** Loss, reordering and duplication are yours to handle. --- # nox.dns Explicit DNS resolution. `nox.http` resolves a host name by itself while connecting, so a program that validates the address first (SSRF protection) would otherwise resolve twice and could be fooled by DNS rebinding. `nox.dns.resolve` makes the lookup a separate step; together with `nox.http.request(..., connect_ip=...)` the flow is **resolve → validate → connect to the validated address**. ```text import nox.dns import nox.http import nox.ip ips: list[str] = nox.dns.resolve("api.example.com", 3000) for ip in ips: if nox.ip.is_global_text(ip): # see nox.ip resp = nox.http.request("GET", "https://api.example.com/", "", {}, 5000, ip) break ``` **Capability:** `network`. | Function | Description | |---|---| | `resolve(host: str, timeout_ms: int = 0, doh_url: str = "") -> list[str]` | the A/AAAA addresses of `host` as text (at most 16, in the operating system's RFC 6724 order); `doh_url` is only used on WASM (see below) | - IP literals (`203.0.113.7`, `[2001:db8::1]`) and `localhost` / `*.localhost` come back without touching the network. - `timeout_ms > 0` bounds the lookup (`DnsTimeoutError`); with `0` it is bounded by a 2-minute cap. An unresolvable name raises `DnsError` (the function never returns an empty list, so a caller cannot treat "failure" as "allowed"). - Inside a fiber only the calling fiber waits. The lookup shares the bounded, single-flight resolver that `nox.http` uses. - `DnsCapabilityError` when the `network` capability is denied; `DnsError` on targets without a resolver (freestanding, and WASM unless a `doh_url` is given). - Address classification (private/loopback/link-local/metadata ranges) is [`nox.ip`](https://noxlang.com/docs/stdlib/ip/); `nox.dns` only resolves. ## DNS on WASM (DNS-over-HTTPS) A browser or WASI module has no system resolver. On `wasm32-freestanding --asyncify` with the host `fetch` capability, pass the URL of a **DoH JSON** resolver (the `application/dns-json` format) as `doh_url`: the lookup is then two `GET` requests (`?name=&type=A` and `&type=AAAA`) through the host's `fetch`. ```text ips: list[str] = nox.dns.resolve("api.example.com", 3000, "https://doh.example/dns-query") ``` - There is **no default resolver**: the host names you look up are sent only to the server you choose. Without `doh_url` the call raises `DnsError` ("not supported on this target"). - IP literals and `localhost` still need no network. A name with characters other than letters, digits, `-`, `_` and `.` is rejected without a request. - `DnsTimeoutError` when the host's `fetch` times out, `DnsCapabilityError` when the host grants no network capability, `DnsError` when neither query returns an address (NXDOMAIN or a malformed answer). One of the two queries returning addresses is a success. - The host's own network policy (`--net-allow`, `--allow-net`) applies to the DoH server like any other `fetch`. The addresses you get are only as trustworthy as that server: validate them with [`nox.ip`](https://noxlang.com/docs/stdlib/ip/) before connecting. --- # nox.ip IPv4/IPv6 address parsing and classification — the "validate" step of a resolve → validate → connect defence against SSRF and DNS rebinding. Pure Nox: no network, no capability. ```nox import nox.ip import nox.dns import nox.http def safe_get(host: str) -> int: for ip in nox.dns.resolve(host, 3000): if nox.ip.is_global_text(ip): resp: nox_http_HttpResponse = nox.http.request("GET", "https://" + host + "/", "", {}, 5000, ip) return resp.status return 0 ``` | Function / method | Description | |---|---| | `parse(text) -> IpAddress` | parses an IPv4 or IPv6 literal (`[::1]` URL form accepted); raises `IpError` otherwise | | `is_valid(text) -> bool` | `parse` succeeds | | `is_global_text(text) -> bool` | valid **and** `is_global()`; an invalid literal is `False` (fail closed) | | `a.version`, `a.octets` | `4` or `6`; 4 or 16 values 0–255 | | `a.text()` | canonical text (IPv6 per RFC 5952, IPv4-mapped as `::ffff:a.b.c.d`) | | `a.is_global()` | publicly routable unicast: none of the categories below | | `a.is_loopback()`, `a.is_private()`, `a.is_link_local()`, `a.is_cgnat()`, `a.is_multicast()`, `a.is_unspecified()` | `127/8` and `::1`; RFC 1918 and `fc00::/7`; `169.254/16` and `fe80::/10`; `100.64/10`; `224/4` and `ff00::/8`; `0.0.0.0` and `::` | | `a.is_metadata()` | well-known cloud metadata endpoints (`169.254.169.254`, `169.254.170.2`, `100.100.100.200`, `192.0.0.192`, `fd00:ec2::254`) | | `a.is_reserved()` | documentation, benchmarking, IETF protocol assignments, `240/4` (including broadcast), `0/8`, `100::/64`, `2001::/23`, `2001:db8::/32`, `2002::/16`, `3fff::/20`, `64:ff9b:1::/48` | | `a.is_ipv4_mapped()`, `a.is_nat64()`, `a.unmap()` | `::ffff:a.b.c.d`; `64:ff9b::/96`; the embedded IPv4 address (or the address itself) | Notes: - `parse` **rejects** ambiguous forms: a leading zero (`010.0.0.1`, octal in some parsers), `0x7f.1` and short forms such as `127.1`, IPv6 zone ids (`fe80::1%eth0`), and a second `::`. - IPv4-mapped (`::ffff:127.0.0.1`) and NAT64 addresses are classified by the IPv4 address they carry, so the common mapped-loopback bypass is `False` for `is_global()`. - `is_global()` treats multicast as not global, which is stricter than Python's `ipaddress`; everything else agrees with it (the golden `ip_classify` is checked against Python on 72 valid and 22 invalid inputs). - Classification is address-based only. It cannot know about your own private networks; combine it with an allow-list of hosts you trust. --- # nox.safehttp An HTTP client that is safe to point at **untrusted URLs** (webhooks, link previews, "fetch this image" features). It refuses to talk to internal addresses and cannot be tricked by DNS rebinding or by a redirect into your network. Pure Nox, built on [`nox.dns`](https://noxlang.com/docs/stdlib/dns/), [`nox.ip`](https://noxlang.com/docs/stdlib/ip/) and `nox.http.request(..., connect_ip=...)`. **Capability:** `network`. ```nox import nox.http import nox.safehttp try: r: nox_http_HttpResponse = nox.safehttp.request("GET", "https://example.com/preview", "", {}, 5000) print(r.status) except nox.safehttp.SafeHttpBlockedError as e: print("refused:", e.message) ``` For every request **and every redirect hop** it: 1. accepts only `http`/`https` URLs without embedded credentials; 2. resolves the host name once (`nox.dns`) — an IP literal is used as is; 3. requires **every** resolved address to be globally routable (`nox.ip` `is_global()`): loopback, private (RFC 1918, `fc00::/7`), link-local, CGNAT, multicast, reserved and cloud-metadata addresses (`169.254.169.254` and friends) block the request, including IPv4-mapped forms such as `::ffff:127.0.0.1`; 4. connects to the **validated address** (`connect_ip`), so the name is never resolved a second time; TLS still verifies the certificate against the original host name. | Call | Description | |---|---| | `request(method, url, body, headers, timeout_ms=10000, max_redirects=5, allow_private=False, allow_hosts="", allow_downgrade=False) -> HttpResponse` | the safe request; raises `SafeHttpBlockedError` (a `SafeHttpError`) when an address is not allowed, `SafeHttpError` for a bad URL, an unresolvable host, too many redirects or no reachable address, `HttpTimeoutError` on a timeout | - Redirects (`301/302/303/307/308`) are followed by hand and each new location is checked like the first request. `303` (and `301`/`302` after a `POST`) become `GET` without a body. When the **origin** (scheme + host + port) changes — even to another port of the same host — `Authorization`, `Cookie` and `Proxy-Authorization` headers are dropped. A redirect from `https` to `http` is refused (`SafeHttpBlockedError`) unless `allow_downgrade=True`. - `allow_hosts` is a comma-separated list of host names or IP literals you **do** want to reach even though they are internal (`"db.internal,127.0.0.1"`); the address check is skipped for those names only, on every hop. - `allow_private=True` switches the address check off (local development and tests only). - It does not use the connection pool, HTTP/3 or `HTTP_PROXY`/`HTTPS_PROXY` (a proxy would resolve the name for you), and it does not read the response body before the headers have been checked — but it does not limit the body size either; set limits in your own code when fetching untrusted content. --- # nox.tls A client TLS stream: connect to a host and port, then read and write text over an encrypted connection. Certificates are verified against the operating system's trust store. ```text from nox.tls import connect, TlsStream, TlsError ``` **Capability:** `network`. ## Functions | Function / method | Description | |---|---| | `connect(host, port, connect_ip="")` | connects and completes the TLS handshake; returns a `TlsStream`; raises `TlsError` on connection or certificate failure. With `connect_ip` (an IPv4/IPv6 literal) the host name is **not resolved**: TCP goes to that address while the server name (SNI) and the certificate are still verified against `host` — the resolve → validate → connect flow of [`nox.dns`](https://noxlang.com/docs/stdlib/dns/) and [`nox.ip`](https://noxlang.com/docs/stdlib/ip/). An invalid literal fails the connection; it never falls back to name resolution | | `write(data)` | sends `data`; returns the number of bytes written; raises `TlsError` on failure | | `read(max_len)` | reads **at most** `max_len` bytes; returns the **empty string** when the peer closed cleanly (not an error — it means "no more data") | | `is_open()` | whether the stream is still usable | | `close()` | closes it (idempotent) | Using a stream after `close()` raises `TlsError`. ```nox from nox.tls import connect, TlsStream, TlsError def head(host: str) -> str: try: s: TlsStream = connect(host, 443) s.write("HEAD / HTTP/1.0\r\nHost: " + host + "\r\n\r\n") first: str = s.read(64) s.close() return first except TlsError as e: return "tls failed" print(head("localhost.invalid")) ``` ```output tls failed ``` ## Notes - Operations are synchronous at the call site; other tasks keep running while one waits. - Server-side TLS is part of [`nox.http`](https://noxlang.com/docs/stdlib/http/) (`serve_tls`), which needs a PEM certificate and key. - For HTTPS requests use [`nox.http.get`](https://noxlang.com/docs/stdlib/http/#client), which uses this machinery internally. --- # nox.smtp An SMTP client for sending plain-text e-mail: connect, optionally upgrade with STARTTLS, authenticate and send. ```text from nox.smtp import connect, send_mail, SmtpClient, SmtpError ``` **Capability:** `network`. ## One call | Function | Description | |---|---| | `send_mail(host, port, use_tls, use_starttls, ehlo_domain, username, password, from_addr, to_addrs, subject, body)` | connects, greets, optionally upgrades, authenticates (when `username` is non-empty), sends one message and disconnects; raises `SmtpError` on any failure | `use_tls` selects implicit TLS (typically port 465); `use_starttls` starts in plain text and upgrades (typically port 587). Pass `False` for both only for trusted local relays. ## `SmtpClient` For finer control: | Function / method | Description | |---|---| | `connect(host, port, use_tls)` | opens the connection and reads the server greeting; returns an `SmtpClient` | | `ehlo(domain)` | introduces the client | | `starttls()` | upgrades the connection to TLS | | `auth_login(username, password)`, `auth_plain(username, password)` | authenticate with `AUTH LOGIN` / `AUTH PLAIN` | | `send(from_addr, to_addrs, subject, body)` | sends one plain-text message to every address in `to_addrs` | | `quit()` | ends the session politely | | `close()` | closes the socket | ```nox from nox.smtp import send_mail, SmtpError def notify(address: str, text: str) -> bool: try: send_mail("smtp.example.com", 587, False, True, "client.example.com", "user", "app-password", "noreply@example.com", [address], "Hello", text) return True except SmtpError as e: return False ``` ## Scope Plain-text bodies only: no MIME multipart, attachments or `Date` header. Only `EHLO` (no `HELO` fallback) and the `AUTH LOGIN` / `AUTH PLAIN` mechanisms are implemented. All methods are synchronous at the call site. > **Credentials.** Do not hard-code passwords; read them from the environment ([`nox.os`](https://noxlang.com/docs/stdlib/os/)) or a secrets store. --- # nox.db The vocabulary shared by every SQL driver: **`Row`** and **`Statement`** classes, and the `DbConnection` protocol that [`nox.sqlite`](https://noxlang.com/docs/stdlib/sqlite/), [`nox.postgres`](https://noxlang.com/docs/stdlib/postgres/) and [`nox.mysql`](https://noxlang.com/docs/stdlib/mysql/) connections all satisfy. Code written against `DbConnection` — such as [`nox.orm`](https://noxlang.com/docs/stdlib/orm/) — works with any of the three. ```text from nox.db import Row, Statement, DbConnection ``` **Capability:** none for the module itself (the drivers carry `filesystem` or `network`). ## `DbConnection` — the common connection interface A structural [protocol](https://noxlang.com/docs/language/protocols-generics/#protocols): any connection with these methods fits, no declaration needed. | Method | Description | |---|---| | `execute(sql)` | runs a statement without parameters and returns the number of affected rows | | `query(sql)` | runs a query and returns its rows as a `list[Row]` | | `prepare(sql)` | prepares a parameterised statement and returns a `Statement` | | `close()` | closes the connection | A function with a `DbConnection` parameter is compiled once for each driver it is called with. ## `Row` One result row. Every column is available through typed getters by **zero-based index**: | Method | Description | |---|---| | `get_str(i)` | the column as text | | `get_int(i)` | the column parsed as an `int` (`ValueError` if it is not a number or is `NULL`) | | `get_float(i)` | the column parsed as a `float` | | `is_null(i)` | whether the column is SQL `NULL` — check this before reading a nullable column | | `column_count()` | the number of columns | | `column_name(i)` | the name of column `i` | Rows hold their values as text internally, so the getters convert on demand and a database that returns a number as text is read the same way. ## `Statement` A prepared, parameterised statement. Placeholders are `?` (SQLite, MySQL) or `$1`, `$2`, … (PostgreSQL). Bind values by **zero-based** parameter index, then run it once: | Method | Description | |---|---| | `bind_int(idx, value)`, `bind_float(idx, value)`, `bind_str(idx, value)`, `bind_null(idx)` | set parameter number `idx` (the first `?` is `0`). Values are passed as parameters, never concatenated into the SQL, so they cannot cause SQL injection. An out-of-range index raises the driver's error | | `execute()` | runs the statement; returns the affected row count | | `query()` | runs it and returns the rows | A `Statement` is **single use**: it is finished by `execute()` or `query()`; prepare a new one to run again. ```nox import nox.sqlite from nox.sqlite import Connection from nox.db import Row, Statement conn: Connection = nox.sqlite.open(":memory:") conn.execute("CREATE TABLE t (name TEXT, n INTEGER)") ins: Statement = conn.prepare("INSERT INTO t (name, n) VALUES (?, ?)") ins.bind_str(0, "ada") ins.bind_int(1, 36) print(ins.execute()) rows: list[Row] = conn.query("SELECT name, n FROM t") print(rows[0].get_str(0), rows[0].get_int(1), rows[0].column_count(), rows[0].column_name(1), rows[0].is_null(1)) conn.close() ``` ```output 1 ada 36 2 n False ``` ## Writing driver-independent code ```nox import nox.sqlite from nox.sqlite import Connection from nox.db import DbConnection, Row def count_rows(db: DbConnection, table: str) -> int: rows: list[Row] = db.query("SELECT COUNT(*) FROM " + table) return rows[0].get_int(0) c: Connection = nox.sqlite.open(":memory:") c.execute("CREATE TABLE a (x INTEGER)") c.execute("INSERT INTO a VALUES (1)") c.execute("INSERT INTO a VALUES (2)") print(count_rows(c, "a")) c.close() ``` ```output 2 ``` (Table and column names cannot be bound as parameters — validate them yourself before concatenating.) --- # nox.sqlite An SQLite driver. It loads the system `libsqlite3` **at run time, the first time you call `open`**, so programs that never use SQLite have no dependency on it; if the library is not installed, `open` raises a clean `SqliteError` instead of failing at build or start-up. On the WASM targets SQLite is linked statically instead (there is no dynamic loading); see [WASM](https://noxlang.com/docs/tools/wasm/#sqlite). ```text import nox.sqlite from nox.sqlite import Connection, SqliteError ``` **Capability:** `filesystem`. ## Functions and methods | Member | Description | |---|---| | `open(path)` | opens (creating if needed) a database file, or `":memory:"` for a private in-memory database; raises `SqliteError` on failure | | `Connection.execute(sql)` | runs a statement without parameters; returns the number of rows it changed. Several `;`-separated statements run in order (like `sqlite3_exec`: no implicit transaction, an error stops the script and earlier statements stay applied; the result is the total rows changed) | | `Connection.execute_script(sql)` | the same multi-statement runner, always (what `execute` calls when the text contains `;`) | | `Connection.query(sql)` | runs a query; returns `list[Row]` | | `Connection.prepare(sql)` | a parameterised [`Statement`](https://noxlang.com/docs/stdlib/db/#statement) with `?` placeholders | | `Connection.last_insert_rowid()` | the rowid of the most recent `INSERT` on this connection | | `Connection.changes()` | the number of rows changed by the most recent statement | | `Connection.close()` | closes the database | Errors — a syntax error, a constraint violation, a locked database, a missing file — raise `SqliteError` carrying SQLite's message. Result rows are the shared [`Row`](https://noxlang.com/docs/stdlib/db/#row) type; parameters are bound by **zero-based** index (`bind_str(0, …)` is the first `?`), and an out-of-range index raises `SqliteError`. ```nox import nox.sqlite from nox.sqlite import Connection, SqliteError from nox.db import Row, Statement conn: Connection = nox.sqlite.open(":memory:") conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, score REAL, note TEXT)") print(conn.execute("INSERT INTO users (name, score) VALUES ('ada', 9.5)"), conn.last_insert_rowid(), conn.changes()) st: Statement = conn.prepare("INSERT INTO users (name, score, note) VALUES (?, ?, ?)") st.bind_str(0, "alan") st.bind_float(1, 7.25) st.bind_null(2) print(st.execute()) for r in conn.query("SELECT id, name, score, note FROM users ORDER BY id"): print(r.get_int(0), r.get_str(1), r.get_float(2), r.is_null(3)) q: Statement = conn.prepare("SELECT name FROM users WHERE id = ?") q.bind_int(0, 2) print(q.query()[0].get_str(0)) try: conn.execute("NOT SQL") except SqliteError as e: print("SqliteError") conn.close() ``` ```output 1 1 1 1 1 ada 9.5 True 2 alan 7.25 True alan SqliteError ``` ## Notes - **Always pass values through `bind_*`**, never by building SQL from strings — see [Security](https://noxlang.com/docs/reference/security/). - A connection is not safe to share between tasks that may run on different workers; open one per task, or serialise access through a channel. - For the file-backed database, SQLite's own journalling gives you durability; wrap related changes in `BEGIN` / `COMMIT` with `execute`. - To back up a live SQLite database safely use SQLite's `VACUUM INTO 'file'` or its online-backup API, not a plain file copy. --- # nox.postgres A PostgreSQL driver over `libpq`, loaded at run time on the first `open` (no link-time dependency; a missing library raises a clean `PostgresError`). ```text import nox.postgres from nox.postgres import Connection, PostgresError ``` **Capability:** `network`. ## Functions and methods | Member | Description | |---|---| | `open(conninfo)` | connects; `conninfo` is passed to libpq unchanged, so both forms work: `"host=localhost user=app dbname=mydb"` and `"postgres://user:pass@host:5432/db"`; raises `PostgresError` on failure | | `Connection.execute(sql)` | runs a statement; returns the affected row count | | `Connection.query(sql)` | runs a query; returns `list[Row]` | | `Connection.prepare(sql)` | a parameterised [`Statement`](https://noxlang.com/docs/stdlib/db/#statement) with **`$1`, `$2`, …** placeholders | | `Connection.close()` | closes the connection | | `Connection.is_ok()` | is the connection still usable (not dropped)? | | `Connection.set_query_timeout(ms)` | client-side limit: a statement still running after `ms` milliseconds is cancelled with `PQcancel` and fails with `kind == "query_canceled"`; `0` removes the limit. Works even when the server stops answering normally. The connection stays usable | | `Connection.cancel()` | cancels the running statement from another task or thread (`True` if the request was sent); the statement fails with `kind == "query_canceled"`. Opens a short extra connection to the server, so it blocks the caller briefly | | `Connection.set_statement_timeout(ms)` | server-side limit: a statement running longer than `ms` milliseconds is cancelled by the server (`kind == "query_canceled"`); `0` removes the limit. The connection stays usable | | `Connection.set_lock_timeout(ms)` | the same for waiting on locks | | `Connection.transaction()` | a [`Transaction`](#transactions) for `with` | | `pool(conninfo, size, acquire_timeout_ms)` | a bounded [`Pool`](#connection-pool) | Parameters are bound by **zero-based** index in the Nox API (`bind_str(0, …)` fills `$1`), accumulated and sent together when you call `execute()` or `query()`. Each `Statement` execution is an independent request; there are no server-side named prepared statements. There is no `last_insert_rowid()`: use PostgreSQL's idiom `INSERT … RETURNING id` and read the id from `query()`. ```nox import nox.postgres from nox.postgres import Connection, PostgresError from nox.db import Row, Statement def create_user(conn: Connection, name: str) -> int: st: Statement = conn.prepare("INSERT INTO users (name) VALUES ($1) RETURNING id") st.bind_str(0, name) rows: list[Row] = st.query() return rows[0].get_int(0) def connect() -> Connection: return nox.postgres.open("postgres://app:secret@localhost:5432/appdb") ``` ## Errors `PostgresError` is structured. For errors reported by the server the fields come from the protocol, so you never have to parse the message: | Field / method | Meaning | |---|---| | `sqlstate` | the five-character SQLSTATE (`"23505"`); empty when no server was involved | | `severity`, `detail`, `hint`, `table`, `column`, `constraint` | the server's diagnostic fields (empty when absent) | | `kind` | `"unique_violation"` (23505), `"foreign_key_violation"` (23503), `"not_null_violation"` (23502), `"check_violation"` (23514), `"serialization_failure"` (40001), `"deadlock"` (40P01), `"query_canceled"` (57014: `statement_timeout`, cancel), `"connection"` (class 08, 57P01–57P03, and failures to connect or load libpq), otherwise `"other"` | | `is_unique_violation()`, `is_serialization_failure()`, `is_deadlock()`, `is_query_canceled()`, `is_connection_error()` | shortcuts for `kind` | | `is_retryable()` | `True` for serialization failures and deadlocks: retry the whole transaction. A connection error needs a **new connection** instead | ```text try: conn.execute("INSERT INTO users (id) VALUES (1)") except PostgresError as e: if e.is_unique_violation(): print("duplicate", e.constraint) ``` ## Transactions `with conn.transaction() as tx:` runs `BEGIN`, and `__exit__` rolls back unless the body called `tx.commit()` first (Nox's `__exit__` cannot see an exception, so the rule is "anything not explicitly committed is rolled back", like Go's `defer tx.Rollback()`). `tx` has `execute`, `query`, `prepare`, `commit` and `rollback`. ```text with conn.transaction() as tx: tx.execute("UPDATE accounts SET balance = balance - 10 WHERE id = 1") tx.execute("UPDATE accounts SET balance = balance + 10 WHERE id = 2") tx.commit() # leave the block without this and both updates are rolled back ``` ## Connection pool `nox.postgres.pool(conninfo, size, acquire_timeout_ms)` returns a `Pool` that opens at most `size` connections on demand. `acquire()` hands out an idle connection or a new one; when all `size` are in use it waits **cooperatively** (other tasks keep running) and raises `PostgresError` after `acquire_timeout_ms`. Give the connection back with `give_back(conn)`: a dropped connection is discarded (and replaced on the next `acquire`), an open transaction is rolled back. `close()` closes the idle connections. The pool's bookkeeping is protected by an atomic lock, so one pool may be shared by tasks running on different workers; a single connection must be used by one task at a time. ```text pool: Pool = nox.postgres.pool("host=localhost dbname=app", 4, 5000) conn: Connection = pool.acquire() try: rows: list[Row] = conn.query("SELECT 1") finally: pool.give_back(conn) ``` ## Notes - libpq is driven in non-blocking mode: inside a task a slow query suspends only that task, and other tasks keep running on the same worker (outside a task the call waits with `poll`). `set_query_timeout` bounds a query from the client, `set_statement_timeout` from the server, and `cancel()` stops one on demand. - Module-level variables are per worker (see [Modules](https://noxlang.com/docs/language/modules/#module-level-state-and-the-multi-core-runtime)): a `Connection` kept in a module variable and used from several tasks is a different object on each worker, so `cancel()` only reaches the query running on the same copy. Run with `NOX_POOL_WORKERS=1` (or keep the cancelling code on the connection's own task) when one task must cancel another's query. - `libpq` (the PostgreSQL client library) must be installed on machines that call `open` — for example the `libpq5` package on Debian/Ubuntu. - Prefer `Statement` parameters over concatenating SQL; they travel to the server separately from the SQL text. - Do not share a connection between tasks that may run on different workers. - For application code that should run on any driver, accept a [`DbConnection`](https://noxlang.com/docs/stdlib/db/#dbconnection-the-common-connection-interface). ## On a mobile target (iOS, Android) There is no `libpq` on a phone, so on `ios-*` and `android-*` targets `nox.postgres` uses a PostgreSQL protocol 3.0 client written in Zig, over the operating system's sockets. The API and the `conninfo` forms are the same; nothing has to be installed. Authentication: trust, cleartext, MD5 and SCRAM-SHA-256. Queries use the simple protocol (`execute`, `query`) and the extended protocol (`prepare` with `bind_*`). - **TLS** is used only for `sslmode=require` and `verify-*`: the connection asks the server for TLS, then verifies its certificate and host name against the system CA store, and fails if it cannot (a self-signed certificate is refused; the client never falls back to plain text when `require` is set). Every other `sslmode`, including the default, is plain text, unlike libpq's `prefer`. **Use `sslmode=require` for any server that is not on a trusted local network.** - Calls block the calling thread. `set_query_timeout(ms)` and `cancel()` work here too: when the time runs out (or you call `cancel()` from another task) a `CancelRequest` goes out on a separate connection, the server's `57014` answer is awaited and the connection stays usable; if the server does not answer the cancel within 10 s the connection is closed and the call fails. (On `wasm32-freestanding --asyncify` the same limit works: the host bounds each TCP read; a host that ignores the `timeout=` field of the read request blocks as before.) `set_statement_timeout` still bounds queries on the server. - Verified on the iOS simulator and the Android emulator against a real PostgreSQL server (`scripts/mobile_db_probe.py`). --- # nox.grpc A gRPC client (HTTP/2 over plain TCP `h2c`, or over TLS with ALPN `h2`) written in Zig: no `grpc` library needed. Messages are protobuf bytes (encode and decode them with [`nox.protobuf`](https://noxlang.com/docs/stdlib/protobuf/)); a `str` holds bytes safely, including NUL. ```text import nox.grpc from nox.grpc import Client, Response, GrpcError, GrpcStatusError ``` **Capability:** `network`. ## Connecting and calling ```text c: Client = nox.grpc.connect("127.0.0.1", 50051) reply: str = c.unary("/helloworld.Greeter/SayHello", request_bytes) r: Response = c.call("/pkg.Svc/Stream", [m1, m2]) print(r.status, r.message, len(r.messages), r.header("x-request-id")) c.close() ``` | Member | Description | |---|---| | `connect(host, port) -> Client` | opens a plain TCP (`h2c`) connection and sends the HTTP/2 preface; failure raises `GrpcError` | | `connect_tls(host, port, ca_file="", cert_file="", key_file="") -> Client` | the same over TLS with ALPN `h2`. The server name is checked against the certificate. An empty `ca_file` uses the system CA store; a PEM path trusts only the CAs in that file (a private CA, a self-signed server). `cert_file` + `key_file` (PEM) present a client certificate when the server asks for one (mTLS); the key can be ECDSA P-256/P-384, Ed25519 or RSA (1024 to 4096 bits; RSASSA-PSS), PKCS#8 or PKCS#1/SEC1 PEM, unencrypted | | `Client.unary(path, request, timeout_ms=0) -> str` | one request, one reply message; a status other than `OK` raises `GrpcStatusError` (`code`, `detail`) | | `Client.call(path, requests, timeout_ms=0) -> Response` | any RPC shape: one or more request messages (client streaming), all reply messages collected (server streaming). The status is in the `Response`, not raised | | `Client.call_with(path, requests, metadata, timeout_ms) -> Response` | the same with request metadata (`dict[str, str]`) | | `Client.open_stream(path, metadata, timeout_ms=0) -> Stream` | a bidirectional stream: requests and replies interleave (see below) | | `Client.close()`, `Client.is_ok()` | close; whether the connection is still usable | | `Response.status`, `.message`, `.messages`, `.ok()`, `.header(name)` | gRPC status code, status message, reply messages, response header or trailer value (case-insensitive, `""` if absent) | `path` is `/package.Service/Method`. Status constants (`nox.grpc.NOT_FOUND`, `UNAVAILABLE`, ...) follow the gRPC status codes. `timeout_ms > 0` is sent as `grpc-timeout`; the server answers `DEADLINE_EXCEEDED` when it runs out. ## Bidirectional streams `open_stream` returns a `Stream` for calls where requests and replies interleave (chat-like RPCs, or a server that answers each request before the next is sent): ```text st: Stream = c.open_stream("/chat.Room/Talk", metadata) st.send(first) reply: str | None = st.recv() # blocks (cooperatively) until a reply or the end of the stream st.close_send() # no more requests; the server may finish while st.recv() is not None: pass print(st.status(), st.message(), st.header("x-trailer")) ``` `recv()` returns `None` once the server has finished the call; then `status()`, `message()` and `header(name)` hold the result. `finish()` reads and discards the rest and returns the status. Only one stream (or `call`) can be open on a connection at a time. Letting a `Stream` go out of scope before it ends cancels the call (`RST_STREAM`) and frees the connection for the next one; release or finish streams **before** `Client.close()`. ## Errors - A transport or protocol failure (connection lost, malformed frame, `GOAWAY`, a stream reset) raises `GrpcError` and closes the connection; open a new one with `connect`. - A server status is data: `Response.status`, or `GrpcStatusError` from `unary`. The status message is percent-decoded. ## Limits - **TLS needs TLS 1.3 ALPN support from the server** (the usual case for gRPC servers); a server that does not select `h2` makes `connect_tls` fail. Client certificates: TLS 1.3 only (ECDSA, Ed25519, RSA-PSS keys; no password-protected keys). On `wasm32-freestanding-asyncify` the host terminates TLS (ALPN `h2`, `ca_file` and mTLS files are read by the host; see [WebAssembly](https://noxlang.com/docs/tools/wasm/#grpc-over-tls-noxgrpcconnect_tls)). - **One call or stream at a time** per connection (open several connections for parallel calls). `call` sends all requests and then collects the replies; use `open_stream` to interleave. - **Compression:** gzip only. Requests announce `grpc-accept-encoding: gzip,identity` and gzip replies are decoded automatically; `Client.use_compression(True)` gzips the request messages too. Any other `grpc-encoding` is an error. - **No client-side read timeout** (the same limit as [`nox.redis`](https://noxlang.com/docs/stdlib/redis/)); use `timeout_ms` so the server enforces the deadline. - Flow control is handled in both directions (a 300 KB request and a 2 MB reply are tested). --- # nox.grpc_server A gRPC **server** written in Nox on top of [`nox.http`](https://noxlang.com/docs/stdlib/http/) (HTTP/2: cleartext with prior knowledge, or TLS with ALPN `h2` through the `serve_tls*` functions). Messages are protobuf bytes; encode and decode them with [`nox.protobuf`](https://noxlang.com/docs/stdlib/protobuf/). ```text import nox.http import nox.grpc_server from nox.http import HttpRequest, HttpResponse from nox.grpc import GrpcStatusError from nox.grpc_server import Method, StreamMethod, CtxMethod, Call ``` **Capability:** `network`. ```nox-fragment def say_hello(requests: list[str]) -> list[str]: return ["hello " + requests[0]] def not_found(requests: list[str]) -> list[str]: raise GrpcStatusError(5, "no such user") def table() -> list[Method]: return [Method("/helloworld.Greeter/SayHello", say_hello), Method("/helloworld.Greeter/Find", not_found)] def handle(req: HttpRequest) -> HttpResponse: return nox.grpc_server.dispatch(table(), req) nox.http.serve(50051, handle) ``` | Member | Description | |---|---| | `Method(path, handler)` | a method: `path` is `/package.Service/Method`; `handler` is `(list[str]) -> list[str]` | | `StreamMethod(path, handler)` | a **true streaming** method: `handler` is `(Call) -> None` | | `Call.recv() -> str \| None`, `Call.send(message) -> bool` | the next request message (`None` when the client has finished sending); send a reply message **immediately** | | `CtxMethod(path, handler)` | a batch method whose handler also gets the `Call`: `(Call, list[str]) -> list[str]` | | `dispatch_all(methods, streams, req) -> HttpResponse` | like `dispatch` with both tables | | `dispatch_full(methods, streams, ctxs, req, compress_replies=False) -> HttpResponse` | all three tables; `compress_replies=True` gzips replies for clients that accept it | | `dispatch(methods, req) -> HttpResponse` | runs the call for a `nox.http` handler: finds the method, calls the handler with the request messages, sends the reply messages and the `grpc-status` trailer | | `parse_messages(body) -> list[str]`, `frame(message) -> str`, `frame_gzip(message) -> str` | the length-prefixed message framing (`frame_gzip` compresses the message with gzip and sets the compressed flag), for tests and custom handlers | | `parse_timeout_ms(value) -> int` | parses a `grpc-timeout` header value (`5S`, `100m`, `2H`, units `H M S m u n`) into milliseconds; `0` if absent or malformed | A handler receives **all request messages** (one for a unary or server-streaming method, several for client streaming) and returns **all reply messages** (one for unary or client streaming, several for server streaming). Raise `GrpcStatusError(code, "message")` to return a status other than `OK`; the message is percent-encoded for you. A method that is not in the table answers `UNIMPLEMENTED` (12). A gzip-compressed request message is decompressed; replies are compressed only when you ask (see below). ## Bidirectional streaming A `StreamMethod` handler runs as soon as the request headers arrive and reads the request body piece by piece, so requests and replies interleave: a chat-like RPC can answer each message before the next one is sent. ```text def chat(call: Call) -> None: m: str | None = call.recv() while m is not None: call.send("echo:" + m) m = call.recv() def streams() -> list[StreamMethod]: return [StreamMethod("/chat.Room/Talk", chat)] def handle(req: HttpRequest) -> HttpResponse: return nox.grpc_server.dispatch_all(table(), streams(), req) ``` Raise `GrpcStatusError` from the handler to finish the call with that status (replies already sent stay delivered). When the handler returns, the call ends with `OK`. Under the hood the HTTP/2 server gives a request with `content-type: application/grpc` to the handler before its body ends, and `req.read_chunk(n)` (see [`nox.http`](https://noxlang.com/docs/stdlib/http/)) delivers the body as it arrives; flow control keeps at most 1 MiB buffered per call. ## Metadata, deadlines, headers, trailers and compression `Call` (the argument of a `StreamMethod` handler and of a `CtxMethod` handler) exposes the call's context: | Member | Description | |---|---| | `call.header(name) -> str` | request metadata (case-insensitive name; `""` if absent), e.g. `call.header("authorization")` | | `call.timeout_ms() -> int`, `call.remaining_ms() -> int`, `call.expired() -> bool` | the client's `grpc-timeout` in ms (0 if none), time left (-1 if none, 0 once passed), and whether it has passed | | `call.set_header(name, value)`, `call.set_trailer(name, value)` | response metadata: headers go out with the first reply (or `call.send_headers()`), trailers next to `grpc-status` | | `call.use_compression(True)` | gzip the replies (effective only when the client sent `grpc-accept-encoding: gzip`; call it before the first reply). `call.compressing()` tells whether it is on | | `call.send_headers()` | send the response headers now | The deadline is enforced for you: `recv()` and `send()` raise `GrpcStatusError(4, "deadline exceeded")` (`DEADLINE_EXCEEDED`) once the client's `grpc-timeout` has passed, and a batch method whose handler returns late answers `DEADLINE_EXCEEDED` instead of its replies. A handler stuck in a loop that never calls `recv`/`send` is not interrupted; poll `call.expired()` there. ```text def whoami(call: Call, requests: list[str]) -> list[str]: if call.header("x-token") != "s3cret": raise GrpcStatusError(16, "bad token") call.set_trailer("x-served-by", "nox") return ["ok"] def ctxs() -> list[CtxMethod]: return [CtxMethod("/svc.Auth/WhoAmI", whoami)] def handle(req: HttpRequest) -> HttpResponse: return nox.grpc_server.dispatch_full(table(), streams(), ctxs(), req, True) ``` ## Limits - A plain `Method` handler runs after the whole request body has been read (it is the simple unary / client-streaming / server-streaming form). Use `StreamMethod` when a reply must go out before the request ends. - Plain `Method` handlers do not see metadata or the deadline; use `CtxMethod` for that. - For `Method`/`CtxMethod`, reply messages are sent after the handler returns, not while it runs (use `StreamMethod` + `call.send` to stream). - Flow control, large messages and many sequential calls on one connection are tested against `grpcio` (a 300 KB request and a 2 MB reply). --- # nox.redis A Redis client (RESP2) written in Zig: no `hiredis` needed. Plain TCP or TLS from the first byte, `AUTH` (password or user + password), `SELECT`, byte-safe commands and replies, Streams and consumer groups, a script cache with `NOSCRIPT` recovery, and reconnecting. ```text import nox.redis from nox.redis import Client, Reply, RedisError ``` **Capability:** `network`. ## Connecting `connect(host, port=6379, tls=False, username="", password="", db=0, ca_file="", cert_file="", key_file="") -> Client` - `tls=True` starts TLS immediately (a `rediss://`-style endpoint); the certificate and host name are checked against the system CA store. `ca_file` (a PEM path) replaces the system store: only the CAs in that file are trusted (a private CA or a self-signed server). `cert_file` + `key_file` (PEM) present a client certificate when the server requires one (mTLS): ECDSA P-256/P-384, Ed25519 or RSA (RSASSA-PSS) keys, unencrypted PEM. `reconnect()` keeps all three. - A non-empty `password` sends `AUTH` (`AUTH username password` when `username` is given); `db > 0` sends `SELECT`. - Failure raises `RedisError` with `kind == "connection"`. `connect_url(url, ca_file="", cert_file="", key_file="") -> Client` connects from a connection URL, the form managed services (Upstash, Redis Cloud, ElastiCache, Azure Cache) hand out: ```text c: Client = nox.redis.connect_url("rediss://default:s3cret@db.example.com:6380/2") ``` `redis://` is plain TCP, `rediss://` starts TLS (system CA store unless `ca_file`). `[user]:password@` becomes `AUTH` (a password alone: `redis://:password@host`; user and password may be percent-encoded, e.g. `%40` for `@`); the path is the database number (`/2`); the port defaults to 6379. Another scheme, an empty host or a non-numeric database raises `RedisError` with `kind == "connection"`; the error message never contains the password. ## Commands | Member | Description | |---|---| | `command(args: list[str]) -> Reply` | any Redis command; the arguments are binary-safe (NUL bytes and non-UTF-8 bytes are sent as is) | | `ping()`, `get(key) -> str \| None`, `set(key, value)`, `set_ex(key, value, seconds)`, `delete(key)`, `incr(key)`, `expire(key, seconds)` | common commands | | `xadd(stream, fields, maxlen=0)` | `XADD` (approximate `MAXLEN ~` when `maxlen > 0`); returns the new entry id | | `xgroup_create(stream, group, start_id="$", mkstream=True)` / `xgroup_ensure(...)` | `XGROUP CREATE`; `xgroup_ensure` returns `False` instead of raising when the group exists (`BUSYGROUP`) | | `xreadgroup(group, consumer, stream, id=">", count=1, block_ms=-1)` | `XREADGROUP`; `block_ms < 0` does not block, `0` blocks forever. A timeout returns a nil `Reply` | | `xautoclaim(stream, group, consumer, min_idle_ms, start="0-0", count=100)` | `XAUTOCLAIM`: `[next-id, [[id, [field, value, ...]], ...], [deleted ids]]` | | `xack(stream, group, ids)` | `XACK`; returns how many entries were acknowledged | | `script_load(script)`, `eval_cached(script, keys, args)` | `SCRIPT LOAD` + `EVALSHA`, caching the sha per connection; a `NOSCRIPT` reply (server restart, `SCRIPT FLUSH`) reloads the script and retries once | | `set_read_timeout(ms)` | per-reply read deadline (`0` = off, the default); see *Read timeout* below | | `pipeline(commands: list[list[str]]) -> list[Reply]` | sends every command in one write, then reads the replies in order; a server error is the matching `Reply` (`is_error()`), not an exception | | `is_ok()`, `reconnect()`, `close()` | connection management | ## Replies A `Reply` is a tree: `kind()` is `0` nil, `1` simple string, `2` error, `3` integer, `4` bulk string, `5` array. `as_str()`, `as_int()`, `len()`, `at(i)` read it; `to_str_list()` turns an array of strings into a `list[str]`. Bulk strings are byte-exact. A child returned by `at(i)` borrows the parent's memory and keeps the parent alive. ```text r: Reply = client.xreadgroup("workers", "w1", "jobs", ">", 10, 2000) if not r.is_nil(): entry: Reply = r.at(0).at(1).at(0) # first entry of the first stream print(entry.at(0).as_str(), entry.at(1).to_str_list()) ``` ## Errors `RedisError` has `kind` and `code`: - `kind == "server"`: the server answered with an error (`-WRONGTYPE ...`). `code` is its first word (`"WRONGTYPE"`, `"NOSCRIPT"`, `"BUSYGROUP"`, `"NOAUTH"`, `"NOPERM"`); helpers `is_wrongtype()`, `is_noscript()`, `is_busygroup()`. - `kind == "timeout"` (`is_timeout()`; also `is_connection_error()`): a reply did not arrive within `set_read_timeout`. The client is closed afterwards (a late reply must not be mistaken for the next command's): call `reconnect()`. - `kind == "connection"` (`is_connection_error()`): connecting failed, or the connection broke. The client is closed afterwards: call `reconnect()` (it repeats `AUTH`/`SELECT` and clears the script cache). A command interrupted by a broken connection may or may not have run on the server; whether to retry is up to the caller. ## Notes - **Read timeout:** off by default (blocking commands such as `XREADGROUP ... BLOCK` legitimately wait; inside a task only that task waits). `set_read_timeout(ms)` bounds every reply; `xreadgroup` adds its own `block_ms` to the bound, so `BLOCK 0` is bounded by the timeout alone. Inside a fiber only that fiber is suspended. On `wasm32-freestanding --asyncify` the host bounds the TCP read (the request carries `timeout=`); a host that ignores that field blocks as before. If the deadline passes, the late bytes stay with the host and are not lost, but the client is closed anyway. - RESP2 only; no pub/sub push messages. A single `Client` talks to one node: `MOVED`/`ASK` surface as `RedisError` there; use [`nox.redis_cluster`](https://noxlang.com/docs/stdlib/redis_cluster/) for a Redis Cluster. - Verified against real `redis-server` for commands, binary payloads, Streams, scripts, `AUTH`/ACL and reconnecting. TLS reuses the client of [`nox.tls`](https://noxlang.com/docs/stdlib/tls/) (an untrusted certificate is rejected); a successful handshake with a publicly trusted server certificate has not been exercised against a Redis in this repository's tests. --- # nox.redis_cluster A Redis Cluster client on top of [`nox.redis`](https://noxlang.com/docs/stdlib/redis/). It computes each key's hash slot (CRC16, with `{hash tag}` support), sends the command to the node that owns the slot, follows `-MOVED` and `-ASK` redirects, and refreshes the slot map when a node goes away. Pure Nox; RESP2. **Capability:** `network`. ```nox import nox.redis_cluster slot: int = nox.redis_cluster.key_slot("user:1000") print(slot >= 0 and slot < 16384) print(nox.redis_cluster.key_slot("a{b}c") == nox.redis_cluster.key_slot("b")) print(nox.redis_cluster.same_slot(["{u}.a", "{u}.b"]), nox.redis_cluster.same_slot(["a", "b"])) ``` ```output True True True False ``` Connecting and using a cluster: ```text c: nox.redis_cluster.ClusterClient = nox.redis_cluster.connect(["10.0.0.1:7000", "10.0.0.2:7000"]) c.command("user:1", ["SET", "user:1", "ada"]) print(c.command("user:1", ["GET", "user:1"]).as_str()) c.close() ``` | Call | Description | |---|---| | `connect(seeds, tls=False, username="", password="", ca_file="", read_timeout_ms=0, max_redirects=5) -> ClusterClient` | `seeds` is a list of `"host:port"`; at least one must answer `CLUSTER SLOTS`. Node connections are opened lazily and reused; the options are applied to every node | | `c.command(key, args) -> Reply` | runs `args` on the node that owns `key`'s slot (the key must also appear in `args`). Raises the same `RedisError` as `nox.redis` for server errors | | `c.refresh()` | re-reads the topology (`CLUSTER SLOTS`) from a known node or a seed | | `c.slot_owner(slot) -> str` | the `"host:port"` that serves a slot | | `c.close()` | closes every node connection | | `key_slot(key) -> int`, `same_slot(keys) -> bool` | the hash slot (0–16383) and a same-slot check for multi-key commands | Redirects: a `-MOVED` updates the slot map and the command is retried on the new owner; an `-ASK` (slot migration in progress) sends `ASKING` plus the command to the target without changing the map; a broken connection triggers one topology refresh and a retry. More than `max_redirects` hops raises `ClusterError`. Limits: multi-key commands (`MGET`, `MSET`, Lua scripts) need all keys in one slot (use `{tags}`; the server answers `-CROSSSLOT` otherwise); there is no pub/sub, no pipelining across nodes, and every command goes to the slot's primary (no reads from replicas). Verified against a real three-node cluster (slot arithmetic cross-checked with the server's `CLUSTER KEYSLOT`, `-MOVED` self-healing and `-ASK`), see `scripts/redis_cluster_probe.py`. --- # nox.mysql A MySQL / MariaDB driver over `libmysqlclient` (or the binary-compatible MariaDB connector), loaded at run time on the first `open_url`. A missing library raises a clean `MysqlError`. ```text import nox.mysql from nox.mysql import Connection, MysqlError ``` **Capability:** `network`. ## Functions and methods | Member | Description | |---|---| | `open_url(conn_url)` | connects using `mysql://user:pass@host:port/database` (the port defaults to 3306); raises `MysqlError` on failure | | `Connection.execute(sql)` | runs a statement; returns the affected row count | | `Connection.query(sql)` | runs a query; returns `list[Row]` | | `Connection.prepare(sql)` | a parameterised [`Statement`](https://noxlang.com/docs/stdlib/db/#statement) with `?` placeholders | | `Connection.last_insert_rowid()` | the auto-increment id of the last `INSERT` | | `Connection.changes()` | rows changed by the last statement | | `Connection.close()` | closes the connection | Parameters are bound by **zero-based** index. This driver escapes string values on the client with the library's own `mysql_real_escape_string` and substitutes them into the statement, so bound values are protected from SQL injection even though there is no server-side prepared statement. ```nox import nox.mysql from nox.mysql import Connection, MysqlError from nox.db import Row, Statement def add_user(conn: Connection, name: str) -> int: st: Statement = conn.prepare("INSERT INTO users (name) VALUES (?)") st.bind_str(0, name) st.execute() return conn.last_insert_rowid() def connect() -> Connection: return nox.mysql.open_url("mysql://app:secret@localhost:3306/appdb") ``` ## Notes - Install `libmysqlclient` (or MariaDB Connector/C) on machines that connect. - Do not build SQL by concatenating untrusted text; use `bind_*`. - Do not share a connection between tasks that may run on different workers. ## On a mobile target (iOS, Android) There is no `libmysqlclient` on a phone, so on `ios-*` and `android-*` targets `nox.mysql` uses a MySQL/MariaDB client written in Zig, over the operating system's sockets. The API is the same; nothing has to be installed. Authentication: `mysql_native_password` and `caching_sha2_password` (fast path, and the full path with the server's RSA key, so the password never travels in plain text even without TLS), including an authentication plugin switch. Queries use the text protocol (`COM_QUERY`); a result set is held in memory once the reply is complete, and only the first of several result sets is returned. - **There is no TLS yet.** The password is protected, but queries and results are not: only connect to a server over a network you trust (loopback, a VPN, a private network). A phone app should normally talk to an HTTP API rather than straight to a database. - `host` is always a TCP host (no Unix socket for `localhost`). Calls block the calling thread, and there is no read timeout. - Verified on the iOS simulator and the Android emulator against a real MySQL 8.4 server (`scripts/mobile_db_probe.py`). --- # nox.orm A micro-ORM: describe a table once, then create it and run parameterised insert/update/delete/select helpers over any [`DbConnection`](https://noxlang.com/docs/stdlib/db/#dbconnection-the-common-connection-interface). It is a **query builder with typed values**, not an object mapper — there is no reflection in Nox, so results come back as [`Row`](https://noxlang.com/docs/stdlib/db/#row)s and you convert them to your own types. ```text from nox.orm import Table, Column, Value import nox.orm ``` **Capability:** none (it works over whichever driver you pass). ## Describing a table | Constructor | Description | |---|---| | `Column(name, kind, is_primary_key)` | a column; `kind` is `0` integer, `1` text, `2` real (float) | | `Table(name, columns)` | a table with its columns | ## Values SQL values are wrapped in `Value`s so every statement is parameterised: | Function | Description | |---|---| | `val_str(s)`, `val_int(i)`, `val_float(f)`, `val_bool(b)`, `val_null()` | construct a `Value` | ## Operations | Function | Description | |---|---| | `create_table_sql(table)` | the `CREATE TABLE IF NOT EXISTS …` text | | `create_table(conn, table)` | runs it | | `insert(conn, table, values)` | inserts one row from a `dict[str, Value]` (column → value); returns the affected row count | | `update(conn, table, values, where_sql, where_params)` | sets the given columns on rows matching `where_sql` (using `?` placeholders filled from `where_params`); returns the affected row count | | `delete(conn, table, where_sql, where_params)` | deletes matching rows; returns the affected row count | | `select(conn, table, where_sql, where_params)` | returns the matching rows as `list[Row]` in column order | `where_sql` is a fragment such as `"age > ? AND name = ?"`; its values always come from `where_params`. Pass `""` for no condition. Column and table names are placed into the SQL text, so they must come from your code, never from user input. Errors raise `OrmError` (or the driver's error). ```nox import nox.sqlite import nox.orm from nox.sqlite import Connection from nox.db import Row from nox.orm import Table, Column, Value conn: Connection = nox.sqlite.open(":memory:") people: Table = Table("people", [Column("id", 0, True), Column("name", 1, False), Column("age", 0, False)]) print(nox.orm.create_table_sql(people)) nox.orm.create_table(conn, people) vals: dict[str, Value] = {"name": nox.orm.val_str("grace"), "age": nox.orm.val_int(85)} print(nox.orm.insert(conn, people, vals)) print(nox.orm.update(conn, people, {"age": nox.orm.val_int(86)}, "name = ?", [nox.orm.val_str("grace")])) found: list[Row] = nox.orm.select(conn, people, "age > ?", [nox.orm.val_int(50)]) print(found[0].get_str(1), found[0].get_int(2)) print(nox.orm.delete(conn, people, "name = ?", [nox.orm.val_str("grace")])) conn.close() ``` ```output CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, name TEXT, age INTEGER) 1 1 grace 86 1 ``` ## Notes - The SQL it generates uses `?` placeholders; with PostgreSQL use `Statement` directly, or a driver that accepts `?` (SQLite, MySQL). - For anything beyond single-table CRUD (joins, aggregates) write the SQL yourself with `query` and `prepare`. --- # nox.thread Explicit worker threads and thread-to-thread channels. The language's `spawn` / `await` already runs tasks in parallel under the default scheduler ([Concurrency](https://noxlang.com/docs/language/concurrency/)); `nox.thread` is for when you want a named unit of work with a joinable handle, or a channel that is safe to hand to such a unit. ```text import nox.thread ``` **Capability:** `threads` (unavailable in freestanding profiles). ## `start` and `ThreadHandle[T]` ```text h: ThreadHandle[T] = nox.thread.start(fn, arg) result: T = await h.join() ``` | Item | Description | |---|---| | `nox.thread.start(fn, arg)` | starts `fn(arg)` on another thread and returns a `ThreadHandle[T]` where `T` is the result type of `fn`. `fn` must be an `async def` taking one argument | | `await h.join()` | waits for the thread and returns (or re-raises) its result | ## `ThreadChannel[T]` A bounded channel designed to be shared with a started thread: `ThreadChannel[T](capacity)` with `await tc.send(v)` and `await tc.recv()`, like [`Channel[T]`](../language/concurrency.md#channels), but the channel itself may be passed as the `arg` of `start`. `capacity` must be at least 1 (rendezvous channels are not supported across threads). ```nox import nox.thread async def worker(x: int) -> int: return x * 2 async def producer(tc: ThreadChannel[int]) -> None: i: int = 0 while i < 3: await tc.send(i * 10) i = i + 1 async def run() -> None: h: ThreadHandle[int] = nox.thread.start(worker, 21) print(await h.join()) tc: ThreadChannel[int] = ThreadChannel[int](2) p: ThreadHandle[None] = nox.thread.start(producer, tc) total: int = 0 j: int = 0 while j < 3: total += await tc.recv() j = j + 1 await p.join() print(total) t: Task[None] = spawn run() await t ``` ```output 42 30 ``` ## `pool_run` `nox.thread.pool_run(num_workers, entry)` runs `entry` — an `async def entry() -> None` with no parameters — and waits until it and everything it spawns has finished. On the default backend the program already runs on a shared worker pool, so `pool_run` simply groups work under one waiting call; the `num_workers` argument is honoured only when it has to create the pool itself, and the pool size is otherwise set at program start (see below). ## Argument types | Backend | `start` / `spawn` arguments and results | |---|---| | LLVM (default) | `int`, `float`, `bool`, `str`, `None`, `ptr`, `ThreadChannel[T]`, plus `list[T]`, classes, `dict[K, V]`, `Task[T]`, `Channel[T]`, `TaskLocal[T]` (retained for the worker) | | QBE | `int`, `float`, `bool`, `str`, `None`, `ptr`, `ThreadChannel[T]` | ## Pool size Under the LLVM backend, programs that only use `spawn`/`start` get a small default pool (2 workers); programs that call `nox.http.serve_multicore*` or `nox.thread.pool_run` get one worker per CPU core. Set the environment variable **`NOX_POOL_WORKERS=N`** to choose the size explicitly at run time. ## Notes - Threads share nothing implicitly: module-level variables are per worker, so communicate through channels, [`nox.atomic`](https://noxlang.com/docs/stdlib/atomic/) cells or [`nox.sharedmem`](https://noxlang.com/docs/stdlib/sharedmem/). - `start` needs `async def` entry functions even though they run on their own thread. --- # nox.atomic Process-wide atomic cells for sharing a counter or flag between workers. A cell lives in memory shared by every worker, so — unlike module-level variables, which are per worker — updates are visible everywhere. ```text import nox.atomic from nox.atomic import AtomicInt, AtomicBool ``` **Capability:** `threads` (unavailable in freestanding profiles). This is intentionally narrow: a single 64-bit integer or boolean, not a shared object graph. For separate **processes** use [`nox.sharedmem`](https://noxlang.com/docs/stdlib/sharedmem/). ## `AtomicInt` | Member | Description | |---|---| | `new_int(initial)` | creates a cell holding `initial` | | `load()` | reads the value | | `store(value)` | writes a value | | `add(delta)` | atomically adds `delta` and returns the **new** value | | `increment()`, `decrement()` | `add(1)` / `add(-1)`, returning the new value | | `compare_and_swap(expected, desired)` | if the value equals `expected`, replaces it with `desired`; returns whether it did | | `handle` | the cell's address as an `int`, to pass to another worker | | `from_int_handle(h)` | wraps the same cell from a handle | | `free()` | releases the cell | `AtomicError` is the exception class of the module; the operations above do not raise in normal use. ## `AtomicRef` A shared, immutable **`str` snapshot** (serialized configuration, a route table, JSON). Workers have separate ARC heaps, so the *bytes* are shared rather than an object: `set` copies the value and swaps it in, `get` returns a fresh copy on the caller's heap, and a reader always sees one whole `set` (never a half-written value). | Member | Description | |---|---| | `new_ref(initial)` / `from_ref_handle(h)` | create a cell / attach to an existing one in another worker (`handle` is an `int`) | | `get()` | the current snapshot (a copy) | | `set(value)` | publishes a new snapshot and returns its version number | | `version()` | increases by one on every `set`; poll it to notice a change | | `free()` | release the cell once every worker is done | ## `AtomicBool` `new_bool(initial)`, `load()`, `store(value)`, `compare_and_swap(expected, desired)`, `handle`, `from_bool_handle(h)`, `free()` — the same operations for a flag. ```nox import nox.atomic from nox.atomic import AtomicInt, AtomicBool c: AtomicInt = nox.atomic.new_int(5) print(c.load(), c.add(3), c.increment(), c.decrement(), c.compare_and_swap(8, 100), c.compare_and_swap(8, 1), c.load()) c.store(42) print(c.load()) b: AtomicBool = nox.atomic.new_bool(False) print(b.load(), b.compare_and_swap(False, True), b.load()) same: AtomicInt = nox.atomic.from_int_handle(c.handle) print(same.load()) c.free() b.free() ``` ```output 5 8 9 8 True False 100 42 False True True 42 ``` ## Sharing a cell with workers Create the cell once, pass `cell.handle` (an `int`) to each worker as an argument, and rebuild a wrapper there with `from_int_handle`. Free the cell **once**, after every worker has finished — there is no automatic release, and using a handle after `free()` is invalid. ```nox import nox.atomic import nox.thread from nox.atomic import AtomicInt async def bump(handle: int) -> int: cell: AtomicInt = nox.atomic.from_int_handle(handle) i: int = 0 while i < 100: cell.increment() i = i + 1 return 0 async def run() -> None: counter: AtomicInt = nox.atomic.new_int(0) a: ThreadHandle[int] = nox.thread.start(bump, counter.handle) b: ThreadHandle[int] = nox.thread.start(bump, counter.handle) await a.join() await b.join() print(counter.load()) counter.free() t: Task[None] = spawn run() await t ``` ```output 200 ``` --- # nox.sharedmem Named shared-memory segments for communicating between **separate operating-system processes** (two `noxc run` invocations, a server and a helper). Within one program, use channels or [`nox.atomic`](https://noxlang.com/docs/stdlib/atomic/) instead. ```text import nox.sharedmem from nox.sharedmem import SharedBuffer, SharedMemError ``` **Capability:** `shared_memory` (macOS and Linux; unavailable in freestanding profiles). ## Functions and methods | Member | Description | |---|---| | `open(name, size)` | opens the segment called `name` (creating it with `size` bytes if it does not exist) and maps it; names look like `"/myapp-state"`; raises `SharedMemError` on failure | | `unlink(name)` | permanently removes the segment's name (segments live until unlinked) | | `SharedBuffer.lock()`, `unlock()` | a spin lock stored in the segment: take it around any read-modify-write; pair it with `defer buf.unlock()` | | `SharedBuffer.read_int(offset)`, `write_int(offset, value)` | a 64-bit integer at a byte offset | | `SharedBuffer.read_str(offset, length)`, `write_str(offset, value)` | `length` bytes as text / write the bytes of a string | | `SharedBuffer.close()` | unmaps it **in this process only**; other processes keep their mapping | The segment is plain bytes: you decide the layout. Keep offsets inside `size` and, when two processes interpret the layout, agree on it. `lock` protects the segment as a whole; it is not re-entrant. ```nox import nox.sharedmem from nox.sharedmem import SharedBuffer nox.sharedmem.unlink("/noxdocdemo") b: SharedBuffer = nox.sharedmem.open("/noxdocdemo", 4096) b.lock() b.write_int(0, 12345) b.write_str(16, "hello") b.unlock() c: SharedBuffer = nox.sharedmem.open("/noxdocdemo", 4096) c.lock() print(c.read_int(0), c.read_str(16, 5)) c.unlock() c.close() b.close() nox.sharedmem.unlink("/noxdocdemo") ``` ```output 12345 hello ``` ## Notes - Always `unlink` a segment you created when it is no longer needed, otherwise it persists after the program exits. - The segment's name is global to the machine: use a distinctive prefix and treat the segment as untrusted input from other local processes. --- # nox.mem Bulk typed-pointer memory operations and volatile access — a friendly facade over `lowlevel` and `ptr[T]`, so ordinary code (device drivers, kernels, FFI buffers) does not need to write its own `lowlevel` loops. Pure Nox with no operating-system or libc dependency, so it works in freestanding programs. ```text import nox.mem ``` **Capability:** none. Callers still need `lowlevel` to *obtain* pointers ([Foreign functions](https://noxlang.com/docs/language/ffi/#raw-pointers)). ## Functions | Function | Description | |---|---| | `copy(dst, src, count)` | copies `count` elements of type `T` from `src` to `dst`; the regions must **not overlap** | | `move(dst, src, count)` | like `copy`, but correct for overlapping regions (copies backwards when `dst` is after `src`) | | `set(dst, value, count)` | stores `value` into `count` consecutive elements | | `read_volatile(p)` | loads from `p` in a way the optimiser may not remove or reorder (memory-mapped registers) | | `write_volatile(p, value)` | stores through `p` likewise | All are generic over the element type: `ptr[i32]`, `ptr[u8]`, … Counts are element counts, not bytes. There is **no bounds checking**: you are responsible for the regions. ```nox import nox.mem extern def malloc(n: int) -> ptr from "c" extern def free(p: ptr) -> None from "c" def demo() -> int: total: int = 0 lowlevel: raw: ptr = malloc(64) a: ptr[i32] = ptr[i32](ptr_to_int(raw)) b: ptr[i32] = ptr[i32](ptr_to_int(raw) + 32) nox.mem.set(a, i32(7), 4) nox.mem.copy(b, a, 4) nox.mem.write_volatile(b, i32(9)) total = int(nox.mem.read_volatile(a)) + int(nox.mem.read_volatile(b)) + int(ptr_read(ptr_offset(b, 3))) free(raw) return total print(demo()) ``` ```output 23 ``` ## Allocation counters `nox.mem.stats() -> MemStats` reports how many ARC-managed heap blocks (`str`, `list`, `dict`, class instances) were allocated and freed. The counters cost one boolean check on the allocation path while off; the **first** `stats()` call starts counting and returns zeros, later calls return what was counted since. Call it once before the code you want to measure, then again and read the difference: ```nox import nox.mem nox.mem.stats() # starts counting # ... code under measurement ... s: nox.mem.MemStats = nox.mem.stats() print(s.allocations, s.frees, s.live) ``` | Field | Meaning | |---|---| | `allocations` | blocks allocated since counting started (blocks reused from the internal pool count too) | | `frees` | blocks freed since counting started | | `live` | `allocations - frees`; can be negative if a block allocated before counting started is freed during measurement | | `bytes_allocated` | total payload bytes of those allocations | Objects the compiler promotes to the stack or an arena never reach the heap and are not counted. ## Notes - `detach(x)` of a `list[T]` yields a pointer **16 bytes before the first element** (the historical "header pointer" contract: `ptr_add(detach(xs), 16)` is element 0, also after the list has grown). [`nox.buffer`](https://noxlang.com/docs/stdlib/buffer/) hides that detail for byte buffers. - This module is part of the same [trust boundary](https://noxlang.com/docs/language/ffi/#the-trust-boundary) as `lowlevel`: a wrong pointer is a crash or corruption. --- # nox.reflect Queries the metadata that [decorators](https://noxlang.com/docs/language/decorators/) record, and class constructor signatures — the raw material for frameworks that wire routes, controllers and dependencies from annotations. Decorators never change behaviour on their own; `nox.reflect` is how a framework reads what they say. ```text import nox.reflect ``` **Capability:** none. The complete function table, a worked example and the meaning of each record kind are on the [Decorators and reflection](https://noxlang.com/docs/language/decorators/#reading-metadata-noxreflect) page. In summary: | Group | Functions | |---|---| | Records | `decorator_count()`, `decorator_kind(i)`, `decorator_name(i)`, `decorator_target_name(i)`, `decorator_owner(i)` | | Arguments | `decorator_arg_count(i)`, `decorator_arg_kind(i, j)`, `decorator_arg(i, j)`, `decorator_arg_int(i, j)`, `decorator_arg_bool(i, j)`, `decorator_arg_list_len(i, j)`, `decorator_arg_list_item(i, j, k)` | | Signatures | `decorator_param_count(i)`, `decorator_param_name(i, k)`, `decorator_param_type(i, k)`, `decorator_return_type(i)` | | Classes | `class_count()`, `class_name(i)`, `class_index(name)`, `class_init_param_count(i)`, `class_init_param_name(i, k)`, `class_init_param_type(i, k)` | | Handlers | `decorator_is_handler(i)`, `decorator_handler(i)`, `router_from_decorators()` | ```nox import nox.reflect @route("/hello", 3, True) def hello(a: int) -> int: return a print(nox.reflect.decorator_count(), nox.reflect.decorator_name(0), nox.reflect.decorator_target_name(0)) print(nox.reflect.decorator_arg(0, 0), nox.reflect.decorator_arg_int(0, 1), nox.reflect.decorator_arg_bool(0, 2), nox.reflect.decorator_param_name(0, 0)) print(nox.reflect.decorator_kind(0), nox.reflect.decorator_arg_kind(0, 1), nox.reflect.decorator_return_type(0)) ``` ```output 1 route hello /hello 3 True a 0 1 int ``` Record kinds: `0` function, `1` class, `2` method; argument kinds: `0` string, `1` int, `2` bool, `3` string list. --- # nox.native The Nox side of the [Nox Native Interface](https://noxlang.com/docs/apis/nni/): load a native plugin (a shared library exporting `nox_plugin_init_v1`), call the functions it registered, and receive events from its threads. This is the **raw** interface; for manifests, typed signatures and capability consent use [`nox.plugin`](https://noxlang.com/docs/stdlib/plugin/), which is built on it. ```text from nox.native import open_plugin, Plugin, Event, NativeError ``` **Capability:** none registered (hosted programs only). ## Functions and methods | Member | Description | |---|---| | `open_plugin(path)` | loads the library at `path`, runs `nox_plugin_init_v1`, returns a `Plugin`; raises `NativeError` if it cannot be loaded or initialisation fails | | `Plugin.arg_int(v)`, `arg_float(v)`, `arg_bool(v)`, `arg_str(v)` | pushes the next argument for the next call | | `Plugin.clear_args()` | discards pushed arguments | | `Plugin.call(name)` | calls the native function `name` with the pushed arguments, ignoring the result | | `Plugin.call_int(name)`, `call_float(name)`, `call_bool(name)`, `call_str(name)` | calls and returns the result as that type | | `Plugin.call_int_list(name)`, `call_str_int_dict(name)` | NNI v1.x: copies a host-built `list[int]` or `dict[str, int]` into a Nox value | | `Plugin.result_kind()` | the kind of the last result (`VALUE_NONE`=0, `VALUE_INT`=1, `VALUE_FLOAT`=2, `VALUE_BOOL`=3, `VALUE_STRING`=4, `VALUE_BYTES`=5) | | `Plugin.poll_event()` | the next queued event from a native thread, or `None` | | `Plugin.wait_event(timeout_ms)` | waits up to `timeout_ms` for an event; `None` on timeout | | `Plugin.close()` | calls `nox_plugin_shutdown_v1` (if exported) and unloads the library | An `Event` carries `kind` (the number the plugin chose), `value_kind`, `int_value`, `float_value` and `str_value`. A native function that reports failure raises `NativeError` with the plugin's message; calling an unregistered name raises `NativeError`. Arguments are not type-checked here — the plugin must validate them (the manifest-based [`nox.plugin`](https://noxlang.com/docs/stdlib/plugin/) checks them for you). ```nox from nox.native import open_plugin, Plugin, NativeError def try_load(path: str) -> str: try: p: Plugin = open_plugin(path) p.close() return "loaded" except NativeError as e: return "not loaded" print(try_load("/definitely/not/a/plugin.so")) ``` ```output not loaded ``` See the [NNI guide](https://noxlang.com/docs/apis/nni-guide/) for complete plugins in C, Zig and Rust. ## Trust A plugin runs with full native authority ([Security](https://noxlang.com/docs/reference/security/)). --- # nox.plugin The Nox side of the [Plugin API](https://noxlang.com/docs/apis/plugin-api/): load a native plugin through a `nox-plugin.json` manifest, with API-version negotiation, platform library selection, typed call checking, a registration cross-check and capability consent. It is a thin, pure-Nox layer over [`nox.native`](https://noxlang.com/docs/stdlib/native/). ```text from nox.plugin import load_plugin, LoadedPlugin, PluginManifest, FunctionSpec, PluginError ``` **Capability:** none registered (hosted programs only). The complete specification — the manifest schema, types, capabilities, errors and lifecycle — is on the [Plugin API](https://noxlang.com/docs/apis/plugin-api/) page. This page lists the module's surface. ## Constants and functions | Item | Description | |---|---| | `PLUGIN_API_VERSION` | the Plugin API version this runtime implements (`1`) | | `load_plugin(manifest_path, allowed)` | reads and validates the manifest, checks every declared capability against `allowed` (`"*"` grants all), loads the library, runs init, cross-checks the registered functions and returns a `LoadedPlugin` | | `read_manifest(manifest_path)` | parses and validates a manifest and returns a `PluginManifest` without loading anything | | `host_platform()` | the platform key (`"macos-arm64"`, `"linux-x64"`, `"linux-arm64"`, `"linux-riscv64"`, `"windows-x64"`) | | `capability_granted(cap, allowed)` | whether `cap` is permitted by the list `allowed` | | `obj_get(v, key)`, `dir_of(path)`, `kind_ok(kind)`, `return_ok(kind)`, `require_string(v, key, what)` | internal helpers used by the manifest reader; they are public but not part of the stable API. `kind_ok` accepts argument types. `return_ok` also accepts `"list"` (`list[int]`) and `"dict"` (`dict[str, int]`) as return types only | ## Classes | Class | Description | |---|---| | `PluginManifest` | the validated manifest: `name`, `version`, `plugin_api`, `library` (the resolved path for this platform), `capabilities`, `functions` | | `FunctionSpec` | one declared function: `name`, `args` (a list of type names, possibly ending in `"..."`), `returns` | | `LoadedPlugin` | a loaded plugin: `manifest`; `has_function(name)`, `spec_of(name)`; `arg_int/arg_float/arg_bool/arg_str`; `call`, `call_int`, `call_float`, `call_bool`, `call_str`, `call_int_list`, `call_str_int_dict`; `poll_event`, `wait_event`; `clear_args`, `reset_args`, `finish`, `check_call`; `shutdown`. A call whose manifest return type does not match raises `PluginError` | | `PluginError` | raised for manifest, version, capability, registration and call-signature problems | ```nox from nox.plugin import read_manifest, host_platform, capability_granted, PluginError, PLUGIN_API_VERSION print(PLUGIN_API_VERSION, host_platform() != "", capability_granted("net", ["fs.read"]), capability_granted("net", ["*"])) try: read_manifest("/no/such/nox-plugin.json") except PluginError as e: print("no manifest") ``` ```output 1 True False True no manifest ``` For the end-to-end flow (building a plugin and loading it) see the [NNI guide](https://noxlang.com/docs/apis/nni-guide/). --- # nox.hpy Load an aHPy Universal package (`nox-hpy-host-v1`). The facade opens the manifest, checks the artifact for this machine, and calls the extension. It never hands out a raw pointer. ```text from nox.hpy import Module, Object, load_package ``` **Capability:** filesystem. This is a preview profile, not part of the stable 2.x library surface. A package's native code runs with the process's own privileges. ## Functions | Function | Description | |---|---| | `host_profile()` | the profile string `nox-hpy-host-v1` | | `host_abi()` | the ABI string `universal` | | `load_package(root)` | reads `root/nox-hpy.json`, verifies the artifact for this target, and returns an open `Module` | ## `Module` `load_package` returns a `Module`. Close it with `close`, or use `with`, which calls `__enter__` and `__exit__`. A closed module raises `HPyError`. One module is not shared across operating-system threads. Calls run on the caller's fiber. | Method | Description | |---|---| | `call_int(name)` | calls `name` with no arguments and returns an `int` | | `call_int_arg(name, arg)` | calls `name` with one `int` | | `call_bool(name)` | returns a `bool` | | `call_float(name)` | returns a `float` | | `call_float_arg(name, arg)` | calls `name` with one `float` | | `call_str(name)` | returns a `str` | | `call_str_arg(name, arg)` | calls `name` with one `str` | | `call_bytes(name, arg)` | `arg` and the result are `list[int]` values in `0..255`, including embedded zeros. The manifest must list the `bytes` capability | | `call_int_keyword(name, key, arg)` | one keyword argument. The manifest must list `call-keywords` | | `call_object(name)` | returns an `Object` | | `construct(class_name, arg)` | calls the named constructor with one `int` and returns an `Object` | ## `Object` An `Object` is an opaque extension value. `close` releases it. `call(name)` and `call_int(name, arg)` invoke a method and return an `int`. ```nox import nox.hpy print(nox.hpy.host_profile()) print(nox.hpy.host_abi()) ``` ```output nox-hpy-host-v1 universal ``` --- # nox.test Assertions and a result-collecting test suite. `noxc test` runs every `*_test.nox` file (see [Testing](https://noxlang.com/docs/tools/testing/)); inside those files use the functions below. ```text import nox.test from nox.test import TestSuite ``` **Capability:** none. ## Assertions — stop at the first failure Each function raises an exception when the check fails, ending the test program (and failing `noxc test`). | Function | Description | |---|---| | `assert_eq_int(actual, expected, msg)` | `int` equality | | `assert_eq_str(actual, expected, msg)` | `str` equality | | `assert_eq_float(actual, expected, msg)` | exact `float` equality | | `assert_true(cond, msg)` | `cond` must be `True` | `msg` names the check in the failure report. (There is one function per type because Nox has no overloading.) ## `TestSuite` — collect results, keep going A suite records every check instead of raising, so later code — including cleanup — always runs, and it can emit a JUnit XML report for continuous-integration systems. | Member | Description | |---|---| | `TestSuite(name)` | an empty suite | | `check_eq_int(case_name, actual, expected)`, `check_eq_str(...)`, `check_eq_float(...)` | records a pass or a failure | | `check_true(case_name, cond)` | records a pass or a failure | | `total_count()` | number of checks recorded | | `all_passed()` | whether every check passed | | `write_junit_xml(suite, path)` | writes the results as JUnit XML to `path` | ```nox import nox.test from nox.test import TestSuite suite: TestSuite = TestSuite("demo") suite.check_eq_int("add", 1 + 1, 2) suite.check_eq_str("s", "a", "a") suite.check_eq_float("f", 1.5, 1.5) suite.check_true("t", True) print(suite.total_count(), suite.all_passed()) suite.check_eq_int("bad", 1, 2) print(suite.total_count(), suite.all_passed()) nox.test.assert_eq_int(3, 3, "ok") try: nox.test.assert_eq_int(3, 4, "values") except Exception as e: print("assertion failed") ``` ```output 4 True 5 False assertion failed ``` ## Notes - Test files are ordinary programs: they print what they like and **fail by raising**. A file that finishes normally passes. - `nox.test` defines its own `AssertionError` class; catch assertion failures with `except Exception` (the built-in `assert` statement raises the prelude's `AssertionError`). --- # noxc — the compiler and project tool `noxc` is the single command that checks, compiles, runs, formats, tests and packages Nox programs. This page is the complete reference; see the [tutorial](https://noxlang.com/docs/tutorial/01-hello/) for a gentle introduction. ```text noxc compile the file to an executable (shortcut for build) noxc [options] ``` > **Message language.** `noxc --help` follows your locale (`LC_ALL`, `LC_MESSAGES`, `LANG`; Turkish if the value starts with `tr`, English otherwise). Compiler diagnostics, standard-library exception text and every other `noxc` status line are English. Their *kind* is stable; their wording is not. Branch on exit codes, not on message text. ## Exit status `0` on success. `1` for any failure: a syntax or type error, a failed build, a failing test, an uncaught exception in a program started by `run` (the program's own exit status is returned when it exits normally). ## Building and running | Command | Description | |---|---| | `noxc build [options] ` | compile to a native executable named after the file (or `-o`) | | `noxc sign register [--key ] [--label ]` | bind a signing key's public half to your registry account (needs `noxc login`); the registry then accepts signed attestations from that key | | `noxc sign check [dir] [--require]` | for every dependency in `nox.lock`, fetch its registry attestation and re-verify the signature locally: `signed (trusted key)`, `signed (key not trusted locally)`, `UNSIGNED`, `MISMATCH` (attestations exist, but not for the locked commit), `BAD SIGNATURE`, `KEY REVOKED`; exit 1 on a bad verdict, and with `--require` also on `UNSIGNED` | | `noxc sbom [dir] [-o file]` | write a deterministic CycloneDX 1.5 SBOM of `nox.json` + `nox.lock` (each locked dependency with its purl and commit; `nox:native` flags `extern def` / `lowlevel` (a declared `bin` executable is reported separately as `nox:bin` and does not make a package native), found by a static scan of the cached sources; nothing is executed) | | `noxc sign keygen `, `sign lock --key [dir]`, `sign trust `, `sign revoke `, `sign verify [dir]` | Ed25519 signing of `nox.lock` ([ADR-011](https://noxlang.com/docs/internals/adr/011-lock-signing/)); `verify` exits 0 only for a valid signature by a trusted, non-revoked key | | `noxc run --sandbox [--allow-net] [--allow-write=DIR] [--allow-read=DIR] ` | run the compiled program under an OS sandbox: no network, writes only to `$TMPDIR` ([ADR-010](https://noxlang.com/docs/internals/adr/010-sandbox/)); macOS `sandbox-exec`, Linux `bwrap` | | `noxc run [options] [args…]` | compile into `$NOX_HOME/cache/run/` (keyed by path, source contents, the `noxc` binary, `noxrt.o`, and the installed stdlib) and run; a matching cache entry is not rebuilt. Everything after `--` goes to the program (`nox.os.arg(1)`, …) | | `noxc check [options] ` | parse and type-check only — fast, no code generation. Exit status 0 means "no type errors" | | `noxc test [name\|path …]` | run every `*_test.nox` under the current directory, or only those whose file name contains `name`, or the given directory. A compile error is a failed file; the rest still run ([Testing](https://noxlang.com/docs/tools/testing/)) | | `noxc expand ` | print the decorator metadata the compiler extracted from the file | | `noxc bindgen --lib ` | generate Nox `extern def` bindings (and a C shim where needed) from a C header ([bindgen](https://noxlang.com/docs/tools/bindgen/)) | | `noxc explain [--release] ` | print each local variable's allocation decision (stack, arena or reference-counted) and why ([Memory](https://noxlang.com/docs/language/memory/#seeing-the-compilers-decisions-noxc-explain)) | | `noxc fmt ` | rewrite the file in the standard style, in place ([Formatter](https://noxlang.com/docs/tools/formatter/)) | ### Build options | Option | Meaning | |---|---| | `-o ` | output file name (`build` only) | | `--backend ` | code-generation backend. Default `llvm`; `qbe` is chosen automatically for freestanding builds, `--emit-asm`, `-g`, and when neither `clang` nor `zig` is installed. Mobile targets stay on LLVM ([Backends](https://noxlang.com/docs/tools/backends/)) | | `--release` | the old name for `--backend llvm` | | `--profile ` | which standard-library modules may be imported (default `hosted`; [Freestanding](https://noxlang.com/docs/tools/freestanding/)) | | `--target ` | cross-compile. Desktop hosted names build through LLVM when `zig` is on `PATH` (QBE otherwise, or with `--backend qbe`): `macos-arm64`, `macos-x64`, `linux-x64`, `linux-arm64`, `linux-riscv64`, `windows-x64`. Freestanding: `x86_64`, `aarch64`, `riscv64`. Mobile names are LLVM libraries: `ios-arm64`, `ios-simulator-arm64`, `android-arm64`, `android-x64`. `wasm32-wasi` and `wasm32-freestanding` are LLVM-only WebAssembly modules ([WebAssembly](https://noxlang.com/docs/tools/wasm/)) Cross-building needs `zig` on `PATH`. With `--backend qbe`, `windows-x64` also needs the patched `qbe` that ships in the release archives (stock QBE 1.3 fails with `invalid operand for instruction`; `scripts/build_qbe.sh` builds the patched one) | | `--asyncify` | with `--target wasm32-wasi` or `wasm32-freestanding`: real fibers through Binaryen Asyncify (needs `wasm-opt`) instead of the nested-run simulation ([WebAssembly](https://noxlang.com/docs/tools/wasm/)) | | `--threads` | with `--target wasm32-wasi`: real parallel M:N through shared memory and atomics (includes the Asyncify fibers; needs `wasm-opt` and `node`) ([WebAssembly](https://noxlang.com/docs/tools/wasm/)) | | `--emit-asm` | stop after producing assembly (`.s`). Not valid for a mobile target | | `--emit-obj`, `--emit-static-lib`, `--emit-shared-lib` | mobile library output. iOS is a static archive. Android's packaged form is `--emit-shared-lib`. One flag only | | `-g` | emit DWARF line tables for debugging — QBE backend only, selected automatically ([Debugging](https://noxlang.com/docs/tools/debugging/)) | | `--dump`, `-v` | verbose output: dump the AST and compiler decisions | A bare `noxc file.nox` builds `file`; it does not run it (use `noxc run`). ## Projects and packages | Command | Description | |---|---| | `noxc init [name]` | scaffold a project (`nox.json` and `main.nox`) in `name/` or the current directory | | `noxc fetch` | download the dependencies listed in `nox.json` into the cache and record exact commits in `nox.lock` | | `noxc update` | re-resolve dependencies to the latest commits of their refs and rewrite `nox.lock` | | `noxc add [repo] [--ref ]` | add a dependency to `nox.json` (looks `repo` up in the index when omitted; `ref` defaults to `master`) | | `noxc delete ` | remove a dependency from `nox.json` and `nox.lock` | | `noxc search ` | search the central index; `noxc search ` searches another index | | `noxc login [--no-browser]` | sign in to the registry with GitHub (needed to publish); saves a token in `~/.nox/credentials` | | `noxc logout` | delete the local token and revoke it on the server | | `noxc whoami` | show which GitHub account you are signed in as | | `noxc publish [--ref ] [--description ] [--tags a,b,c] [--source nox\|c\|cpp\|rust\|go\|zig\|mixed]` | submit package metadata to the central index (requires `noxc login`; awaits admin approval) | | `noxc install [--ref ] [--force]` | globally install a package that declares a `bin` entry point. `github.com/org/name@v1.2.3` sets the ref; `--ref` overrides it. `git@host:path` is not split on the first `@` | | `noxc refresh [command] [--force]` | update globally installed packages (all of them without an argument). A package whose remote commit is unchanged, built by the same `noxc`, is reported as *up to date* and skipped (one `git ls-remote`, no clone or build); `--force` rebuilds anyway. After `noxc upgrade`, packages are rebuilt once with the new compiler | | `noxc uninstall ` | remove a globally installed command | | `noxc list` | list globally installed packages | | `noxc cache prune [--dry-run] [--all]` | delete stale package-cache directories and old/oversized `noxc run`/`noxc test` binaries (`--all` empties the run cache) | Details: [Packages](https://noxlang.com/docs/tools/packages/) and [noxpkg](https://noxlang.com/docs/tools/noxpkg/). ## Maintenance | Command | Description | |---|---| | `noxc upgrade [--check] [vX.Y.Z]` | update `noxc` itself to the highest stable release (or a given version); `--check` only reports. The version is the highest `vX.Y.Z` in the release list (drafts and pre-releases are skipped), not GitHub's "latest" flag, and `noxc upgrade` never downgrades without an explicit version | | `noxc version`, `noxc --version`, `-V` | print the version | | `noxc --help`, `-h` | print the help screen | ## Progress output Commands that wait on the network or the build (`upgrade`, `install`, `refresh`, `fetch`, `update`, `add`, `search`, and automatic dependency fetching during `build`/`run`) report what they are doing on stderr, one `==>` line per stage: ```text ==> Checking the latest release ... done ==> Upgrading noxc to v2.0.135 (macos-arm64) ==> Downloading nox-lang-v2.0.135-macos-arm64.tar.gz (19.8 MB) [===========> ] 48% 9.5 MB / 19.8 MB 4.1 MB/s eta 2.5s ==> Verifying checksum ... done ``` In a terminal the download line is a live bar (percentage, size, speed, estimated time) that is replaced by a summary (`19.8 MB in 4.8s (4.1 MB/s)`) when it finishes. When stderr is not a terminal (a pipe, a file, CI) or `TERM=dumb`, no bar is drawn: you get only the stage lines and the summary, so logs stay readable. A stage that finishes in under a tenth of a second omits its duration. ## Capability restrictions `--allow-net` also applies to `noxc run --target wasm32-freestanding-asyncify`: it gives the module the host's `fetch` so `nox.http` works; without it the client raises `HttpCapabilityError` (see [WebAssembly](https://noxlang.com/docs/tools/wasm/#network-the-noxhttp-client-through-the-hosts-fetch-wasm32-freestanding---asyncify)). `--allow-process` and `--allow-serve` likewise give a `wasm32-freestanding-asyncify` module the host's child-process and HTTP-server capabilities (off by default; see [WebAssembly](https://noxlang.com/docs/tools/wasm/)). `--vfs-dir ` (with `noxc run --target wasm32-freestanding`) loads a directory into the module's virtual file system before the run and writes it back on exit, so `nox.fs` and file-based `nox.sqlite` persist; see [WebAssembly](https://noxlang.com/docs/tools/wasm/#persistent-virtual-file-system). `--deny-capability ` (also `--deny-capability=`, valid with every subcommand) makes the compiler reject any program that imports a module needing one of the listed capabilities, or calls a function marked `@capability.requires` for it: `filesystem`/`fs`, `network`/`net`, `clock`, `entropy`/`random`, `threads`, `process`, `shared_memory`/`shm`, `libc_math`, `dynamic_code`/`dynamic`. It is meant for environments that compile untrusted code (a playground, a CI sandbox) and works on every target; see [WebAssembly](https://noxlang.com/docs/tools/wasm/#capability-model-and---deny-capability). ## Scripts A Nox file can be run like a script. `noxc run` compiles it once, keeps the binary in the run cache (keyed by the source, the compiler and the standard library, so editing the file recompiles it and an unchanged file starts immediately) and runs it: ```nox #!/usr/bin/env -S noxc run import nox.os print("hello,", nox.os.arg(1)) ``` ```sh chmod +x greet.nox ./greet.nox world # hello, world ``` Everything after the file path is passed to the program, like `python script.py a b`; a leading `--` is optional and accepted for older invocations. Compiler and sandbox options (`--backend`, `--sandbox`, ...) go **before** the file path, so they never reach the program. `env -S` is needed for the two-word shebang on Linux; macOS accepts it too. The plain form `#!/usr/bin/env noxc` does not run the script: a bare `noxc file.nox` only builds it. ## Environment `NOX_HOME` (the data directory, default `~/.nox`), `NOX_INDEX_URL`, `NOX_PUBLISH_API_BASE`, `NOX_UPGRADE_API_BASE` and others are listed in [Environment variables](https://noxlang.com/docs/reference/environment/). ## Examples ```sh noxc run main.nox a b c # run with arguments (everything after the file goes to the program) noxc build -o app main.nox # produce ./app noxc check main.nox # type-check only noxc build --backend qbe main.nox # use the QBE backend noxc search http # find packages noxc add nyx # add a dependency by name noxc upgrade --check # is there a newer noxc? ``` ## Tool locations `noxc` finds its runtime object (`noxrt.o`) and standard library next to the executable (`/lib/noxrt.o`, `/lib/nox/stdlib`), so an installed `noxc` works from any directory. A release archive also contains `noxlsp` (the [language server](https://noxlang.com/docs/tools/lsp/)) and, on Linux and macOS, a bundled `qbe`. Set `NOX_RESOURCE_DIR` to point at a different resource directory. --- # Compilation backends Nox compiles the typed program to one of two back ends, which are tested against the same corpus and must produce **identical program output**. | | **LLVM** (default) | **QBE** | |---|---|---| | Pipeline | typed IR → LLVM IR (`.ll`) → `clang -O2` (or `zig cc -O2`) → native | typed IR → QBE IL (`.ssa`) → `qbe` → assembly → `cc` → native | | Code speed | faster (roughly 1.5× C on a mixed benchmark suite) | good (roughly 1.7× C) | | Compile speed | fast | fast | | Scheduler | **multi-core M:N work-stealing** with atomic reference counts | the same M:N scheduler (since 2.1.111); atomic reference counts only in programs that use tasks or threads | | Needs | `clang` or `zig` on `PATH` | the bundled `qbe`, and a C compiler for linking | | Debug info (`-g`) | no | yes (DWARF line tables) | | `--target` cross-compile (desktop) | yes, needs `zig` (`zig cc -O2 -target`) | yes | | `--emit-asm`, freestanding | no | yes | ## How the backend is chosen `--backend llvm` and `--backend qbe` always win. Otherwise (`auto`): 1. **freestanding** builds, `--emit-asm` and `-g` → QBE. A desktop `--target` (`macos-arm64`, `macos-x64`, `linux-x64`, `linux-arm64`, `linux-riscv64`, `windows-x64`) goes to LLVM when `zig` is on `PATH` (the `.ll` file is cross-linked with `zig cc -O2 -target `, so cross-built programs run at `-O2` speed and a Windows `.exe` does not depend on QBE's `amd64_win` back end), otherwise to QBE. Mobile names (`ios-arm64`, `ios-simulator-arm64`, `android-arm64`, `android-x64`) and `wasm32-wasi`/`wasm32-freestanding` stay on LLVM; `--backend qbe` is an error; 2. on **Windows**, LLVM when `zig` is installed (it links with `zig cc -target x86_64-windows-gnu`), otherwise QBE with MinGW `cc`; 3. on macOS and Linux, LLVM when `clang` or `zig` is on `PATH`; with neither, QBE and a one-line note; 4. otherwise LLVM. Asking for LLVM together with `-g`, `--emit-asm` or freestanding is an explicit error rather than a silent switch. ### The C driver The LLVM path needs a C toolchain driver to optimise and link the `.ll` file. `noxc` tries `clang` first, then `zig cc` (Zig's bundled clang and LLD), so a machine with only Zig installed works. The QBE path links with the system `cc` (or `zig cc` for cross targets). ## What is the same Both back ends implement exactly the language in the [reference](https://noxlang.com/docs/language/): - integer overflow: plain `int` wraps, fixed-width integers trap, on **both**; - argument evaluation order, exception semantics, `with`/`defer`/`finally` cleanup order; - program output, including float formatting. ## What differs (and how code should treat it) | Difference | Guidance | |---|---| | Parallelism: tasks run on a worker pool (LLVM) or interleave on one thread (QBE) | write tasks that are correct under both; communicate with channels | | `spawn`/`nox.thread.start` argument types are wider on LLVM | stay within the QBE set for portable code ([Concurrency](https://noxlang.com/docs/language/concurrency/#the-scheduler)) | | `-g`, `--emit-asm`, freestanding exist only on QBE | choose `--backend qbe` for those. Desktop `--target` works on both. Mobile targets and `wasm32-*` are LLVM | | speed | LLVM is faster; neither is a semantic choice | Both back ends are run over the entire golden corpus on every change, and a differential test compares their output. ## Intermediate files `noxc build` leaves `file.ll` (LLVM) or `file.ssa` and `file.s` (QBE) next to the executable; they are useful for inspecting the generated code and are safe to delete. ## Platforms See [Platforms](https://noxlang.com/docs/reference/platforms/) for which combinations are tested. --- # Packages and dependencies A Nox *package* is an ordinary project in a Git repository. A project lists the packages it needs in `nox.json`; `noxc` fetches them, pins exact commits in `nox.lock`, and compiles them into your program together with your own code. ## `nox.json` ```json { "name": "myapp", "version": "0.1.0", "entry": "main.nox", "bin": { "name": "myapp", "path": "main.nox" }, "requires": [ { "alias": "nyx", "repo": "github.com/mburakmmm/nyx", "ref": "v0.21.0" }, { "alias": "local", "repo": "/abs/path/to/pkg", "ref": "main", "require_signed_commit": false } ] } ``` | Field | Meaning | |---|---| | `name` | the project's name | | `version` | the project's version (informational) | | `entry` | the entry file (default `main.nox`) | | `bin` | optional `{name, path}`: makes the package installable as a global command ([below](#global-installs)) | | `requires[]` | the dependencies | Each dependency has: | Field | Meaning | |---|---| | `alias` | the name you import it by (`import nyx.app` loads module `app` of the package). Aliases must be unique, and `nox` is reserved for the standard library | | `repo` | where to get it: `github.com/owner/repo`, another Git host path, or an absolute local directory (for development) | | `ref` | the branch, tag or commit to follow | | `require_signed_commit` | optional; when `true` the resolved commit must carry a valid signature (`git verify-commit`) or the fetch fails | ## `nox.lock` `nox.lock` records, for every dependency, the exact commit its `ref` resolved to: ```json { "packages": [ { "alias": "nyx", "repo": "github.com/mburakmmm/nyx", "ref": "v0.21.0", "resolved": "1e7388a908aa2ca0fcfc2810f78ad88fbff82d77" } ] } ``` `build`, `run` and `test` always use the locked commit, never re-resolving a branch silently — builds are reproducible. **Commit `nox.lock`** to version control. ## Commands ```sh noxc init myapp # scaffold nox.json + main.nox noxc search http # query the central index noxc add nyx # look "nyx" up in the index and add it (ref defaults to `master`; pass --ref to pin a tag) noxc add nyx github.com/mburakmmm/nyx --ref v0.21.0 noxc fetch # download dependencies, write nox.lock noxc update # move every dependency to the latest commit of its ref noxc delete nyx # remove it from nox.json and nox.lock noxc cache prune --dry-run # show stale cached checkouts that would be deleted ``` Downloaded checkouts live in `$NOX_HOME/pkg/mod///` (default `~/.nox`); the cache is content-addressed by commit, so several projects share one copy. `cache prune` deletes checkouts no lock file refers to (install, refresh and upgrade also prune automatically). ## Using a dependency ```nox-fragment import nyx.app # module "app" of the package aliased "nyx" from nyx.config import Config ``` All modules of all packages compile together into one program. Packages may depend on packages; the whole graph is resolved and locked. ## Global installs A package that declares a `bin` entry can be installed as a command: ```sh noxc install nyx # build and install into ~/.nox/bin noxc list # list installed commands noxc uninstall nyx # remove the command ``` Add `~/.nox/bin` to your `PATH`. `install` accepts a package name from the index or a repository. ## Publishing a package 1. Put your project in a public Git repository with a `nox.json` and a tag for each release. 2. Sign in once with your GitHub account (see [noxpkg](https://noxlang.com/docs/tools/noxpkg/#signing-in-and-publishing)): ```sh noxc login ``` 3. Submit its metadata to the central index: ```sh noxc publish github.com/you/yourpkg --ref v1.0.0 --description "What it does" --tags web,http ``` 4. A registry administrator reviews and approves the submission; once approved, `noxc search` and `noxc add` find it. The package page shows you as its publisher, and the name is yours for future releases. `publish` sends **metadata only** (name, repository, ref, description, tags, source label); no code is uploaded — consumers fetch from your repository. See [noxpkg](https://noxlang.com/docs/tools/noxpkg/) for the service. **Source label.** Every published package carries a *source language* label shown on its card and page (and filterable on the packages page): `nox` (pure Nox), `c`, `cpp`, `rust`, `go`, `zig` or `mixed` (two or more native languages). It is the **publisher's declaration** — set `"source": "c"` in `nox.json` or pass `--source c`. `noxc publish` scans your project tree (skipping `tests/`, `examples/`, `docs/`, benchmarks and build output) and **refuses to publish when the declaration contradicts what it finds** (for example `"source": "nox"` with a `native/shim.c`). With no declaration, the scan result is used. The registry stores and displays the label; it does not clone or scan your repository. ## Security A package can contain `extern def` declarations (native code) and build steps run on your machine, so **adding a dependency means trusting it** — and everything it depends on. The lock file protects against a moved tag; `require_signed_commit` adds signature verification; neither audits behaviour. There is no sandbox. Read the code of what you depend on and see [Security](https://noxlang.com/docs/reference/security/). --- # noxpkg — the central package index **noxpkg** is the registry service behind `noxc search`, `noxc add` and `noxc publish`. It is deliberately simple: a JSON *index* of package metadata (name, repository, description, tags) and a moderated *submission* queue. It does **not** host code — packages live in their own Git repositories. The public instance is at ****. ## The index `GET /index.json` returns the approved packages: ```json { "packages": [ { "name": "nyx", "repo": "github.com/mburakmmm/nyx", "description": "Rails-scoped web framework for Nox", "tags": ["web", "framework"] } ] } ``` The index deliberately carries no `ref`: it is a *discovery* catalogue. Version pinning is the job of your `nox.json` and `nox.lock` ([Packages](https://noxlang.com/docs/tools/packages/)). `noxc search` and `noxc add` read the index from `NOX_INDEX_URL` (default `https://noxpkg.noxlang.com/index.json`); you can search any other index with `noxc search `, and run your own registry by serving a file of the same shape. ## Signing in and publishing Publishing needs an account. Run `noxc login` once: it shows a short code, opens `github.com/login/device` (or prints the address with `--no-browser`), and waits while you approve. `noxc` never talks to GitHub: the registry relays the OAuth *device flow*, checks who you are (your public GitHub profile only, no scopes), and hands back its own API token. Your GitHub token is used once on the server and thrown away. The registry token is saved in `~/.nox/credentials` (`$NOX_HOME/credentials`), readable only by you (mode `0600`); the server keeps only its SHA-256 digest and the token expires after a year. | Command | | |---|---| | `noxc login [--no-browser]` | sign in with GitHub; saves the token | | `noxc whoami` | which account the saved token belongs to (asks the server) | | `noxc logout` | deletes the local token and revokes it on the server | A package **name belongs to whoever submits it first**. Only that account can publish the name again (updates); anyone else gets a `403` that names the owner. A **new package name** or a **change of repository** waits for administrator approval. Publishing again to the same name and the same repository as the account that owns it (a new version, description or tags) needs **no new approval**: the catalogue entry is updated at once and `noxc publish` says `published` instead of `submitted`. Submitting the same pending package again does not add rows to the queue; it updates the one that is waiting. The package page and the administration panel show who published each package (a warning appears when the repository owner differs from the publisher). Packages that were listed before accounts existed belong to the registry administrator's GitHub account. ## Package versions The registry records one **version** per package: the `--ref` given to the last `noxc publish` (a tag such as `v1.2.0`, or a branch such as `main`). It shows on the package card and the package page, appears as `"version"` in `index.json` (older clients ignore the field) and in `noxc search` output. Signed release statements (see `noxc sign`) are listed on the package page under *Releases* with the ref, commit, date and signer. A package published before versions were recorded shows "Version not declared yet" until its publisher publishes again (`noxc publish --ref v1.0.0`). ## Submitting a package `noxc publish [--ref ] [--description ] [--tags a,b,c]` (after `noxc login`) sends `POST /api/publish` with the token in an `Authorization: Bearer` header and this JSON: | Field | Type | Required | | |---|---|---|---| | `name` | string | yes | the package name | | `repo` | string | yes | repository path, e.g. `github.com/you/pkg` | | `ref` | string | no | the tag or branch you are announcing | | `description` | string | no | one line | | `tags` | array of strings | no | search keywords | Without a valid token the endpoint answers `401`. The reply is `{"ok": true, "status": "pending", "id": ...}` when the submission lands in the inbox (it becomes visible in `index.json` only after an administrator approves it in the web UI) and `"status": "published"` when an owner's update to an approved package went live directly. The endpoint is rate-limited and validates its input. ## Running a registry The service is a small Nox program (`services/noxpkg/` in the repository): `main.nox` wires the routes, `handlers_public.nox` serves the index and accepts submissions, `handlers_admin.nox` is the moderation UI (password login with Argon2id, session cookie and CSRF protection), `store.nox` persists the index and inbox as JSON files under `data/`. | Route | Purpose | |---|---| | `GET /` | the public package list | | `GET /index.json` | the machine-readable index | | `POST /api/publish` | submit a package (Bearer token required) | | `POST /api/auth/device/start`, `POST /api/auth/device/poll` | the GitHub device flow that `noxc login` drives | | `GET /api/auth/whoami`, `POST /api/auth/logout` | token owner; revoke the token | | `GET/POST /admin/login`, `GET /admin`, `POST /admin/approve/:id`, `POST /admin/reject/:id`, `POST /admin/index/remove`, `POST /admin/logout` | moderation | Configuration comes from the environment: | Variable | | |---|---| | `NOXPKG_ADMIN_PASSWORD_HASH` | an Argon2id hash of the administrator password — generate one with `noxc run services/noxpkg/scripts/gen_admin_hash.nox -- ''` | | `NOXPKG_SESSION_SECRET` | secret for the signed session cookies | | `NOXPKG_GITHUB_CLIENT_ID` | client id of a GitHub OAuth App with *Device Flow* enabled (no client secret is needed). Without it, `noxc login` answers that GitHub login is not configured | | `NOXPKG_ADMIN_GITHUB` | the administrator's GitHub login; when it signs in, packages that predate accounts are assigned to it | | `NOXPKG_PORT` | listen port (default `8080`) | | `NOXPKG_GITHUB_BASE`, `NOXPKG_GITHUB_API` | where GitHub is reached (for tests; defaults `https://github.com` and `https://api.github.com`) | A `docker-compose.yml` and a Cloudflare Tunnel sidecar are included; persistent data lives in the `data/` volume, which should be backed up regularly (the production deployment snapshots it on a schedule and keeps off-site copies). ## Trust Approval means "the metadata looks legitimate", not "the code is safe". See [Security](https://noxlang.com/docs/reference/security/). --- # Testing `noxc test` finds every file named `*_test.nox` under the current directory, compiles and runs each as its own program, and reports one line per file and a summary. A name argument matches the file name (`noxc test smtp` runs `v18_smtp_test.nox`). A directory limits the walk. One `.nox` path runs that file and returns its exit status. If a file fails to compile, it is reported as failed and the remaining files still run. ```sh noxc test noxc test smtp noxc test tests/http ``` ```text PASSED: /path/mathutil_test.nox 1 passed, 0 failed (1 total) ``` (`PASSED` / `FAILED`; the exit status is the contract: `0` when every file passes, `1` otherwise.) ## Writing tests A test file is an ordinary Nox program that **fails by raising an exception** (or exiting non-zero). Use [`nox.test`](https://noxlang.com/docs/stdlib/test/): ```nox import nox.test def double(n: int) -> int: return n * 2 nox.test.assert_eq_int(double(2), 4, "double(2)") nox.test.assert_true(double(0) == 0, "double(0)") nox.test.assert_eq_str("a" + "b", "ab", "concat") print("all good") ``` ```output all good ``` For many small checks that should all run even when one fails, use a `TestSuite` and write a JUnit report for CI: ```nox-fragment suite: TestSuite = TestSuite("mathutil") suite.check_eq_int("double 2", double(2), 4) suite.check_eq_int("double 3", double(3), 6) nox.test.write_junit_xml(suite, "test-results.xml") if not suite.all_passed(): nox.os.exit(1) ``` ## Importing the code under test Tests import your modules like any other code (`import mathutil`); run `noxc test` from the project root so the project's `nox.json` is found. ## Testing servers and handlers An HTTP handler is just a function: call it with a hand-built `HttpRequest` and assert on the `HttpResponse`: ```nox from nox.http import HttpRequest, HttpResponse import nox.test def handle(req: HttpRequest) -> HttpResponse: return HttpResponse(200, "hi " + req.target, {}) resp: HttpResponse = handle(HttpRequest("GET", "/x", "", {}, "")) nox.test.assert_eq_int(resp.status, 200, "status") nox.test.assert_eq_str(resp.body, "hi /x", "body") print("ok") ``` ```output ok ``` ## Testing the compiler itself The compiler's own suites — golden source→output tests, IR snapshots, differential tests between backends, fuzzing, concurrency torture — are described in [Testing internals](https://noxlang.com/docs/internals/testing/). --- # The formatter `noxc fmt file.nox` rewrites a file **in place** in the standard Nox style. It is a real formatter — it parses the file, preserves comments and blank lines, and prints the syntax tree — so the result does not depend on the input's spacing. ```sh noxc fmt main.nox ``` The command prints nothing on success. It fails (status 1) if the file does not parse; fix the syntax error first. ## What it does - Indents with four spaces and normalises spacing around operators, commas and colons (`x:int=1` → `x: int = 1`, `if x>0 :` → `if x > 0:`, `print( "a" )` → `print("a")`). - Wraps nothing: it never changes line breaks inside an expression you broke over several lines in brackets, and it keeps your blank lines and `#` comments in place. - Prints non-decimal integer literals as decimal (`0xFF` → `255`) and keeps string quoting as written. - Re-creates syntactic sugar faithfully: comprehensions, chained comparisons, f-strings, `str.format`, generator expressions and augmented assignments are printed in the form you wrote them. ```nox x: int = 1 if x > 0: print("a") ``` The formatter is idempotent: formatting a formatted file changes nothing. ## Editors `noxlsp` serves the same formatter as the LSP `textDocument/formatting` request, so "Format Document" in an editor ([Editors](https://noxlang.com/docs/install/editors/)) gives byte-identical results to `noxc fmt`. --- # The language server (noxlsp) `noxlsp` is a [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) server for Nox that speaks JSON-RPC over standard input/output. It ships in the release archive next to `noxc`. ## Capabilities | LSP feature | What you get | |---|---| | `textDocument/publishDiagnostics` | syntax and type errors with exact spans, as you type | | `textDocument/completion` | names in scope, standard-library modules and members | | `textDocument/hover` | the type of the symbol under the cursor | | `textDocument/definition` | go to a definition in this file, or in the file an `import` / `from` names | | `textDocument/references` | uses of the same binding; the innermost scope wins | | `textDocument/rename` | a workspace edit for that binding (the server does not write files itself) | | `textDocument/documentSymbol` | outline of top-level functions, classes and methods | | `textDocument/signatureHelp` | the parameter list of the call under the cursor | | `textDocument/semanticTokens/full` | identifier kinds (function, class, parameter, variable); keywords and strings stay with the TextMate grammar | | `textDocument/inlayHint` | parameter names at call sites; types already written in the source are not repeated | | `textDocument/codeAction` | one fix: replace tab indentation with four spaces | | `textDocument/formatting` | the standard formatter ([Formatter](https://noxlang.com/docs/tools/formatter/)) | Diagnostics come from the same front end as `noxc check`, so editor and command line always agree. Cross-file navigation opens the target file on its own; the compiler's merged module is not used, because that merge shifts spans away from the bytes in the editor. ## Using it Any LSP client works: configure it to run `noxlsp` for `*.nox` files. The VS Code extension does this for you ([Editors](https://noxlang.com/docs/install/editors/)); set `nox.languageServerPath` if `noxlsp` is not on `PATH`. ```sh noxlsp # reads LSP messages on stdin, writes responses on stdout ``` --- # Debugging ## Print-style debugging `print` renders every value structurally — lists, dictionaries, tuples, sets and class instances (`Name(field=value, …)`) — so `print(obj)` is usually enough. [`nox.log`](https://noxlang.com/docs/stdlib/log/) adds timestamps and levels; `assert cond, "message"` documents assumptions and is always on. An uncaught exception ends the program with exit status 1 and a message naming the exception class and the **source line** of the `raise`. Every exception carries `message` and `line`. ## Debug information (`-g`) ```sh noxc build -g -o app main.nox # QBE backend; DWARF line tables ``` `-g` emits DWARF **line tables** (the QBE backend generates them; asking for LLVM together with `-g` is an error). A debugger can then set breakpoints and step by source line. Limits: - **Linux:** breakpoints and stepping work with `gdb`/`lldb`. - **macOS:** the linker drops debug sections from the linked binary, so breakpoints are not verified and the Variables pane stays empty. Names are still in the `.s` from `noxc build -g --emit-asm`. - **Scalar locals** (`int`, `bool`, `float` and the fixed-width integers) declared at the top of a function are named in a `.debug_str` section appended after QBE. QBE has no variable directive and often keeps the value in a register, so a debugger has no frame offset to show the value. - Steps into standard-library code can show the wrong file for the line. VS Code: install the CodeLLDB extension, use `noxc build -g` as the pre-launch task and launch the produced binary; no Nox-specific debug adapter is needed because DAP works from DWARF. ## Inspecting what the compiler did | Tool | Shows | |---|---| | `noxc explain file.nox` | allocation decision (stack / arena / reference-counted) for every local and why | | `noxc expand file.nox` | decorator metadata | | `noxc build` leaves `file.ll` / `file.ssa` | the generated IR | | `noxc build --emit-asm` | the assembly | | `noxc check -v file.nox` | verbose front-end output (AST dump) | ## Runtime switches | Variable | Effect | |---|---| | `NOX_POOL_WORKERS=N` | number of scheduler worker threads (LLVM backend) | | `NOX_STACK_PAINT=1` | measure fiber-stack usage; prints `NOX_STACK_HWM_BYTES=` at exit (useful before deep recursion in tasks) | Debug builds of the runtime report leaked reference-counted allocations at exit ("memory address … leaked"); a clean run prints nothing. ## Crashes and stack overflow Fibers have a guard page: overflowing a task's stack terminates the program instead of corrupting memory. Deep recursion belongs on the main program (OS stack) or an explicit work list. Fixed-width integer overflow and out-of-range conversions terminate with a message naming the type. --- # Freestanding builds Nox can compile programs that run with **no operating system** — kernels, firmware, bootloaders — by linking a freestanding runtime and importing only modules that need no OS services. This page describes the profile, the target model and the allocator interface. > Freestanding builds use the QBE backend. A complete worked example — a bootable x86-64 kernel written in Nox with a physical-memory manager, virtual memory, PCI enumeration, timer interrupts and a shell — is the > separate `nox-kernel-demo` project. ## Building ```sh noxc build --profile freestanding --target x86_64 -o kernel.elf kernel.nox noxc build --profile freestanding --target aarch64 -o kernel.elf kernel.nox noxc build --profile freestanding --target riscv64 --emit-asm kernel.nox # assembly only ``` - `--profile freestanding` restricts imports to modules that need no capability, checked at compile time ([capabilities](https://noxlang.com/docs/stdlib/#capabilities)). `nox.mem`, `nox.bits`, `nox.buffer`, `nox.binary`, `nox.mathx`, `nox.collections`, `nox.strings`, `nox.console`, `nox.json`, `nox.csv` and the other pure modules are allowed; `nox.fs`, `nox.http`, `nox.thread`, `nox.time`'s clock functions and similar are rejected. - **Linked into the freestanding runtime today:** the pure modules above plus `nox.strings`, `nox.json`, `nox.regex`, `nox.base64`, `nox.path` (lexical only; `canonicalize` always fails without a file system) and `nox.random` (seeded from the time-stamp counter on x86_64; call `seed(n)` for reproducible output). **Every module the profile admits links.** Bare-kernel notes: `nox.gzip` runs on a dedicated 768 KiB stack (single core, not re-entrant); `nox.crypto` offers the digests, HMAC and constant-time comparison, but no password hashing that needs entropy or MiB of memory (`argon2`, `scrypt`, `*_hash` return empty; `bcrypt_verify` works); `nox.os` has an in-memory environment, `arg(0)` is `"nox"` and `exit` halts the machine. The same checks run in `scripts/freestanding_survey.py`. - `--target` selects the architecture (`x86_64`, `aarch64`, `riscv64`). All three have a boot chain proven in QEMU (see *Reference boot chains* below); on riscv64 the link step of `noxc build` is not wired yet, so use `--emit-asm` and link it yourself as the reference chain does. Hosted riscv64 is a separate target, `linux-riscv64`. The result is linked with `zig cc` against the freestanding runtime object (`noxrt-freestanding-generic-.o`). ## Reference boot chains (QEMU) | Architecture | Machine | Files | Output / exit | |---|---|---|---| | x86_64 | `q35`, Multiboot1 | `runtime/freestanding/x86_64/` (`boot.S`, `kernel.ld`, `kernel.zig`, `kernel_demo.nox`) | COM1; `isa-debug-exit` | | aarch64 | `virt`, `cortex-a57`, `-kernel` ELF | `runtime/freestanding/aarch64/` | PL011 at `0x09000000`; ARM semihosting `SYS_EXIT_EXTENDED` (`-semihosting`) | | riscv64 | `virt`, `-bios none`, `-kernel` ELF | `runtime/freestanding/riscv64/` | NS16550 at `0x10000000`; SiFive test finisher at `0x100000` | Each directory is a complete, small example: `boot.S` (entry, FPU enable, stack, `.bss` clear), `kernel.ld`, `kernel.zig` (UART sink, halt provider, fiber stack pool, exit) and a demo program whose checkpoints (`Hello Nox`, list/dict/string/class/float/recursion/exception, integer and float `print`) the test `tests/golden/kernel_boot_qemu_test.zig` checks on a real QEMU run (`zig build kernel-boot-qemu-test`; skipped when `qbe` or `qemu-system-` is missing). Notes that cost real debugging time and are worth knowing for your own kernel: - **aarch64 needs the MMU on.** With the MMU off every data access is Device memory and an unaligned access faults, which the generated code does (string copies). `boot.S` builds a one-level identity map (1 GiB device block, 1 GiB normal block) and enables MMU + caches; keep the page table outside the `.bss` range you zero. - **riscv64 RAM starts at `0x80000000`.** QBE's riscv64 output materializes addresses with `lui %hi` / `addi %lo`, which only reaches the first 2 GiB, so `noxc build --target riscv64 --profile freestanding --emit-asm` rewrites each pair into the PC-relative `lla sym`. The runtime object is built with the `medium` code model. - `print` of integers and floats on aarch64 and riscv64 works through a register-based `printf` (no `va_list`): at most 7 integer and, on aarch64, 8 floating-point arguments per call, which `print` never exceeds. ## The allocator interface The managed heap — lists, dictionaries, strings, class instances, reference counts, everything — needs memory. A freestanding program provides it by registering a pair of functions **before** `main` runs: ```text nox_allocator_install(kernel_alloc, kernel_free) ``` The runtime then satisfies *every* memory request from them. The functions must return memory that is at least 8-byte aligned (the runtime's headers assume it) and must really own it. Because these functions back the whole managed heap, they sit inside the same [trust boundary](https://noxlang.com/docs/language/ffi/#the-trust-boundary) as `extern def`: a wrong allocator corrupts the whole program. **Default heap.** The reference x86_64 boot chain (`kernel.zig`) installs a built-in allocator: a size-class free-list heap over a contiguous 16 MiB region at the top of the 32 MiB identity-mapped memory (the page pool for `nox_alloc_page` lives below it). Requests are rounded up to a power-of-two class (16 B and up), blocks are reused after `free`, and there is no coalescing. If the heap (or a kernel-installed allocator) cannot satisfy a request, the program stops with `nox: out of memory — terminating the program` instead of continuing with a null pointer. Earlier releases rejected any request above 4096 bytes and never reclaimed memory, which silently corrupted lists above 128 elements. The boot chain runs the program on a 1 MiB boot stack (64 KiB in earlier releases overflowed in formatted printing such as `{x:8.3f}`). `nox_freestanding_early_init` is the one-time bootstrap step that runs, unconditionally and exactly once, before control reaches the program's top-level code. ## Hardware access `ptr[T]`, `ptr_read`/`ptr_write`, `ptr_*_volatile` and `memory_fence()`/`compiler_fence()` (inside `lowlevel`) give typed memory-mapped I/O; [`nox.mem`](https://noxlang.com/docs/stdlib/mem/) wraps the common patterns. Fixed-width integers (`u8`…`u64`) and `@repr("C")` / `@packed` classes model hardware registers and descriptor tables; `sizeof`, `alignof` and `offsetof` check layouts. Native entry stubs (boot code, interrupt trampolines) are small assembly or Zig objects linked in with `extern def`. ## Limits No threads, no scheduler pool (single-threaded cooperative `spawn` only if the runtime's fiber support is built for the target), no file system, networking or clock. Unhandled errors halt the machine rather than exiting a process. **Exit codes under QEMU.** The reference boot chain writes to the `isa-debug-exit` device: a program that finishes normally exits with QEMU status `33`; an unrecoverable error (unhandled exception, out of memory, integer overflow trap) prints its message on the serial port and exits with status `35`. On real hardware the port is inert and the machine halts. **Numerics.** There is no libm. Float `**` uses Zig's `std.math.pow`, and `nox.mathx.exp` uses a correctly rounded `f128` implementation (it agrees with a hosted libm to the last digit); the other `mathx` functions may differ from a hosted libm in the last digit. --- # noxc bindgen Generate Nox bindings from a C header. ```text noxc bindgen --lib [-o ] [--prefix ] [-I ] [-D ] [--shim ] [--shim-lib ] [--no-compile] [--no-classes] [--config ] [--cc ] ``` `bindgen` runs the C preprocessor (`cc -E`) on the header, reads the declarations with a small built-in C declaration parser (no libclang, no extra dependency) and writes a `.nox` file of `extern def` declarations and constants. C++ headers are handled through their `extern "C"` surface; for a Rust library, generate the C header with `cbindgen` first. ```text noxc bindgen sqlite3.h --lib sqlite3 --prefix sqlite3_,sqlite_ -o sqlite.nox ``` | Option | Meaning | |---|---| | `--lib` | where the symbols live: a system library name (`"m"`, linked `-lm`) or an object/archive path. Written into every `from "..."` clause. Required | | `-o` | output file (default `
    .nox`) | | `--prefix` | emit only names starting with the prefix (case-insensitive, comma-separated). **Required to get `#define` constants**, because the preprocessor does not say which header a macro came from | | `-I`, `-D` | forwarded to the preprocessor and the shim compiler | | `--shim`, `--shim-lib` | the generated C shim and the object name used in the generated `from` clauses (default `_shim.c` / `_shim.o`) | | `--no-compile` | do not compile the shim; the command prints the `cc` line to run | | `--no-classes` | do not write the [high-level classes](#high-level-classes) (only the raw functions) | | `--config` | a JSON file with variadic shims, `long_double`, `event_callbacks`, `unchecked_accessors`, and the class settings `classes` / `owned_returns` | ## What is generated | C | Nox | |---|---| | `int8_t … uint64_t`, `char`, `short`, `int`, `long`, `long long` | `i8 … i64`, `u8 … u64` (`long` and plain `char` follow the C compiler's own target: `__SIZEOF_LONG__`, `__CHAR_UNSIGNED__`) | | `size_t`, `uintptr_t` / `ssize_t`, `ptrdiff_t`, `intptr_t` | `usize` / `isize` | | `double`, `_Bool` | `float`, `bool` | | `float` | `float` through the shim (the shim converts) | | `const char *` parameter | `str` (plain `char` only; `unsigned char *` / `uint8_t *` stay `ptr`) | | every other pointer, function pointer, array parameter | `ptr` | | `enum` type | `i32`; the enumerators become `NAME: i32 = i32(value)` constants | | `static const NAME = expr;` | `NAME: = (value)` | | `#define NAME ` / `"string"` (needs `--prefix`) | `NAME: int = value` / `NAME: str = "..."` | | `struct` / `union` | memory is always a `ptr`; helpers and field accessors, below | | `extern T name;` | `name_get()` / `name_set(v)` (no setter for `const`) | | function pointer parameter with a `void *` userdata | `@ffi.callback(...)` declaration, below | ### Structs, unions and by-value arguments For every complete `struct`/`union` in the header `bindgen` generates, through the C shim (so the C compiler decides layout, padding, bit fields and `const`): | Function | Meaning | |---|---| | `Name_new()` / `Name_free(p)` / `Name_size()` | zeroed memory for one struct (`calloc`), release it, `sizeof`. **`Name_free` only releases blocks made by `Name_new` (or returned by by-value wrappers).** Never call it on a pointer the library owns (use the library's own destroy function) and note that it does not free memory the fields point to | | `Name_get_f(p)` / `Name_set_f(p, v)` | read / write field `f` (also bit fields; no setter for `const` fields) | | `Name_get_f(p, i)` / `Name_set_f(p, i, v)`, `Name_f_ptr(p)`, `Name_f_LEN` | an array field: element access, the array's start (use `nox.ffi.cstr` for a `char` array) and its length. For a fixed-length array the accessors are **bounds-checked**: an index `>= Name_f_LEN` makes the getter return `0`/`NULL` and the setter do nothing. Set `"unchecked_accessors": true` in `--config` for raw `p->f[i]` access (and always for flexible arrays, whose length is unknown) | | `Name_get_f(p)` for a nested struct | the **address** of the nested struct (read or write it with that struct's accessors); `Name_set_f(p, v)` copies `*v` into it | Fields of an anonymous inner `struct`/`union` are reachable directly on the outer type. A function that takes or returns a struct **by value** (`vec2 add(vec2 a, vec2 b)`) is called with pointers to struct memory, and a returned struct is a **new** block you free with `Name_free`: ```nox-fragment a: ptr = vec2_new() vec2_set_x(a, 1.5) vec2_set_y(a, 2.0) c: ptr = vec2_add(a, b) # a NEW block: free it (or use the generated classes below, which do it for you) print(vec2_get_x(c)) vec2_free(a) vec2_free(c) ``` ### Callbacks When a function takes a function pointer whose own signature has a non-`const` `void *` (the userdata) and the function has a `void *` next to it, `bindgen` writes the declaration with [`@ffi.callback`](https://noxlang.com/docs/language/ffi/#callbacks), including `ud_index=` when the userdata is not the callback's last parameter (`sqlite3_exec` has it first): ```nox-fragment def on_row(ncols: i32, vals: ptr, names: ptr) -> i32: print(ncols) return i32(0) sqlite3_exec(db, "select * from t", on_row, np()) # the userdata argument is left out: the compiler fills it in sqlite3_exec(db, "create table x(a)", None, np()) # None = no callback (a NULL function pointer) ``` A closure or lambda goes through a [`nox.ffi.Callback`](https://noxlang.com/docs/stdlib/ffi/) handle in the same place. Callback parameters are scalars, enums and pointers; read a `char *` with `nox.ffi.cstr(p)`. ### The C shim Some functions cannot be called directly from Nox, so `bindgen` also writes a small C file that wraps them: - `static inline` functions have no symbol in the library; - `float` (32-bit) parameters and results do not match Nox's `float` (64-bit), so the shim converts; - struct/union arguments and results, struct field access and global variables go through it too. A shimmed function becomes a raw `extern def nox_shim_` (linked from the shim object) plus an ordinary Nox `def` that calls it. **The wrapper always has the C name** (`mylib_half`, `vec2_add`). When the library also exports a symbol of that name, the wrapper is marked `@link_name("nox_w_")` — a built-in attribute that changes only the object-file symbol of a `def`, never its Nox name — so the two do not collide at link time. Names that are Nox keywords or builtins (`in`, `from`, `sum`, …) get a trailing underscore in Nox (functions: `in_`; parameters: `from_`). Helper and accessor names (`Name_get_f`, `counter_get`, …) are shim symbols themselves; if one would collide with a library function it gets a trailing `_`. ### Wide and special types: `_Complex`, `__int128`, `long double` | C type | In Nox | Helpers (generated once) | |---|---|---| | `float _Complex`, `double _Complex` | a `ptr` block | `cfloat_make(re, im)` / `cdouble_make(re, im)`, `_re(p)`, `_im(p)`, `_new`, `_free`, `_size` | | `__int128`, `unsigned __int128` | a `ptr` block | `i128_make(lo, hi)` / `u128_make(lo, hi)` (two `u64` halves), `_lo(p)`, `_hi(p)`, `_new`, `_free`, `_size` | | `long double` | `float` (narrowed to `f64`, precision is lost) | none; **off by default**: set `"long_double": "f64"` in the config | Arguments are the addresses of such blocks; a result is a NEW block that the caller releases with `_free`. Struct fields and globals of these types give the address of the field, like nested structs. Bit fields work like any field (`Name_get_f` / `Name_set_f`; the C compiler decides the layout). ### Variadic functions (`...`) A `printf`-style function cannot be called directly. Describe the fixed-signature versions you need in a JSON file and pass it with `--config bindgen.json`: ```json { "variadic": [ {"function": "my_log", "name": "my_log_s", "args": ["str"]}, {"function": "my_logn", "name": "my_logn_si", "args": ["str", "int"]} ], "long_double": "f64", "event_callbacks": ["lib_on_event"] } ``` `function` is the C function, `name` the generated Nox function (a C shim that makes the real variadic call), `args` the types of the part after the fixed parameters: `int`, `long`, `double`, `str`, `ptr` or `size`. A variadic function without an entry is skipped with a warning that points here. `event_callbacks` lists functions whose callback the library calls from its OWN thread: the callback parameter stays a plain `ptr` for [`nox.ffi.EventQueue`](https://noxlang.com/docs/stdlib/ffi/#callbacks-from-a-library-thread). ### What is skipped (with a warning) SIMD vector types (`__m128`, `float32x4_t`, `vector_size`) and callbacks that take or return a struct by value. A declaration the parser cannot understand is skipped with a warning naming its line, never silently. ## Using the output ```nox-fragment c: ptr = mylib_new("demo") if mylib_run(c, i64(5), MYLIB_FLAG_FAST) != MYLIB_OK: print("failed") mylib_free(c) ``` Constants made from `#define` are `int`s, and a constant that is never reassigned fits a fixed-width parameter **implicitly** when its value is in range, including expressions such as `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` (see [numbers](https://noxlang.com/docs/language/numbers/)); no `i32(...)` is needed. The generated `extern def`s are raw native calls: they run with the full authority of the process ([trust boundary](https://noxlang.com/docs/language/ffi/#the-trust-boundary)). Combine them with [`@ffi.errors`](https://noxlang.com/docs/language/ffi/#errors) and [`nox.ffi.Callback`](https://noxlang.com/docs/stdlib/ffi/) to get exceptions and closure callbacks. ## High-level classes Unless you pass `--no-classes`, `bindgen` also writes, below the raw functions (which stay available), a Nox **class** for every struct/union it made helpers for: ```nox-fragment from vec import Vec2 a: Vec2 = Vec2.new() # zeroed C memory, freed automatically when `a` goes away a.set_x(3.0) a.set_y(4.0) b: Vec2 = Vec2.new() b.set_x(1.0) c: Vec2 = a.add(b) # `vec2_add(vec2, vec2)`: the result is a NEW block that `c` owns print(c.len()) ``` - The constructor is `Name(p, owned)`; `Name.new()` allocates. `__del__` calls the free function when `owned` is true, so you never write `free`. - Scalar fields become `x()` / `set_x(v)`. A function whose **first parameter** is the struct (by value or pointer) becomes a method (the `Name_` or `lib_` prefix is dropped: `vec2_add` -> `add`, `sqlite3_stmt_readonly` -> `readonly`); a function that **returns** the struct and takes no struct first becomes a `@staticmethod`. Parameters and results of struct type use the class. Names that would clash are skipped with a warning, and the raw function is still there. - A pointer **returned by the library** is wrapped as *borrowed* (`owned=False`, never freed by the class), because `bindgen` cannot know who owns it. List the functions that hand you an owned pointer in `owned_returns`, and give opaque handles (`typedef struct sqlite3 sqlite3;`, no body) their destroy function in `classes`: ```json { "classes": [{"record": "sqlite3", "free": "sqlite3_close"}, {"record": "sqlite3_stmt", "free": "sqlite3_finalize"}], "owned_returns": ["sqlite3_open_helper"] } ``` The class then calls that function in `__del__` (instead of `Name_free`). Objects that must be destroyed in a particular order (a statement before its connection) still need you to keep the owner alive or `del` them in order; the generated code cannot see that relationship. - Cost: the class adds one small ARC object per wrapped value. Measured on an Apple M-series CPU with a by-value `vec2_add` returning a new block, 30 million iterations of "add, read, free" take 0.67 s through the raw functions and 0.86 s through the class (about 22 ns and 29 ns per iteration), so per-call allocation is not a bottleneck for per-frame game or UI code. ## Worked example: yyjson `noxc bindgen yyjson.h --lib yyjson.o --prefix yyjson` turns the whole yyjson header (about 9000 lines, mostly `static inline` functions) into 331 functions and 116 constants, 288 of them through the generated shim. Reading, walking (with the array iterator) and writing a JSON document work from Nox on both backends, and on a 1.6 MB document the generated binding walks it 4.8 times faster and writes it 8.4 times faster than `nox.json` (writing is as fast as C itself). The benchmark and the numbers are in `benchmarks/yyjson/` and `benchmarks/RESULTS.md`. --- # WebAssembly Nox programs compile to WebAssembly, and the compiler itself runs as WebAssembly in a browser tab ([Playground](https://noxlang.com/docs/tools/playground/)). ```bash noxc build --target wasm32-wasi hello.nox -o hello.wasm node --no-warnings tests/golden/wasm_run.mjs hello.wasm # or wasmtime, wasmer, ... ``` The output is a WASI command (`_start`). The build path is LLVM: the `.ll` file is linked with wasi-libc and the `noxrt-wasm32-wasi.o` runtime through `zig cc -target wasm32-wasi`, so `zig` must be on `PATH`; `--backend qbe`, `--emit-asm` and `-g` are errors on this target. The runtime objects (`lib/noxrt-wasm32-*.o`, the `-sqlite3.o` objects and the `lib/compiler-rt-wasm32*.a` archives) are produced by `zig build wasm-rt`. Since v2.0.150 they ship inside the release archives (macOS, Linux, Windows), so a published `noxc` can build `--target wasm32-*` without compiling anything from source (`zig` on `PATH`; `--asyncify` also needs `wasm-opt`). ## What works The whole language: classes, inheritance (multiple included), generators, `async`/`await`/`Channel`, exceptions, `with`, `__del__`, comprehensions, f-strings, `lowlevel`. From the standard library: `nox.strings`, `math`, `mathx`, `os`, `path`, `time`, `random`, `json`, `yaml`, `toml`, `csv`, `unicode`, `bytes`, `buffer`, `base64`, `bits`, `atomic`, `collections`, `url`, `uuid`, `validate`, `template`, `log`, `test`, `io`, **`fs`**, **`regex`**, **`gzip`**, **`crypto`** (hashes, HMAC, password digests), **`sqlite`**, **`http`**, **`router`**, **`web`**, **`reflect`**, **`transfer`**, **`websocket`**, **`tls`**, **`smtp`**, **`postgres`**, **`mysql`** and **`process`**. Anything that needs the outside world — sockets, child processes, a listening server — is a *capability* the host grants; see the [capability model](#capability-model-and---deny-capability). ## Targets and modes | Mode | Flag | `spawn`/`await`/`Channel` | Real fibers | Real parallelism (`nox.thread`, M:N) | Known limit | |---|---|---|---|---|---| | Default | (none) | nested-run simulation | no | no | a task waiting on a task below it on the stack is reported as a deadlock | | Asyncify | `--asyncify` | fibers (M:1) | yes | no | size and speed cost of Asyncify ([ADR-014](https://noxlang.com/docs/internals/adr/014-wasm-asyncify/)) | | Threads | `--threads` | fibers + work-stealing pool (M:N) | yes (with Asyncify) | yes | needs shared memory; file handles are per thread ([ADR-015](https://noxlang.com/docs/internals/adr/015-wasm-threads/)) | Every mode exists for both `wasm32-wasi` and `wasm32-freestanding`. Language and standard-library behaviour is identical across modes; only the concurrency model differs. This equivalence is checked by `zig build wasm-corpus-test` over the fixture corpus on all eight targets; the known differences (the last digit of libm, mode-specific scheduling order) are documented in the corpus lists. ## Limits - **Concurrency depends on the mode** (see the table). In the default mode there are no threads and `spawn`/`await` use the nested-run simulation: a task runs to completion on the stack of the task awaiting it, and a task waiting for the result of a task below it is reported as a "deadlock". `--asyncify` gives real fibers (one thread, M:1); `--threads` gives real parallelism (M:N). - **Modules that are not available.** `sharedmem`, `native`, `plugin`, `hpy` and the `hpy_*` / `wasm_call` built-ins are rejected at compile time with a message such as `module 'nox.sharedmem' cannot be used on the wasm32-wasi target (...)`. `native`, `plugin` and `hpy` can never work in WebAssembly (there is no dynamic loading). - **The network belongs to the host.** `nox.http` compiles, but a real socket (client `get`/`post`/`request`/streaming, server `serve*`) does not work without a host capability: client calls raise a catchable `HttpCapabilityError` (a subclass of `HttpError`); `serve` prints a diagnostic and returns at once, like a real bind failure. - **Node WASI on Windows has no `read_dir`.** Running a `wasm32-wasi` module under Node's `node:wasi` on Windows makes `nox.fs.read_dir` (and `remove_dir_all`, which uses it) raise `FsError`: Node's WASI does not implement `fd_readdir` on Windows (ENOSYS). Linux, macOS, `wasm32-freestanding` (virtual file system) and other WASI engines such as Wasmtime are not affected. - **No native libraries.** `extern def ... from "lib"` cannot link a native library into a `.wasm`. - **The file system** depends on the runner's WASI pre-opens (`wasm_run.mjs` opens `.` and `/tmp`). - **Math** functions (`exp`, `sin`, ...) come from wasi-libc and may differ from the platform libm in the last digit (for example `exp(1.0)`). Details and rationale: [ADR-012](https://noxlang.com/docs/internals/adr/012-wasm-target/). *Importing* a WebAssembly module into Nox ([`nox.wasm`](https://noxlang.com/docs/stdlib/wasm/) for a persistent instance handle, or the older single-call `wasm_call` built-in) is a separate mechanism: [HPy and WebAssembly](https://noxlang.com/docs/internals/hpy-wasm/). ## Capability model and `--deny-capability` WebAssembly is a general-purpose compile target: a module compiles as long as what it needs is a *capability* (`network`, `filesystem`, `clock`, `entropy`, ...). Providing the capability is the host's job (WASI, the `nox_host` imports, or a browser page); if the host does not, you get a clear error at the call, not a link error or a crash. The model covers the `nox.http` client (network), `nox.fs` and `nox.sqlite` (virtual file system), sockets, processes and servers, each described below ([ADR-016](https://noxlang.com/docs/internals/adr/016-wasm-capabilities/)). Environments that compile untrusted code (a code playground in a browser, for example) can also restrict capabilities at **compile time**; the flag works on every target, not just WebAssembly: ```bash noxc build --target wasm32-freestanding --deny-capability fs,net,process prog.nox -o prog.wasm NOX_DENY_CAPABILITY=net noxc check prog.nox # an environment variable works too ``` The list is comma separated: `filesystem`/`fs`, `network`/`net`, `clock`, `entropy`/`random`, `threads`, `process`, `shared_memory`/`shm`, `libc_math`, `dynamic_code`/`dynamic`. A program that imports a module needing a denied capability, or calls a function marked `@capability.requires` for it, is rejected: `module 'nox.http' cannot be used: the capability 'network' is denied (--deny-capability)`. An unknown name is an error (a misspelled denial is never ignored silently). The second layer is the host: a host that provides none of the relevant `nox_host` imports does not grant the capability even if it was not denied. On the freestanding asyncify target the host grants capabilities through a bit mask (`nox_host_caps_set`): `fetch` (1), `tcp` (2), `process` (4) and `serve` (8). All are **off by default**. ## `wasm32-freestanding` and `nox_host` ```bash noxc build --target wasm32-freestanding prog.nox -o prog.wasm noxc run --target wasm32-freestanding prog.nox # runs with node (compiler/wasm_host.mjs) ``` This produces a module with no WASI and no libc, suitable for a browser or an embedded host. The module sees the outside world only through the `nox_host` imports: `write`, `read`, `clock_ms`, `random_fill`, `sleep_ms` and `exit` ([ADR-013](https://noxlang.com/docs/internals/adr/013-wasm-host/)). Language and standard library are the same as on `wasm32-wasi`; the differences: `nox.fs` writes to the runtime's in-memory virtual file system, not a real disk (see below), the environment starts empty (`set_var` is module-local), and `arg(0)` is `"nox"`. To run it in a browser or your own host, use `createHost`/`runNox` from `compiler/wasm_host.mjs`: ```js import { runNox } from './wasm_host.mjs'; const code = await runNox(await (await fetch('prog.wasm')).arrayBuffer(), { write: (fd, bytes) => { (fd === 2 ? console.error : console.log)(new TextDecoder().decode(bytes)); return bytes.length; }, read: () => 0, clockMs: (kind) => (kind === 0 ? Date.now() : performance.now()), randomFill: (bytes) => crypto.getRandomValues(bytes), sleepMs: () => {}, }); ``` ### Verification tools `scripts/wasm_corpus.py` runs the fixture corpus in parallel on a selectable engine (`--target`, `--engine node|wasmtime`); `scripts/wasm_stress.py` repeats a mixed workload (channel fan-in, cyclic garbage, abandoned generators, `nox.thread`) on four targets for a given time and compares the output byte for byte with native. ### Cost Measurements are in `benchmarks/wasm/RESULTS.md` (reproduce with `benchmarks/wasm_bench.py`). In short (Apple M4, Node 26): WebAssembly is 1.4x slower than native LLVM on CPU-bound code and 3-5x slower on memory-heavy code; `--asyncify` adds 0-4% on CPU-bound code compared with the default mode but slows workloads that suspend very often (500 thousand `spawn`/`await`) by 2.6x; `--threads` is 2.7x faster than Asyncify on four equal tasks but pays for atomic ARC on a single worker. Modules are 60-125 KB. ### In the browser `createHost`/`runNox` work in a browser as they are, and so do `--asyncify` modules (plain WebAssembly). For threaded `wasm32-freestanding-threads` modules use `runNoxThreads(bytes, io)`: the main wasm thread runs as a Worker (a page cannot `Atomics.wait`), the page creates all Workers, and output and exit code are relayed to the page. The page must be `crossOriginIsolated` (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`). `examples/wasm-browser/` has a sample page and a small server that adds those headers: ```bash noxc build --target wasm32-freestanding-threads prog.nox -o examples/wasm-browser/prog.wasm node examples/wasm-browser/serve.mjs # http://127.0.0.1:8123/examples/wasm-browser/index.html?wasm=prog.wasm ``` Verified in Chromium: the default, `--asyncify` and `--threads` modes (including the 200-thread `thread_spawn_stress` and the shared atomic counter) give the same output as native. Firefox and Safari were not tried for threads. `wasm32-wasi` modules need a WASI shim in a browser (WASI imports instead of `nox_host`); `wasm_host.mjs` provides WASI only on Node. ### Other engines `wasm32-wasi` and `wasm32-wasi-asyncify` modules also run under `wasmtime` (`noxc run` prefers it): the whole fixture corpus passes with zero differences through `scripts/wasm_corpus.py --target wasm32-wasi --engine wasmtime`. Threaded modules do not run under wasmtime or wasmer (wasi-threads was removed); they need `wasm_host.mjs` or a host that implements the `thread_spawn` contract. ## `--asyncify`: real fibers ```bash noxc build --target wasm32-wasi --asyncify prog.nox -o prog.wasm # needs wasm-opt (binaryen) noxc run --target wasm32-freestanding --asyncify prog.nox ``` `--asyncify` really suspends tasks that are waiting (stack switching): mutual channel waits, `nox.thread`/`sleep` ordering and `async` patterns run in the same order as under the native scheduler, and the deadlock limit disappears. The output module asks the host for no extra imports and runs on any WebAssembly engine. Cost: roughly 30-50% in speed and size and a dependency on `wasm-opt` ([ADR-014](https://noxlang.com/docs/internals/adr/014-wasm-asyncify/)). It is not parallelism (a single thread). The `wasm-opt` invocation enables bulk memory, sign extension, non-trapping float-to-int and mutable globals explicitly so older binaryen releases accept the objects. ## `--threads`: real parallel M:N ```bash noxc build --target wasm32-wasi --threads prog.nox -o prog.wasm # needs wasm-opt (binaryen) and node NOX_POOL_WORKERS=4 noxc run --target wasm32-wasi --threads prog.nox ``` `--threads` brings the work-stealing M:N pool of the native `--release` runtime to WebAssembly: `spawn`/`await`, `Channel` and `nox.thread` really run in parallel on several threads (shared memory plus atomics). The module imports `env.memory` (shared) and `wasi::thread-spawn`; `compiler/wasm_host.mjs` provides them with Node Workers (wasmtime 50 removed `-Sthreads`, so `noxc run` uses only Node for this target). Another host can run the module by providing the same two imports. The worker count is set with `NOX_POOL_WORKERS`. Limits and rationale: [ADR-015](https://noxlang.com/docs/internals/adr/015-wasm-threads/). `--threads` also exists for `wasm32-freestanding`: the host provides `nox_host.thread_spawn(arg) -> tid` and calls `nox_host_thread_start(tid, arg)` on each new thread (with a shared `env.memory`). ### How `--threads` is verified - **Differential corpus.** `scripts/wasm_corpus.py --target wasm32-wasi-threads` (and `wasm32-freestanding-threads`) builds every `codegen_cases` fixture and compares its output with the native `.expected` in Node (`worker_threads` + `SharedArrayBuffer`): 590 of 590 comparable fixtures agree (the rest are compile-time rejections of modules WebAssembly does not have, and documented platform limits: no signals other than SIGINT/SIGTERM/SIGHUP, no child processes, `memset`/`memcmp` externs declared with 64-bit `int`). - **Real Windows.** `scripts/wasm_threads_remote.py --host user@pc` builds the threaded concurrency fixtures here and runs them on a remote Windows machine (Node 26, `compiler/wasm_host.mjs`): 109 of 109 modules match. - **A real C program.** `tests/golden/wasm_c_pthreads.c` (4 `pthread_create` threads, an atomic counter, a mutex, `pthread_join`) is compiled by an independent toolchain (wasi-sdk 25, `wasm32-wasip1-threads`) and runs on the Nox host: `wasm_target_test.zig` builds and runs it five times when `WASI_SDK_PATH` points at a wasi-sdk (skipped otherwise). Link it with `-Wl,--import-memory`: the host provides the shared memory. - **ThreadSanitizer.** WebAssembly has no TSan, but the M:N runtime sources are shared with the native runtime: `scripts/tsan_check.sh` runs the shared-state fixtures under TSan (38 runs, 0 reports). ## SQLite `nox.sqlite` compiles on every WebAssembly target; the SQLite library is linked into the program statically (only programs that use `nox.sqlite` grow, by about 700 KB). On `wasm32-wasi`, file-based databases work in the directories the host pre-opens (`wasmtime run --dir=. app.wasm`) and persist between runs; there is no locking (a single process is assumed). On `wasm32-freestanding`, file-based databases live in the virtual file system (below). ## Virtual file system (wasm32-freestanding) A `wasm32-freestanding` module has no operating system; `nox.fs` and file-based `nox.sqlite` go to an **in-memory virtual file system** that lives in the runtime's linear memory. No import is added for the host, and nothing is written to a real disk or server (safe for a playground). It starts with `/` and `/tmp`; relative paths resolve under `/`, and `..` never climbs above the root. By default the file system lives for the lifetime of the program and disappears at exit; in `--threads` mode it is shared between threads. See the next section to make it persistent. `remove_file` is safe even while a handle is open (like POSIX `unlink`). Limits: no symbolic links, permission bits or directory removal of non-empty directories except through `remove_dir_all`; `rename` cannot move a directory on top of another directory. On `wasm32-wasi`, file operations go to the pre-opened directories of WASI (`.` and `/tmp`). ### Persistent virtual file system The virtual file system can be made **persistent on request**: the host fills the tree before the module starts and stores a snapshot at exit. Nothing is imported for this: the module (only if it uses `nox.fs`/`nox.sqlite`) exports `nox_vfs_host_alloc/free/put/mkdir/snapshot` and the host reads and writes memory directly. `/tmp` counts as temporary: it is neither mirrored to the host nor saved. - **Command line (Node):** `noxc run --target wasm32-freestanding --vfs-dir data/ prog.nox`, or with a built module `node wasm_host.mjs prog.wasm --vfs-dir=data/` (or `NOX_VFS_DIR`). The directory is loaded into the virtual file system at start (symbolic links are skipped; at most 512 MiB) and written back at exit: changed files are written with a temporary file plus `rename`, unchanged files are left alone, and files the program deleted are deleted from disk. A symbolic link under the root is never written through or deleted through. A program that does not use the file system does not touch the directory. - **Browser / your own host:** `runNox(bytes, io, { vfs: { files, onSave } })`; `files` is `[{ path, data? }]` (a missing `data` means a directory) and `onSave(entries)` is called at exit with a snapshot in the same shape; writing it to IndexedDB/OPFS is up to you. For threaded modules, `runNoxThreads(bytes, io, { vfs: { files, onSave } })` follows the same contract. Low level: `vfsPreload(instance, entries)` and `vfsSnapshot(instance)`. ```js import { runNox } from './wasm_host.mjs'; const saved = JSON.parse(localStorage.getItem('nox-vfs') ?? '[]').map((e) => ({ path: e.path, data: e.b64 && Uint8Array.from(atob(e.b64), (c) => c.charCodeAt(0)) })); await runNox(bytes, io, { vfs: { files: saved, onSave: (entries) => localStorage.setItem('nox-vfs', JSON.stringify(entries.filter((e) => !e.path.startsWith('/tmp')).map((e) => ({ path: e.path, b64: e.data && btoa(String.fromCharCode(...e.data)) })))), } }); ``` Persistence is written at exit: if the program crashes (a trap) the snapshot is still taken, but if the process is killed it is not. ## Network: the `nox.http` client through the host's `fetch` (wasm32-freestanding --asyncify) On the `wasm32-freestanding-asyncify` target, `nox.http.get/post/request` rely on the host's `fetch` (`window.fetch` in a browser, `globalThis.fetch` in Node, or any `fetch`-compatible function the host provides). The capability is **off by default**: unless the host grants it, client calls raise a catchable `HttpCapabilityError`. ```js import { runNox } from './wasm_host.mjs'; await runNox(bytes, io, { fetch: globalThis.fetch }); // network on await runNox(bytes, io, { fetch: null }); // network off (the default): HttpCapabilityError ``` On the command line, for Node: `noxc run --target wasm32-freestanding-asyncify --allow-net prog.nox` (or `NOX_ALLOW_NET=1`). At compile time, `--deny-capability network` forbids a module from using the network at all (this is what the Playground does). - **How it works.** The fiber that makes the network call is parked and other fibers run (so with `spawn` requests go out in parallel). When no fiber is ready, the module returns to the host without reporting an exit; the host waits for the `fetch`es, delivers the results and resumes the program with `nox_host_resume()`. Nothing is imported by the module; the host only calls exports (`nox_host_caps_set`, `nox_host_fetch_pending`, `nox_host_fetch_complete`, `nox_host_status`, `nox_host_resume`, `nox_host_alloc/free`). Details: spec §3.351. If you write your own host, the `runNox` loop in `compiler/wasm_host.mjs` is the reference. - **Limits.** Only `--asyncify` freestanding (suspending needs fibers); plain freestanding, `--threads` (see below) and `wasm32-wasi` keep raising `HttpCapabilityError`. The streaming client (`stream`, `stream_upload`, `nox.transfer`) is supported: a download is read from the `fetch` response reader chunk by chunk (only as `read_chunk` is called, with back-pressure) and `timeout_ms` is an idle timeout; an upload is buffered in the runtime and sent as one request on `finish()` (not every browser supports streaming upload bodies in `fetch`). `get/post/request` buffer the whole response. Redirects are followed by `fetch`. Header names are lower case, as `fetch` gives them. In a browser, CORS and mixed-content rules belong to the page. Timeouts use `AbortSignal.timeout`. - **`--threads`.** Threaded freestanding modules can use the client too: the calling thread blocks in `nox_host.net_fetch`/`net_read` (a helper Worker plus `Atomics.wait` on Node, synchronous XHR in a browser Worker), with the capability off by default. ## Compiling in the browser The compiler itself also runs as WebAssembly (a server-free playground, an embedded code sandbox): see [The Nox compiler in the browser](https://noxlang.com/docs/tools/browser-compiler/) and the [Playground](https://noxlang.com/docs/tools/playground/). ### WebSocket client `nox.websocket` (`connect`, `send_text`, `recv`, `is_open`, `close`) compiles on every WebAssembly target. On `wasm32-freestanding-asyncify` it relies on the host's `WebSocket` (`window.WebSocket` in a browser, `globalThis.WebSocket` in Node 22+); the network capability is opened with the same switch as `fetch` (`runNox(bytes, io, { fetch, WebSocket })`, `--allow-net`). `send_text` has no reply, `recv` parks the fiber (other fibers run), at close it returns an empty `str` and `is_open()` becomes false; `wss://` is handled by the host. In other modes, or without the capability, `connect` raises `WebSocketError` with a "network capability" message. Binary messages arrive as `str` with the raw bytes. The server side (`serve_ws`) is not available on WebAssembly. ### Stopping a module from the host: `nox.signal` On `wasm32-freestanding-asyncify` a module that imports `nox.signal` exports `nox_host_signal(sig)` (and `nox_host_caps_set`/`nox_host_resume`, as for every asyncify host module). The host calls it with 2 (SIGINT), 15 (SIGTERM) or 1 (SIGHUP); it returns `1` if the module installed a handler for that signal and `0` otherwise. A `wait`/`take` loop in the module then sees it; `nox.signal.wait` sleeps on a host timer (`caps` bit 16, `kind` 16 requests) so the event loop is free to deliver it. `runNox(bytes, io, { signalSource: (deliver) => ... })` is the embedding hook (the Node command line wires `SIGINT`/`SIGTERM`/`SIGHUP` to it and falls back to the default action when the module did not install the signal). `nox.http.serve` keeps its own graceful stop (`serveSignal`). ### Raw TCP: `nox.tls` and `nox.smtp` `nox.tls` and `nox.smtp` compile on every WebAssembly target. For real connections on `wasm32-freestanding-asyncify` the host provides the **TCP capability**: `runNox(bytes, io, { tcp: await nodeTcp() })` (`nodeTcp` is built on Node's `net`/`tls` and exported from `wasm_host.mjs`), or `--allow-net` on the Node command line. A browser has no raw sockets: there `tcp` is not provided unless you give one, and `connect` raises `TlsError`/`SmtpError` with a "tcp capability" message. To get TCP in a browser, run the WebSocket-to-TCP bridge and pass `browserTcp` (see "TCP in a browser" below). **TLS terminates in the host**: the module carries no CA bundle or handshake code, and certificate validation (hostname included) lives in the host's TLS stack (Node: system CAs plus `NODE_EXTRA_CA_CERTS`). The `smtp` STARTTLS upgrade also happens in the host. Streaming uses the same suspension mechanism as `fetch` (a read parks the fiber, writes have no reply). **Read timeouts** (`nox.redis` `set_read_timeout`, `nox.postgres` `set_query_timeout`) travel in the read request as a `timeout=` line of its `headers` field: the host answers with status 2 when the time runs out and keeps the pending read so no byte is lost. It is not a new host import; a host that ignores the field simply blocks as before. Limit: `--threads`, plain freestanding and `wasm32-wasi*` do not have the capability. ### gRPC over TLS: `nox.grpc.connect_tls` `nox.grpc` ([client](https://noxlang.com/docs/stdlib/grpc/)) compiles for `wasm32-freestanding-asyncify` and uses the host TCP capability. `connect_tls(host, port, ca_file, cert_file, key_file)` asks the host for TLS with ALPN `h2`; a server that does not select `h2` makes the connect fail. `ca_file`, `cert_file` and `key_file` are PEM paths on the **host's** file system (the host reads them: TLS terminates there): `nodeTcp({ tlsFiles: true })`, which the Node command line turns on together with `--allow-net`. An embedding host that builds `nodeTcp()` itself gets `tlsFiles: false` by default, and then a `connect_tls` that names a file fails with "TLS certificate files are not allowed by this host". Without file arguments it uses the host's trust store. `Redis` over TLS is not available in the wasm runtime. ### PostgreSQL `nox.postgres` runs on WebAssembly with a PostgreSQL protocol 3.0 client written in Zig instead of `libpq` (it needs the host TCP capability, see "Raw TCP"). Authentication: trust, cleartext, MD5, SCRAM-SHA-256; queries: the simple protocol (`execute`/`query`) and the extended protocol (`prepare` + `bind_*`, text-format parameters and results, `$n` and `?` placeholders). The connection string is either `host=... port=... user=... password=... dbname=...` or `postgres://user:password@host:port/db?sslmode=require`. `sslmode=require|verify-ca|verify-full` uses SSLRequest plus the host's TLS (the host verifies the certificate, so all three modes verify — stricter than libpq's `require`); other modes are plain text (a deliberate departure from libpq's `prefer` default). Limits: no `COPY`, `LISTEN/NOTIFY`, binary format or named `PQprepare` statements (the same scope as the native driver). ### MySQL / MariaDB `nox.mysql` runs on WebAssembly with a MySQL client protocol written in Zig instead of `libmysqlclient` (it needs the host TCP capability, see "Raw TCP"). Authentication: `mysql_native_password` and `caching_sha2_password` (MySQL 8's default: the fast path and, when the server's cache is empty, full authentication with the password encrypted under the server's RSA key with OAEP — no TLS required), including authentication-plugin switching. Queries use the text protocol (`COM_QUERY`); `prepare` + `bind_*` works as in the native driver, escaped on the client (aware of `NO_BACKSLASH_ESCAPES`) and embedded in the SQL. `last_insert_rowid()`, `changes()` and the `NULL` distinction work. Verified against real MySQL 8.4 and MariaDB 11 servers. Limits: no TLS (`open_url` carries no TLS option), TCP is used even for `localhost` (no Unix socket), only the first result of a multi-result statement such as `CALL` is returned, and there is no `LOCAL INFILE`. ### TCP in a browser (WebSocket-to-TCP bridge) Every TCP-based module (`nox.tls`, `nox.smtp`, `nox.postgres`, `nox.mysql`, `nox.redis`, `nox.grpc`) works in a browser through a small Node process that turns a WebSocket into a TCP connection: ```bash node compiler/wasm_tcp_bridge.mjs --listen 127.0.0.1:8765 --allow db.internal:5432,redis.internal:6379 --origin https://app.example.com --token SECRET ``` ```text import { runNox, browserTcp } from './wasm_host.mjs'; await runNox(bytes, io, { tcp: browserTcp({ url: 'ws://127.0.0.1:8765/', token: 'SECRET' }) }); ``` One WebSocket carries one TCP connection (binary messages are the raw bytes). **TLS ends in the bridge**, not in the page: `connect(..., tls=True)` and the `STARTTLS` upgrades are performed by the bridge's TLS stack, which also verifies the certificate; the page never sees keys or certificates. The bridge is an open proxy, so `--allow` is **required** (same syntax as `--net-allow`; `"*"` allows everything); `--origin` and `--token` are optional extra checks, and a refused request gets an HTTP 403/400 before the WebSocket upgrade. `ca_file`/`cert_file`/`key_file` paths name files **on the bridge machine** and are honoured only with `--tls-files`. Limits: no back-pressure (a message is at most 16 MiB), one TLS upgrade per connection. The Node CLI can use the same path with `--tcp-bridge=ws://host:port/` (instead of `--allow-net`), which is how it is tested: the native redis programs run unchanged against real `redis-server` processes through the bridge. ### Redis `nox.redis` runs on `wasm32-freestanding-asyncify` over the host TCP capability (see "Raw TCP"; `--allow-net` in the CLI host): the same RESP2 client as the native one — commands, binary payloads, Streams and consumer groups, cached scripts with `NOSCRIPT` recovery, `AUTH`/ACL users, dropped connections and `reconnect()`. `connect(..., tls=True, ca_file=...)` upgrades the connection with the host's TLS (the host verifies the certificate; a private CA goes through `ca_file`, an untrusted certificate is rejected). Mutual TLS client certificates are passed to the host as for gRPC. Verified against real `redis-server` processes with the same programs and expected output as the native tests. Not available on `wasm32-wasi` (no host TCP). ### Child processes (`nox.process`) `nox.process` compiles on every WebAssembly target; running a process is a **host capability**. On `wasm32-freestanding-asyncify`, if the host provides a process provider (`runNox(bytes, io, { process: await nodeProcess() })`, or `--allow-process` on the Node command line, `noxc run --target wasm32-freestanding-asyncify --allow-process`), `Command(...).run()` works; otherwise it raises `ProcessError` ("could not run the process"). The default Node provider calls `child_process.spawn` **without a shell** (arguments are never interpreted by a shell, so there is no injection); output is buffered and the process is killed if `set_timeout` is exceeded. A browser has no processes (no provider is given). `--allow-net` does **not** turn the process capability on: network and process are separate switches. ### HTTP server (`nox.http.serve`) The server is also a **host capability**: the module opens no socket. On `wasm32-freestanding-asyncify`, if the host provides a `serve` provider (`runNox(bytes, io, { serve: await nodeHttpServer(), serveSignal })`, `--allow-serve` on the Node command line, `noxc run --target wasm32-freestanding-asyncify --allow-serve`), `nox.http.serve(port, handler)` listens on the host (`port` 0: the host picks; the Node provider listens on `127.0.0.1` only by default, changed with `NOX_SERVE_HOST`), forwards every incoming request to the module, and the module runs `handler` in its own fiber per request. Handlers can use `nox.http.get` (the host's `fetch`), `nox.sqlite` and `nox.fs` like any fiber, and the `nox.router`/`nox.web` building blocks work unchanged. The provider interface is `listen(port, handle) -> Promise<{ port, close() }>` and `handle({ method, target, headers, body, peer }) -> Promise<{ status, headers, body }>`: instead of Node's `node:http` you can plug in another engine, a service worker or your own server. When `serveSignal` (an `AbortSignal`) aborts (the CLI does that on `Ctrl-C`/SIGTERM) the listeners close, `serve` returns and the program ends normally. Without the capability, `serve` prints a diagnostic and returns at once, as before. Limits: handler rounds run in batches (requests in one round run concurrently; new requests wait in a queue until the round finishes); there are no streaming responses (`stream`/`respstream_*`), no WebSocket upgrade (`serve_ws`), no TLS (the host terminates it), no HTTP/2 and no multi-core `serve_multicore`; `wasm32-freestanding-asyncify` only. ## Host security policies Capabilities are off by default; when they are on, the host's `node` providers apply the limits below. A host that runs untrusted code (a multi-tenant platform, for example) should tighten them or supply its own providers. - **Network allow-list:** `--net-allow=host[:port],*.domain[:port],...` (or `NOX_NET_ALLOW`; also accepted by `noxc run`) together with `--allow-net` limits `fetch`, WebSocket and raw TCP connections to the listed destinations (no port, or `*`, means any port; `*.domain` does not cover the apex name). `fetch` redirects are followed manually and every hop is checked again. The host name is matched as the module gives it: there is no IP check after DNS resolution, so an allowed name that resolves to a private address is the operator's responsibility. It is not supported with `--threads` modules (refused explicitly). Programmatic equivalents: `netPolicy`, `restrictFetch`, `restrictTcp`, `restrictWebSocket`. - **Process allow-list:** `--allow-process=git,/usr/bin/env` allows only the listed programs (plain `--allow-process` allows all; the program is matched as the module gives it, with no path search). `nodeProcess` limits the sum of stdout and stderr to `maxOutputBytes` (16 MiB by default) and kills the process when it is exceeded. Programmatic equivalent: `restrictProcess`. - **HTTP server quotas:** `nodeHttpServer({ maxBodyBytes: 10 MiB, maxResponseBytes: 64 MiB, requestTimeoutMs: 30000, maxConcurrent: 64 })`. When one is exceeded the client gets 413 (body), 500 (response), 504 (handler time) or 503 (concurrency); the response of a request that timed out or whose client disconnected is dropped. - **`--vfs-dir`:** a symbolic link under the root is never written through or deleted through, so nothing escapes the root. - **Compiler in the browser:** the `compileToIr` options (`target`, `deny`, `label`) cannot contain control characters; otherwise a `\ndeny=` inside a `label` could have bypassed a capability restriction. --- # The Playground (beta) The [Playground](https://noxlang.com/playground/) lets you write, compile and run Nox in a browser tab. It is **beta**: the compiler it uses is the real one, but the page is new and the environment around your program is deliberately small. ## How to use it - Pick an example from the list, or type your own program in the editor. Errors are checked as you type and the first one appears at the top right. - Press **Run** (or Ctrl/⌘ + Enter). The output appears on the right with the exit code and the time spent compiling and running. - **Stop** ends a running program; a program that is still running after 15 seconds is stopped for you. - If your program reads input with `input()`, type the text in the *stdin* box first — each line is one `input()` call. - **Copy link** puts your program into the URL (after the `#`), so you can send it to someone. The code stays in the link; it is never stored on a server. ## What runs where Everything runs in your browser: 1. The Nox front end (about 2 MB of WebAssembly) type-checks your code and produces LLVM IR — the same IR a native `noxc` would produce. 2. An LLVM toolchain (clang and the linker, also WebAssembly, [`@yowasp/clang`](https://www.npmjs.com/package/@yowasp/clang)) turns the IR into a `.wasm` module. It is downloaded the first time you open the page (about 25 MB compressed, from a public CDN, at a pinned version) and kept in the browser cache afterwards. 3. The module runs in a separate worker, so an endless loop cannot freeze the page, and **Stop** simply discards the worker. The source you type is not sent to any server — not for compiling, not for running. ## What a Playground program can and cannot do The Playground compiles for `wasm32-freestanding` with the **network**, **process**, **shared-memory** and **dynamic-code** capabilities denied at compile time (see [`--deny-capability`](https://noxlang.com/docs/tools/wasm/#capability-model-and---deny-capability)). A program that imports `nox.http` or `nox.process` is rejected with a message that names the capability. - The standard library that needs nothing from the outside works: strings, collections, `json`, `regex`, `csv`, `crypto`, `sqlite` (in memory) and so on. - `nox.fs` works on a private **in-memory** file system that vanishes when the program ends; nothing touches your disk. - `spawn`/`await`/`Channel` use the default WebAssembly mode (see [Targets and modes](https://noxlang.com/docs/tools/wasm/#targets-and-modes)), so patterns that need real fibers or real threads are not available here. Compile those locally with `--asyncify` or `--threads`. - Output is capped at 1 MiB, and `sleep` is a short busy wait: this is a toy for learning, not a place to measure performance. ## Embedding it in your own page The pieces are ordinary files: the front end, a few modules and the runtime objects. [The Nox compiler in the browser](https://noxlang.com/docs/tools/browser-compiler/) shows the API — `createNoxCompiler`, `compile`, `runNox` — and the page source (`services/noxlang-site/site/playground/`) is a working example using workers. A page that loads a compiler from another origin needs a content-security policy that allows WebAssembly (`'wasm-unsafe-eval'`), workers, and the CDN you load clang from; the Nox site applies that policy to the `/playground` path only and keeps a stricter one everywhere else. ## Reporting a problem If a program that compiles with `noxc build --target wasm32-freestanding` fails in the Playground — or the reverse — [open an issue](https://github.com/mburakmmm/nox-lang/issues) with the program and what you saw. Browsers differ in how much memory a WebAssembly tab may use; a very large program can fail to link on a phone. --- # The Nox compiler in the browser The whole Nox compiler runs as WebAssembly: source code is compiled to `.wasm` **in the browser** (or in Node) and run there. No server, no `noxc` binary, no `zig` or `clang` installation is needed, and the code is sent nowhere. It powers the [Playground](https://noxlang.com/docs/tools/playground/) and is meant for embedded code sandboxes and offline tools. There are two parts: 1. **The front end** (`noxc-frontend.wasm`, about 2 MB): lexer, parser, type checker and LLVM IR generation. The `nox.*` standard library is embedded in the module. It produces **byte-for-byte the same** IR as a native `noxc build --target wasm32-*` (it is the same code, `compiler/frontend.zig`). It checks and compiles a program in about 30 ms and returns syntax and type errors as readable text. 2. **The back end** (clang and wasm-ld, themselves WebAssembly): links the IR with the runtime objects and produces `.wasm`. The default provider is [`@yowasp/clang`](https://www.npmjs.com/package/@yowasp/clang) (an optional dependency, about 25 MiB gzipped, loaded lazily on first use and kept in the browser cache); any other provider with a compatible `runClang(argv, files)` can be passed instead. ## Usage ```js import { createNoxCompiler } from './wasm_compiler.mjs'; import { runNox } from './wasm_host.mjs'; const nox = await createNoxCompiler({ frontend: await (await fetch('noxc-frontend.wasm')).arrayBuffer(), // runtime objects: noxrt-wasm32-freestanding.o, ...-sqlite3.o, compiler-rt-wasm32.a (the lib/ directory of a release archive) asset: async (name) => new Uint8Array(await (await fetch(`lib/${name}`)).arrayBuffer()), clang: () => import('@yowasp/clang'), }); const r = await nox.compile('print("hello", 6 * 7)\n', { target: 'wasm32-freestanding' }); if (!r.ok) console.error(r.diagnostics); // for example "main.nox:1:9: syntax error: ..." else await runNox(r.wasm, io); // io: write/read/clockMs/randomFill/sleepMs (see the WebAssembly page) ``` - `nox.compileToIr(source, opts)` runs only the front end (`{ ok, ir, plan, diagnostics }`): ideal for live error checking. - `opts.target`: `wasm32-freestanding` (the default), `-asyncify`, `-threads`. `opts.deny`: compile-time capability bans (`['fs', 'network']`, see `--deny-capability`). `opts.label`: the file name shown in diagnostics. These options cannot contain control characters. - `nox.addFile('/stdlib/...' | path, text)`: adds an in-memory virtual file (adding the same path again replaces it). - `--asyncify` targets need a post-link `wasm-opt`: in a browser use `binaryen` (npm, Apache-2.0) with `import { binaryenAsyncify } from './wasm_asyncify.mjs'; createNoxCompiler({ ..., optimize: binaryenAsyncify(binaryen) })`. Without it a clear error is returned. The `nox.http` client (`fetch`) works only on this target. When running, the host options on the [WebAssembly page](https://noxlang.com/docs/tools/wasm/) apply: the in-memory file system, optional persistence (`vfs`) and — only when explicitly given — the network (`fetch`). On pages that run untrusted code, restrict capabilities at compile time with `deny` and give `runNox` no `fetch` or `vfs`. ## Distribution and limits - Next to the release archive a `nox-web-compiler-.tar.gz` is published: `noxc-frontend.wasm`, `wasm_compiler.mjs`, `wasm_asyncify.mjs`, `wasm_host.mjs` and `lib/` (the runtime objects). From source: `zig build wasm-compiler wasm-rt`. - The first compile loads clang/lld (hundreds of ms); later ones take about 0.3-1 s. Large programs and `nox.sqlite` (an output of about 800 KB) take a little longer. - Native `extern def ... from ""` declarations cannot be linked in a browser (there are no native libraries); the `native`, `plugin` and `hpy` modules are unavailable on WebAssembly anyway. - Verification: `scripts/wasm_frontend_corpus.py` compares the front end's IR with native `noxc` over the whole `codegen_cases` corpus (467 identical, plus 16 rejected for the same reason); `scripts/web_compiler_e2e.mjs` runs the full pipeline (front end, clang, run) over the corpus and compares with `.expected` (`wasm32-freestanding` 453 ok, `wasm32-freestanding-asyncify` 458 ok with binaryen). --- # Architecture This section explains how Nox is built, for contributors and the curious. It is a summary of the engineering rules that govern the project (`AGENTS.md`) and of the design history (`nox-teknik-spesifikasyon.md`, one numbered section per change). If a summary here and those documents ever disagree, the engineering documents win. ## The pipeline ```text .nox source → lexer → parser → AST compiler/lexer, compiler/parser → type checker (mandatory static types, compiler/typecheck generics by monomorphisation, protocols, checker-driven AST rewrites) → ownership analysis (ASAP vs ARC decision) compiler/ownership → typed IR → QBE IL or LLVM IR compiler/codegen_qbe (qbe_emit / llvm_emit seam) → native code, linked statically with the Zig runtime runtime/ ``` Both back ends consume the **same typed IR** through one emission seam (`qbe*` helpers that either write QBE text or LLVM text), so every code-generation change is exercised by both and the whole corpus runs on both. The Zig runtime provides allocation, reference counting, the cycle collector, the fiber scheduler, error values, strings, lists and dictionaries, the HPy/CPython bridge and the WASM bridge. ## Repository layout ```text compiler/ lexer, parser, typecheck, ownership, codegen_qbe, fmt, pkg (fetch/index/install/upgrade), lsp, main runtime/ alloc (ASAP/ARC/cycle/lowlevel), async_rt (fibers, scheduler, worker pool, reactor), errors, collections, stdlib_shims (Zig side of nox.*), hpy_bridge, cpython_compat, wasm_bridge, freestanding stdlib/nox/ the standard library, written in Nox tests/ unit, golden (source → output and IR snapshots), compat (real C/HPy/WASM/NNI extensions), cli, fuzz docs/ this documentation editors/ tree-sitter grammar, VS Code extension services/ the noxpkg registry and the website (both written in Nox) include/ nox_nni.h — the public native interface header ``` ## The seven non-negotiable invariants 1. **Ownership never appears in user syntax.** No `mut`/`read`/`owned`/`Annotated`. When the compiler cannot prove ownership it falls back silently to reference counting — never an error, never a hint request. 2. **Static typing everywhere — including `lowlevel`.** `lowlevel` relaxes only the allocation strategy. 3. **No unwind tables or landing pads** in generated code. Error propagation is an implicit error-union return chain. 4. **No raw `PyObject*` and no Nox heap address ever reaches a C extension.** Everything crosses through opaque handles. 5. **WebAssembly is a compilation target through LLVM, never through QBE.** `--target wasm32-wasi` compiles Nox to a `.wasm` ([WebAssembly](https://noxlang.com/docs/tools/wasm/)); there is no QBE WASM back end. Importing a WASM module into a Nox program is a separate library-import mechanism. 6. **No global or hidden mutable state.** The runtime takes its allocator explicitly; the runtime state is threaded through generated code as a hidden first parameter. (One narrow, documented exception: the freestanding runtime's one-time bootstrap state.) 7. **Every language feature ships with at least one golden test.** Changes that would violate one of these are not accepted; they are raised with the maintainers instead. ## noxc-nightly (experimental) `zig build nightly` builds `zig-out/bin/noxc-nightly`: the normal compiler plus components written in Nox itself (`selfhost/`), linked into one binary. The installed `noxc` compiles the Nox sources with a hidden, unsupported flag (`noxc build --selfhost-obj`) into an object without `main` that exports `nox_lib_init(rt)`, `nox_lib_fini(rt)` and every top-level `def` as a C symbol; the Zig side (`compiler/selfhost_glue.zig`) calls them over the C ABI. The ordinary `noxc` never contains these components and `zig build test` does not need them. The plan and progress list are in `project/noxc-nightly-selfhost-plani-2026-11.md`. ## Where to read next | Topic | Page | |---|---| | lexer, parser, module loading | [Compiler front end](https://noxlang.com/docs/internals/compiler/) | | type rules, generics, rewrites | [The type checker](https://noxlang.com/docs/internals/type-checker/) | | memory strategy decisions | [Ownership analysis](https://noxlang.com/docs/internals/ownership/) | | IR, back ends, optimisations | [Code generation](https://noxlang.com/docs/internals/codegen/) | | ARC, cycles, errors, strings | [The runtime](https://noxlang.com/docs/internals/runtime/) | | fibers, work stealing | [The scheduler](https://noxlang.com/docs/internals/scheduler/) | | Python/WASM bridges | [HPy and WASM](https://noxlang.com/docs/internals/hpy-wasm/) | | test suites | [Testing internals](https://noxlang.com/docs/internals/testing/) | | how to send a change | [Contributing](https://noxlang.com/docs/internals/contributing/) | | how a release happens | [Releasing](https://noxlang.com/docs/internals/releasing/) | --- # The compiler front end ## Lexing `compiler/lexer/lexer.zig` turns source text into tokens, including explicit `INDENT`/`DEDENT` tokens. A second entry point (`tokenizeWithTrivia`) additionally records comments and blank lines so the formatter can put them back. The lexer rejects tabs in indentation, non-ASCII identifiers and malformed literals with a position; `compiler/syntax_report.zig` renders errors as `file:line:column` plus the source line and a caret. ## Parsing `compiler/parser/parser.zig` is a hand-written recursive-descent / precedence parser producing the AST defined in `ast.zig`. Notable points: - Expression nesting is bounded (200 levels) so adversarial input cannot overflow the stack; the fuzz tests lex/parse/check random input. - The parser performs **desugaring** that needs no type information: f-strings and `str.format` become concatenations of `str(...)` and format calls; tuple unpacking becomes declarations and indexing; the generator-expression form is marked for the checker; `set` literals and comprehensions map to the prelude's set class; augmented assignment keeps its own node. - Nodes keep enough information (`Binary.is_form`, `fstring` markers, `ListComp.is_genexpr`) for the formatter to print the sugar back as written. - Decorators are parsed on functions, methods, classes and `extern def`, with dotted names. Adding a language feature starts here: grammar and AST first, then the checker rule, the ownership effect, both back ends, a golden test and the spec text — in that order. ## Module loading `compiler/module_loader.zig` resolves imports: the standard library (`nox.*`), project files (relative to the directory with `nox.json`), and dependencies (by alias). It **merges every module into one program**, renaming top-level names per module (`mangled` symbols) so the later stages see a single flat module; imports come first, which is why imported modules' top-level statements run before the importer's. The prelude (`stdlib/nox/core.nox`) is merged into every program. Cyclic imports are rejected. Any new field added to an AST node that is copied during renaming (decorators, defaults, docstrings) must be carried through the loader's rename functions — forgetting this is a recurring class of bug. ## The project layer `compiler/project.zig` finds the project root (`nox.json`), loads the manifest and lock file, and locates the runtime object and standard library relative to the executable. `compiler/pkg/` implements fetching (Git), the package index, global installs, cache pruning and self-upgrade. ## Diagnostics Type errors carry the statement line and span; the language server reuses the same front end, so the CLI and editors agree. Error *kinds* (`TypeMismatch`, `UndefinedFunction`, …) are stable identifiers. Message texts are English and are not part of any compatibility promise. --- # The type checker `compiler/typecheck/checker.zig` enforces mandatory static typing and produces the information code generation needs. It is the largest single component; this page describes its structure and the techniques that keep the rest of the compiler simple. ## What it checks - every declaration, parameter and return has a type; assignment compatibility (`int → float` is the only implicit conversion); - scoping (function and module scope), `break`/`continue` placement, all-paths-return, optional narrowing (`x is None` guards, `and`/`or`/`not`, early exits); - classes: field creation only in `__init__`, single inheritance, method overriding, special-method signatures, structural protocol satisfaction; - generics: inference at call sites, explicit type arguments, monomorphisation of functions, classes and methods; function-typed arguments and lambda return inference; - calls: arity, defaults, keyword arguments (bound by parameter, evaluated in source order), `spawn` data-race pre-checks; - backend-dependent rules (spawn argument types, freestanding import allow-lists via capabilities); - decorator arguments, `extern def` safety (FFI-safe types, `retains`/`@ffi.*`, callback targets), `lowlevel`-only builtins. ## Checker-driven rewriting Many features are implemented by **rewriting the AST after checking**, so every later pass sees only simple constructs. Because the checker receives expressions by value it cannot rewrite them in place; instead it records side tables keyed by the address of a child node and applies them once at the end (`call_expand_apply.zig`): | Side table | Purpose | |---|---| | `call_expansions` | fill default arguments and reorder keyword arguments into positional order | | `call_orders` | the source-order evaluation sequence for calls whose arguments have side effects | | `expr_rewrites` | replace an expression: operator → dunder method call, `str(x)` → `x.__str__()`, `for` over a dictionary → `.keys()`, bound-method values, … | | `stmt_for_rewrites` | give `for` loops a hidden local holding the iterable (strings, dictionaries, `__iter__`, module-level lists) | Because the rewrite happens before ownership analysis, escape analysis, inlining and code generation, those stages needed no change when sugar such as default arguments, operator overloading, comprehensions or lambdas was added. A lambda that captures variables lifts to a closure; a module-level lambda lifts to a top-level function. ## Generics Free functions are instantiated per distinct argument types (`first__int`, `first__str`); classes per type-argument tuple (`Box__int`); methods of non-generic classes per explicit/inferred type argument. Mangled names are computed in **one** place and shared with code generation — computing them twice (once in the checker, once in codegen) was the source of an earlier cross-module bug. Limits: a generic method takes one type parameter. A protocol used as a value type (`list[Shape]`, a field, a variable, a return type) resolves to a synthesized abstract class `Shape__Base` whose methods raise. Assigning a concrete class `C` that satisfies the protocol rewrites the expression to `Shape__Box_C()`: a synthesized subclass of `Shape__Base` with an `inner: C` field whose overrides delegate to `inner`. The fat pointer (object plus method table) is therefore an ordinary single-inheritance class hierarchy, and ownership analysis, ARC, the cycle collector and both backends needed no change. The rewrite is keyed by the address of the expression slot (`assignableOrCoerce` and `call_expand_apply.expr`), so generic instantiations are rewritten independently. Class infos are heap-stable (`*ClassInfo`) because resolving a field type can synthesize another class while a registration still holds a pointer. ## The prelude `stdlib/nox/core.nox` is merged into every program. Rules for prelude functions: generic ones are instantiated only when used, so adding prelude code does not change unrelated programs; non-generic prelude functions must not depend on externs that are unavailable in freestanding builds, and must not return tuples or index lists (older test harnesses merge no stdlib). Adding a class to the prelude renumbers class ids and so changes every IR snapshot — regenerate them deliberately. ## Capabilities and profiles A table maps each standard-library module to the capabilities it needs (`filesystem`, `network`, `process`, `clock`, `entropy`, `threads`, `shared_memory`, `libc_math`, `arch_x86_64`); `@capability.requires("…")` marks individual functions. `--profile hosted` grants everything except architecture-specific modules; `--profile freestanding` grants only capability-free modules. Unknown modules are denied in freestanding builds. --- # Ownership analysis Nox's memory model has no user syntax; the compiler decides, per value, the cheapest safe strategy. This page describes the decision procedure and its guarantees. The user-visible summary is in [Memory](https://noxlang.com/docs/language/memory/). ## The pyramid | Layer | Mechanism | Where | |---|---|---| | 1 | Stack allocation and ASAP destructors | `compiler/ownership/analysis.zig`, `compiler/codegen_qbe/local_escape.zig`, `inlining.zig` | | 2 | ARC fallback | `runtime/alloc/arc.zig` | | 3 | Cycle collector | `runtime/alloc/cycle_detector.zig` | | 4 | `lowlevel` arenas | `runtime/alloc/lowlevel.zig` | ## Layer 1: conservative escape analysis For every allocation the analysis asks whether the value escapes its function: stored in a field or container, returned, captured by a closure, passed to a callee that may retain it, sent to another task, or aliased. The analysis is **conservative**: if ownership or lifetime cannot be proved, the value is promoted to ARC — silently. Promotion is never an error and never visible to the program. Outcomes: - a small fixed-size literal list that never escapes is **stack-allocated** (within a per-frame budget); - other non-escaping values are freed at the exact point of last use (**ASAP destructor**), with no reference count; - everything else is reference counted. Every ASAP decision has golden tests for both the allocation point and the release point. Foreign functions are assumed **not to retain** their arguments unless declared with `retains(...)` / `@ffi.escape`. `noxc explain` prints the decision and reasons for each local (see [Memory](https://noxlang.com/docs/language/memory/#seeing-the-compilers-decisions-noxc-explain)). ## Layer 2: ARC Reference counts are O(1) retain/release with no deep copies. Counts live in a header before the object. On the LLVM backend they are **atomic** (so objects may cross scheduler workers); on QBE, which has no atomic instructions, they are plain and the scheduler is single-threaded. Releases of deeply linked structures use a depth-limited worklist so a long chain cannot overflow a fiber stack. ## Layer 3: the cycle collector Only ARC-managed class instances can form cycles. The collector is a trial-deletion algorithm (Bacon–Rajan, as in Nim's ORC): decrements that do not reach zero register a candidate root; when allocation pressure crosses a threshold (and at exit) the candidates' subgraphs are scanned. Classes that cannot be part of a cycle (decided from the class graph) skip registration entirely. Under the multi-core scheduler the scan runs inside a stop-the-world barrier. ## Layer 4: `lowlevel` A `lowlevel` block gets an arena; heap values created inside belong to it and must not escape (checked at code generation). Typing is unchanged. ## Testing requirements Any ownership change needs: golden tests for allocation and release points; a leak test and a double-free test; the debug allocator ("GeneralPurposeAllocator in safety mode") green; and, if reference counting is touched, the concurrency torture suites. --- # Code generation `compiler/codegen_qbe/` turns the checked, rewritten AST into IR. Despite its name it hosts **both** back ends. ## The emission seam Code generation never writes IR text directly. It calls helpers named `qbe*` (`qbeOp2`, `qbeCall`, `qbeLoadL`, `qbeJnz`, …) that go through `qbe_emit.zig` or `llvm_emit.zig` depending on the chosen backend. The seam handles the differences: QBE's three-address SSA text versus LLVM's typed instructions, calling conventions, `alloca` placement, integer arithmetic flavours, floating-point and atomic operations. Consequences: - a feature is implemented **once**; - both back ends must be verified for every change (the fixture corpus runs on both); - a few operations have back-end-specific lowering where QBE lacks an instruction (atomic reference counts exist only on LLVM; `udiv`/`urem` mapping; 64-bit overflow checks). ## Layout and ABI `abi.zig` and `layout.zig` define the value representations: reference-counted payloads with a header, the packed `str` header (length plus ASCII flag), list headers (length, capacity and a `data` pointer; the header address never moves, see [Lists](https://noxlang.com/docs/apis/internal-abi/)), dictionary layout, class instances (type tag, vtable pointer, fields in 8-byte slots — `@repr("C")`/`@packed` classes use real C layouts), closures (function pointer plus captured environment), tuples (generated structs), error unions (value or exception handle), `Task`/`Channel` objects. These layouts are internal ([Internal ABI](https://noxlang.com/docs/apis/internal-abi/)). ## Major components | File | Responsibility | |---|---| | `registration.zig` | collects declarations, resolves types, computes class layouts, vtables and cyclic classes | | `expr.zig`, `calls.zig`, `stmt.zig` | expressions, calls (including built-ins), statements; arithmetic with overflow policy; printing | | `exceptions.zig` | `raise`, `try`/`except`/`finally`, `with`, `defer`, scope-exit mechanism shared with memory release | | `closures.zig` | closures, lambdas, bound methods, function values | | `ownership.zig`, `local_escape.zig`, `inlining.zig`, `optimizations.zig` | retain/release emission, stack promotion, inlining of small functions, bounds-check elision | | `async_thread.zig` | `spawn`, `await`, channels, `nox.thread`, the multi-core pool | | `http_intrinsics.zig` | the `serve*` family and the generated per-call-site wrappers | | `decorators.zig` | the static decorator/reflection tables | | `ffi_callback.zig` | trampolines for `@ffi.callback` | | `globals.zig` | module-level variables and per-worker globals | ## Semantics that both back ends must share Plain `int` arithmetic wraps; fixed-width `+ - *` trap; conversions are range-checked; `//` and `%` raise `ZeroDivisionError`; keyword arguments with side effects are evaluated in source order; floats print as Python's `repr`. A differential test runs the whole corpus on both back ends and compares output; a conformance test pins down the cases where a divergence would be a bug. ## Error propagation A function that can raise returns a value plus a pending-exception check; every call site emits the check and jumps to the nearest handler or propagates. No unwind tables or landing pads are emitted (invariant 3). Raise analysis (`exceptions.zig`) decides which functions need the check. ## Snapshots `tests/golden/ir_snapshots/` stores the generated IR of every fixture. Any intended IR change is reviewed as a snapshot diff: delete the changed `.ssa` files and run the suite twice (the first run regenerates, the second verifies). Changing the prelude renumbers class ids and so touches every snapshot. --- # Global durum denetimi AGENTS §2.6: runtime gizli/global mutable durum taşımaz, ayırıcıları açıkça alır. Bu sayfa `runtime/` altındaki dosya-seviyesi `var` ve `threadlocal var` bildirimlerinin (v2.0.32'de 82 adet) sınıflandırmasıdır. Onaylı liste `project/global-state-allowlist.tsv`dir; `scripts/check_global_state.py` CI'da yeni bir bildirimi (ya da silinmiş bir satırı) hata sayar. | Kategori | Anlamı | Neden kabul | |---|---|---| | `lazy-lib` | tembel yüklenen dış kütüphane ve CA önbelleği | yüklendikten sonra değişmez, atomik durum korumalı, runtime verisi taşımaz | | `provider` | program başında bir kez kaydedilen işlev işaretçisi | atomik, kullanıcı durumu değil | | `immutable` | sabitlenmiş değişmez nesne | yazılmaz | | `process` | işlem argv'si, Windows dinleme-soketi önbelleği | işlem-geneli OS kaynağı | | `shared-io` | tek `std.Io.Threaded` | `SIGIO`/`SIGPIPE` işleyicisi işlem-geneli | | `tl-sched` | iş parçacığının worker yuvası | M:N zamanlayıcının parçası | | `tl-hpy` | HPy hata metni, hash tohumu | bir `HPyContext` tek iş parçacığına aittir | | `tl-scratch` | JSON için geçici arena ve sınıf kimliği önbelleği | sonuç runtime ayırıcısına kopyalanır | | `diag` | `NOX_STACK_PAINT`, havuz ölçümü | salt-ölçüm | | `freestanding` | çekirdek bootstrap durumu | §2.6'daki belgeli istisna | | `test` | birim test sayaçları | üretim kodu okumaz | | **`tl-errno`** | `errno` benzeri son-işlem durumu ve fiber dışı stdin artığı | **açık borç** | ## Açık borç: `tl-errno` `nox.fs`, `nox.path`, `nox.json`, `nox.gzip` ve `nox.io` son işlemin başarısını (`last_op_ok()`) ve stdin'in okunmamış kalanını bir fiber alanında tutar. Fiber dışındaki (senkron üst-düzey) kod aynı değeri iş parçacığı-yerel bir yedekte tutar. Aynı iş parçacığında çalışan iki runtime bu yedeği paylaşır. Çözüm `RuntimeState`e taşımaktır, ancak `last_op_ok()` API şeklini değiştirir; bu yüzden ayrı bir görev olarak açık bırakıldı (TODO 1.5 çoklu-runtime korpusu bunu ölçer). ## Ayırıcı Çalışma zamanı varsayılan olarak sistem ayırıcısını (`page_allocator`) `RuntimeState.bootstrap_allocator` olarak kullanır; `nox_runtime_init_with_allocator` ve gömme ABI'sindeki `NoxHostAllocator` ([ADR-009](https://noxlang.com/docs/internals/adr/009-embed-allocator/)) bunu değiştirir. `page_allocator`ı doğrudan çağıran yerler: `nox.thread` çocuk runtime'ları ve havuz iş parçacıkları (sistem ayırıcısı, ADR-009), HTTP istemcisinin istek-ömürlü arenası ve `Shared` durumu, `json` ayrıştırma arenası, `Io.Threaded` başlatması. Bunlar runtime'ın yönetilen heap'i değildir (kullanıcı değerlerini taşımazlar), bu yüzden host ayırıcısı kapsamı dışındadır. --- # The runtime The runtime is written in Zig and statically linked into every program (`noxrt.o`; `noxrt-freestanding*.o` for kernels). It follows the Zig rule the project adopts: **allocators are explicit parameters, never globals**. Generated code receives a pointer to a per-program (or per-worker) `RuntimeState` as a hidden first parameter and passes it to every runtime call. ## Memory | Module | Responsibility | |---|---| | `alloc/asap.zig` | `RuntimeState`, ASAP/stack support, leak reporting in debug runs | | `alloc/arc.zig` | reference-counted allocation, retain/release, small-object pools, the depth-limited release worklist | | `alloc/cycle_detector.zig` | the trial-deletion cycle collector, its root table and stop-the-world participation | | `alloc/lowlevel.zig` | arenas for `lowlevel` blocks | | `alloc/dispatch_registry.zig` | class tables for dynamic release/trace | | `alloc/defer_stack.zig` | `defer` bookkeeping | In debug builds the allocator is Zig's `DebugAllocator`: every leaked allocation is reported with a stack trace at exit, which is how most memory bugs in this project were found. Tests must pass with leak and double-free detection on. ## Values - `str.zig` — the packed header (61-bit length and a 2-bit ASCII state), UTF-8 handling, O(1) ASCII indexing, float formatting (`formatFloatRepr`, the shortest round-trip digits) and conversions. - `format.zig` — the Python format mini-language with exact big-integer rounding for `f` and `%`. - `collections/dict.zig`, `list_ops.zig`, `list_sort.zig` — insertion-ordered dictionaries, list operations and a stable sort. ## Errors `errors/handle.zig` defines exception handles (a class tag plus the parent-chain reference used by `except` matching), the unhandled-exception report, `nox_int_overflow_trap` for fixed-width overflow, and `nox_int_pow`. `errors/diag_sink.zig` routes diagnostics so freestanding builds can supply their own sink. ## Concurrency `async_rt/` — fibers (`fiber.zig` and the per-architecture context switches `swap_*.S`), the single-threaded scheduler, channels, thread bridges, the I/O reactor (kqueue/epoll/`WSAPoll`), and the multi-core worker pool. See [The scheduler](https://noxlang.com/docs/internals/scheduler/). ## Standard-library shims `stdlib_shims/` contains the native half of each `nox.*` module that touches the OS: files, processes, time, sockets, TLS (client and server), HTTP client and server, WebSocket client and server, SQLite/PostgreSQL/MySQL (loaded with `dlopen` on first use), crypto, gzip, JSON (parsing via Zig's `std.json`, building Nox values by calling back into a Nox factory), regex, shared memory, atomics and the NNI host (`native.zig`). A shim function is exported with `export fn nox___raw(...)`; the Nox module wraps it. Every export that must survive linking is referenced from `lib.zig` (and `lib_freestanding.zig` for kernels). ## Platform notes Linux and macOS use `epoll`/`kqueue`; Windows uses `WSAPoll` and links `ntdll`, `ws2_32` and `crypt32`; the fiber context switch is hand-written assembly per architecture (x86-64, aarch64). Fiber stacks are 192 KiB with a guard page. ## Freestanding `lib_freestanding.zig` omits everything that needs an OS; memory comes from the kernel-supplied allocator registered with `nox_allocator_install`. The only mutable global state in the runtime is this one-time bootstrap state, documented as the single exception to "no hidden global state". --- # The scheduler Tasks are fibers: small stacks and a hand-written context switch. Two schedulers exist; the language semantics are identical. ## Single-threaded (QBE) One cooperative scheduler on one thread. A task runs until it awaits (a task, a channel operation, or non-blocking I/O); the reactor (`io_reactor.zig`) wakes tasks when sockets become ready. Because nothing runs in parallel, reference counts are non-atomic and module-level state is trivially safe. ## Multi-core M:N (LLVM) A pool of OS worker threads shares a work-stealing scheduler: - **Deques.** Each worker owns a Chase–Lev deque of runnable fibers; idle workers steal from others. - **Atomic reference counts.** Objects may be touched by any worker. - **Fiber-affine globals.** Module-level variables are kept in per-worker blocks. - **Wake-ups.** Completion pipes and self-pipes wake blocked workers; channels use spin-locked buffers that are safe across workers. - **Deadlock detection.** The pool detects the case where every worker is idle and no task can become runnable and reports it instead of hanging. - **Stop-the-world barrier.** The cycle collector needs a consistent view: it requests a barrier, every worker parks at a safe point, the collector runs, workers resume. The barrier is a sense-reversing design that was the source of two real livelocks during development; its tests run repeatedly. - **Pool size.** Chosen at compile time (a small default for programs that merely `spawn`, one worker per core for programs using `serve_multicore*`/`pool_run`) and overridable with `NOX_POOL_WORKERS`. `spawn` argument packing is retain/release-aware: values captured for a task are retained for it so they outlive the spawning scope; the data-race pre-checks in the type checker catch the obvious cases (mutating a collection that a spawned task still reads). ## `nox.thread` `nox.thread.start` and `ThreadChannel[T]` have two implementations behind one source API: independent runtimes per OS thread on QBE (so only scalar-like values cross), and ordinary tasks on the shared pool under LLVM (so lists, classes and dictionaries can be passed). ## Cancellation `task.cancel()` sets a flag; the cancelled task observes it at its next `await` of another task and raises `CancelledError`. Channel operations do not check the flag. ## Blocking calls `time.sleep_ms` and synchronous file operations block their worker. Network operations are non-blocking at the fiber level. A multi-core server therefore keeps serving on other workers while one blocks. ## Testing `worker-pool-test`, `async-rt-test` (a standalone target that also builds on Windows), the stress test, the two concurrency torture suites and the HTTP soak test are opt-in because they are slow; see [Testing internals](https://noxlang.com/docs/internals/testing/). --- # HPy host v1 and WebAssembly Nox can load a native extension that was produced for the `nox-hpy-host-v1` profile. This page is the host contract. QBE and LLVM both pass the pinned fixture on macOS ARM64, macOS x64 (Rosetta), Linux ARM64, Linux x64, and Windows x64 (Wine). Each run printed `42 42 7 9 1 0 255 42`. It does not claim that a CPython extension, NumPy, or Pandas runs unchanged. The direction is one way. An aHPy Universal module (`.hpy0`), a `nox-hpy.json` manifest, and a generated `.nox` facade are consumed by a Nox package. Nox does not load its own modules into Python, does not emit a Python package, and does not embed CPython. There is no Hybrid ABI and no native sandbox. The existing `hpy_*` builtins remain an unsafe developer door; they do not call the package loader. ## v1 surface Profile `nox-hpy-host-v1`, HPy 0.9, Universal ABI. The required capabilities are ABI bits, not a security sandbox: `module-open`, `module-close`, `object-close`, `call-positional`, `error-take`, `extension-object`. Optional bits: `bytes`, `call-keywords`, `hpy-debug`, `hpy-trace`. Value kinds: `none`, `void`, `bool`, `int64`, finite `float64`, `unicode`, and opaque objects. `bytes` is a `list[int]` of values 0–255, including embedded NULs, and is accepted only when the manifest lists `bytes`. A keyword-only parameter is `call_int_keyword(name, key, value)` and is accepted only when the manifest lists `call-keywords`. Positional entry of a keyword-only parameter is `AHPY_NOX007`. Defaults, variadic arguments, and overloads are rejected. Lists, tuples, and dictionaries stay out of this profile: their element ownership is not part of v1, and a container kind is `AHPY_NOX008` before init. The host is 64-bit only. The five triples are `linux-aarch64`, `linux-x86_64`, `macos-aarch64`, `macos-x86_64`, and `windows-x86_64`. A 32-bit ELF, Mach-O, or PE image is `AHPY_NOX006` before `HPyInit_*`, as is an image whose format does not match the selected triple. The checked-in `sample.hpy0` is the macOS ARM64 pin. Another OS builds `sampleext.c` and rewrites that target's digest; it does not load the macOS image. Ownership words in the manifest (`owned`, `borrowed`, `value`) are generator metadata. Nox source does not grow `owned` or `borrowed`. `nox.hpy` exposes `Module` and `Object` as ordinary values. `load_package(root)` opens a package root. `with` closes the module on scope exit, on an error, and on an early return. Closing a module closes the objects it still holds. A second close, or a use after close, raises `HPyError`. The exception's class name is the type and `.message` carries the diagnostic text (`AHPY_NOX001` through `AHPY_NOX008`). Calls are synchronous on the calling fiber. A `Module` is not shared across operating-system threads. The error text is thread-local and is consumed once. Two runtimes do not share an `HPyContext`. Each `load_package` creates its own context and destroys it on close. An HPy `ValueError` (and the other standard types) keeps its type name and message in `HPyError.message`. The context layout is the one locked by `runtime/hpy_bridge/abi_dump.zig`; the backends do not embed a second copy. ## Package identity `nox.json` `requires[]` stays a git identity. The native contract is `nox-hpy.json` at the dependency root. `nox.lock` may carry the schema version, aHPy version, source commit, HPy ABI, target, artifact SHA-256, and module name. An old lock that is not an HPy package still opens. An HPy package without those fields does not install. The digest is checked before the cache accepts the tree and again before `dlopen`. A missing platform artifact does not select another target. Targets are exact: `linux-aarch64`, `linux-x86_64`, `macos-aarch64`, `macos-x86_64`, `windows-x86_64`. The artifact path is relative to the package root (the cache, or the staged copy next to the built executable). The process working directory is not a search path. `..`, a symlink, a wrong size, a wrong SHA-256, or a duplicate target fails before init. If source and a prebuilt binary are both present, the hashed binary is the one that loads. Nox does not recompile the extension. License, notice, and SBOM files are copied when they exist and are not invented. A signature is not required in v1. Build scripts do not receive a registry secret or an unrestricted loader path. A breaking manifest needs a new schema version. An older reader rejects that version before init. ## WebAssembly WASM as a *library import* is separate from WASM as a *compilation target*. Importing a module goes through the embedded interpreter; compiling Nox itself to WebAssembly is `--target wasm32-wasi` ([WebAssembly](https://noxlang.com/docs/tools/wasm/)). Exports go through the same opaque-handle rule as other foreign calls. `runtime/wasm_bridge/` holds the parser and the runtime glue. That bridge is not part of the `nox-hpy-host-v1` package profile. **Interpreter coverage (2.1.65).** The embedded WebAssembly engine is a pure-Zig validator and interpreter (no JIT, no third-party code, so it also runs on iOS and Android). It decodes every section of the WebAssembly 2.0 core except SIMD and threads, validates each function with the specification's typing algorithm before running anything, and executes `i32`/`i64`/`f32`/`f64` arithmetic and conversions, multi-value blocks and returns, linear memory, globals, tables with `call_indirect`, reference types, bulk-memory and sign-extension/saturating instructions. Modules are untrusted: memory and table accesses are bounds-checked, and instances carry limits for fuel (each branch and call costs one), value-stack and call depth, and memory pages. Correctness is checked bit-for-bit against V8 (`scripts/wasm_gen_vectors.py`) and against real compiler output (`scripts/wasm_gen_programs.py`). The current Nox surface is still the single built-in `wasm_call(path, name, arg)`; a persistent instance handle, host functions and WASI are tracked separately. ## Host contract policy `nox-hpy-host-v1` is the supported host profile. It is tied to HPy 0.9 Universal and to the noxc version recorded in `tests/compat/hpy_host/PIN`. A mixed pin (different noxc version, or a different evidence commit) is rejected by `evidenceAgrees`. The pin does not follow aHPy `main`. A breaking manifest change needs a new `schema_version`. An older reader rejects that version before init. Deprecation of a profile is a new profile name, not a silent change of this one. Rollback is the previous pin commit plus its artifact digest, not a moved tag. There is no native sandbox. An extension runs with the process's privileges. Report a host bug in the nox-lang repository. Do not treat `AHPY_NOX00N` as a security boundary. ## Troubleshooting | Result | Meaning | | --- | --- | | `AHPY_NOX001` | Manifest ownership does not match the v1 rule | | `AHPY_NOX002` | Path, symlink, hash, size, or use after close | | `AHPY_NOX003` | Manifest shape, or the export is not declared | | `AHPY_NOX004` | Required capability missing, or `bytes` without the bit | | `AHPY_NOX005` | Two packages, same module name, different digest | | `AHPY_NOX006` | Target or image is not one of the five 64-bit triples | | `AHPY_NOX007` | Call shape: keyword-only used positionally, or the reverse | | `AHPY_NOX008` | Type, non-finite float, bad Unicode, or a byte outside 0–255 | | `ValueError: …` | The extension set that HPy error; the text is kept | ## Author notes Generate the facade against `nox.hpy` only. Do not emit raw `ptr` or `hpy_*` calls into the generated user module. Do not add a reverse path that imports Nox from Python. Do not describe this profile as "CPython extensions run as-is" or as a NumPy compatibility layer. The pinned producer commit and the schema live in `tests/compat/hpy_host/`. The pin moves when aHPy commits the exporter; it does not follow a floating branch. --- # HPy and CPython compatibility: what exists AGENTS §10 describes a tiered target (Tier 0–3) for HPy/CPython extensions. This page states what the code does today so that no page claims more. ## What exists - A **HPy 0.9 Universal ABI host** (`runtime/hpy_bridge/`): the `HPyContext` function table (180 `ctx_*` entries, layout pinned by `abi_dump.zig`), handles that hide object addresses (invariant 4), module loading for the `nox-hpy-host-v1` package profile, error capture per context. - The package flow around it: `nox-hpy.json` manifest, `.nox` facade, `nox.hpy.load_package`, SHA-256 pinning, five target triples (see [HPy host v1](https://noxlang.com/docs/internals/hpy-wasm/)). - A real extension fixture (`sampleext.c`, pinned digest) that runs under QBE and LLVM on five platforms. ## What does not exist - **No CPython C-API emulation layer.** `runtime/cpython_compat/` from the AGENTS repo layout was never created. An extension built against CPython's `Python.h` cannot be loaded. NumPy and Pandas are therefore **not supported**, and no page may say they run "as is". - Tier 1 beyond the HPy surface (PEP 3118 buffer protocol over CPython objects, number/sequence/mapping protocol emulation), Tier 2 (GC hooks, weakref, subclassing across the boundary) and Tier 3 (descriptors, metaclasses, capsules, async protocol) are not implemented as CPython emulation. ## Decision The product target for the HPy path is **`nox-hpy-host-v1` stays a preview profile**: extensions written for HPy (not CPython) with scalar, string, `bytes` and opaque-object values. It leaves preview when (1) at least two independent HPy extensions, not written by this project, pass in CI on the five triples; (2) the context layout stays unchanged for two minor releases; (3) container values (list/tuple/dict) have an ownership contract and a real-extension test. A CPython emulation layer is not started: it needs its own design and a named first consumer, and the tier table stays a roadmap, not a claim. --- # WebAssembly coverage `runtime/wasm_bridge/` is a **library import** (an embedded interpreter that loads WASM modules into a Nox program). Compiling Nox *to* WebAssembly is a separate feature: [WebAssembly](https://noxlang.com/docs/tools/wasm/). This page lists what the interpreter accepts today (v2.1.148); the user-facing API is [nox.wasm](https://noxlang.com/docs/stdlib/wasm/). A module is validated with the specification's algorithm in one pass (`compile.zig`) and rejected with `InvalidModule` before anything runs; an opcode outside the list below is rejected, never silently ignored. A WASM back end for Nox is never added. ## Module format | Part | Status | |---|---| | Header, version, type section (1), function (3), export (7), code (10) | parsed and validated | | Import (2) | functions are bound to Nox host functions (up to 4 `int` parameters, 1 result); other import kinds are rejected | | Table (4), element (9), reference types | supported (`call_indirect`, `table.get/set`, `ref.null/is_null/func`) | | Memory (5), data (11), data count (12) | supported, including shared memories (threads); `memory.grow` is limited by `max_pages` | | Global (6), start (8) | supported (`v128` globals are rejected) | | Custom sections | skipped | ## Value types and instructions `i32`, `i64`, `f32`, `f64`, `v128` (SIMD, inside the module only), `funcref`/`externref`. Multi-value results and block types are supported. - The whole MVP numeric, control-flow (`block`, `loop`, `if`, `br`, `br_if`, `br_table`, `return`, `call`, `call_indirect`), variable, memory and parametric instruction set. - Sign-extension operators, non-trapping (saturating) float-to-int conversions (`0xFC 0-7`), bulk memory (`0xFC 8-17`: `memory.copy/fill/init`, `data.drop`, table equivalents), reference types. - Fixed-width SIMD (`0xFD`, v2.1.98), everything except relaxed SIMD. - Threads (`0xFE`, v2.1.99): shared memory and atomics; since v2.1.155 optionally on real OS threads through the wasi-threads `thread-spawn` contract (see [nox.wasm](https://noxlang.com/docs/stdlib/wasm/#threads-atomics-shared-memory-and-wasi-threads)). - A small opt-in WASI preview1 subset. Not supported (rejected): exception handling, tail calls, GC and function-reference types, memory64, multi-memory, component model, relaxed SIMD, `v128` host-function signatures and `v128` crossing the Nox boundary. ## Errors and limits `Trap` (unreachable, division by zero, out-of-range memory/table access, misaligned atomic, infinite `wait`), `InvalidModule`, `UnsupportedInstruction`, `StackOverflow`, `TypeMismatch`, `ExportNotFound`, `TooManyArgs`, `UnexpectedEof`, `OutOfMemory`, and the fuel limit (`open_with_limits`, default budget counts branches and calls). Memory pages are capped. ## Verification Fuzzing: `tests/fuzz/wasm_parser_fuzz.zig` (parser, instantiation, execution; every single-byte mutation and prefix of small valid modules on each test run). Differential tests against Node's WebAssembly engine on every CI run: 36 904 numeric vectors, 9 330 SIMD vectors, 5 109 atomics vectors, plus compiled programs. See [nox.wasm](https://noxlang.com/docs/stdlib/wasm/#robustness). --- # Testing internals Nox is tested far more heavily than a typical language implementation of its size: roughly 1,200 tests in 180 build steps, plus opt-in stress suites. This page maps them. ## Running them ```sh zig build test --summary all # the whole default suite (a few minutes) zig build test --summary all > out.txt 2>&1 # and read the output before committing ``` The default `zig build test` is the gate every change must pass. After intentionally changing code generation, run it **twice**: the first run regenerates changed IR snapshots, the second verifies them. ## Suites | Suite | Location | What it proves | |---|---|---| | Unit tests | `test` blocks next to the Zig code | each runtime/compiler function (with leak/double-free detection) | | Typecheck goldens | `tests/golden/typecheck_cases/` + `typecheck_golden_test.zig` | the checker accepts valid programs and rejects invalid ones with the expected error kind | | Codegen goldens | `tests/golden/codegen_cases/*.nox` + `.expected`, registered in `fixture_corpus.zig` | source → program output, **on both back ends** | | IR snapshots | `tests/golden/ir_snapshots/` | byte-exact generated IR per fixture | | Ownership goldens | `tests/golden/ownership_cases/` | the escape/allocation decisions | | Formatter goldens | `tests/golden/fmt_cases/` | the formatter's output and idempotence | | Conformance | `backend_conformance_test.zig`, `conformance_cases/` | both back ends agree on tricky semantics (overflow, evaluation order, …) | | Differential corpus | `backend_differential_corpus_test.zig` (`zig build backend-differential-corpus-test`) | the *entire* fixture corpus produces identical output on LLVM and QBE | | Compat | `tests/compat/` | real C, Zig, HPy, WASM and NNI extensions; real HTTP/TLS/WebSocket servers over sockets | | CLI | `tests/cli/` | the `noxc` binary as a subprocess: subcommands, packages, install, upgrade, backends, plugins | | Fuzz | `tests/fuzz/` | the lexer, parser and checker never crash on random input; the WASM parser likewise | | Freestanding | `freestanding_*_test.zig`, `kernel_boot_x86_64_test.zig` | the kernel path, including booting a real image in QEMU | | Docs | `scripts/check_docs.py` | every code block in these docs compiles and its output matches | ## Opt-in, slow suites | Step | What it does | |---|---| | `zig build stress-test` | many rounds of cross-worker channel/task stress | | `zig build concurrency-torture-test`, `concurrency-torture2-test` | seed-driven concurrency torture including thread channels and list transfers | | `zig build http-soak-test` | a multi-core and TLS server under sustained load | | `zig build worker-pool-test`, `async-rt-test` | the scheduler in isolation (the latter also runs on Windows CI) | | `zig build backend-differential-corpus-test` | the full two-back-end comparison | These run in a separate workflow and in the release gate. ## Writing a test for a change 1. A language feature: add a `.nox` fixture plus `.expected` under `codegen_cases/` and register it (the corpus runs it on both back ends); add typecheck goldens for each new error. 2. A memory change: a leak test and a double-free test, with the debug allocator on. 3. An error-handling change: success path, failure path and a `finally`/`with` interaction. 4. A foreign-code change: a test against a real extension in `tests/compat`. 5. A standard-library change: a fixture, and the page in these docs with a checked example. A feature without a golden test is not accepted. ## What the tests have found The most valuable bugs were found by writing real programs, not by unit tests: `for` over module-level lists, a router that ignored query strings, integer power computed through floating point, spawn statements that leaked their handle, `int()` of fixed-width values, `print(None)`, `return` inside `with`. This documentation is itself a test: writing and running every example found several of them, which is why `check_docs.py` is part of the process. ## Performance regression gate `benchmarks/gate.py` runs the core-language kernels (`benchmarks/lang_perf`) and the two standard-library suites (`benchmarks/stdlib_perf`, 39 jobs) and compares them with a checked-in baseline. Install a release build first (`zig build -Doptimize=ReleaseFast`; a Debug runtime is about 100 times slower, and a full `zig build test` leaves `zig-out` in Debug). ```sh benchmarks/gate.py --check # exit status 1 if a job is more than 35% slower than the baseline benchmarks/gate.py --update # rewrite benchmarks/baseline.json (review the diff before committing) ``` The baseline is machine independent where it can be: a job that has a C reference (`stdlib_perf*.c`, compiled with `clang -O2`) is stored as the Nox/C ratio, the others as milliseconds, which only mean something on the same machine. The gate also fails any job that is more than 40 times slower than its C reference. Jobs under 1 ms are treated as noise. ## Front-end diagnostics and the differential runner (noxc-nightly) Two hidden developer commands print the front end's output in a stable form: `noxc tokens [--json] ` (one line per token: `line:col kind start-end "lexeme"`, or `ERROR line:col` with exit code 1 on a lexical error) and `noxc ast ` (parse only, then the AST dump that `build --dump` prints). They are not in the help screen. `scripts/frontend_diff.py` runs a Zig and a Nox front-end component over every `.nox` file in the repository and compares exit code and output (`--component lexer|ast`; `--zig-only` checks the runner itself; `--selftest` proves it catches a difference and shrinks it to a minimal example). `zig build frontend-diff-test` runs the self-check plus a Zig-against-Zig pass. The global `--frontend zig|nox` flag selects the component; the ordinary `noxc` accepts only `zig`. `noxc tokens` also takes `--trivia` (print the comment and blank-line channel the formatter uses). In the nightly binary `--frontend nox tokens` runs the lexer written in Nox (`selfhost/lexer.nox`, generated from `selfhost/lexer.nox.in` by `scripts/gen_selfhost_lexer.py`), and `noxc-nightly lex-bench ` compares its speed with the Zig lexer. `frontend_diff.py --fuzz N --seed S` adds N randomly damaged inputs (broken quotes, tabs, truncated UTF-8) so error paths are compared too; `--sub-args=--trivia` passes extra flags to the sub-command. `frontend_diff.py --component check` compares the whole front half of the pipeline (module loading, parsing, type checking) between the stable `noxc` and `noxc-nightly`, whose default front end is the Nox lexer. `noxc-nightly lex-bench [N] --max-ratio=3.0` fails when the Nox lexer is more than three times slower than the Zig one. --- # Contributing Nox is open source (MIT). This page summarises how to work on the compiler and runtime; the binding rules are in `AGENTS.md` in the repository, which applies equally to human and AI contributors. ## Getting set up ```sh git clone https://github.com/mburakmmm/nox-lang cd nox-lang zig build # needs Zig 0.16; builds noxc, noxlsp, the runtime, installs the stdlib into zig-out/ zig-out/bin/noxc run examples/... # try it zig build test --summary all # the full suite ``` Rebuild with `zig build` after editing `stdlib/**` — `zig-out/bin/noxc` uses the installed copy of the standard library. You also need `qbe` (for the QBE back end) and `clang` or `zig` (for LLVM). ## The workflow for a language change In this order, no skipping: 1. grammar — parser and AST; 2. the type-checker rule; 3. the ownership effect (does the new node create a scope or a lifetime boundary?); 4. IR lowering — **for both back ends**; 5. at least one golden test; 6. the documentation page, and the design-history section if behaviour deviates from the specification. Golden tests are non-negotiable (invariant 7); a change to code generation is not merged without one. ## Rules of the road - **The seven invariants** ([Architecture](https://noxlang.com/docs/internals/architecture/#the-seven-non-negotiable-invariants)) are never traded away for convenience. If a task cannot be done without breaking one, stop and discuss it. - **Ask before architecture.** New language features, memory-model behaviour and ABI changes are proposed first, summarised, and agreed before implementation. Small reversible decisions need no ceremony. - **Zig style.** `zig fmt` before every commit; allocators are explicit parameters; errors use `!T` with per-module error sets; every public function has a test; memory tests run under the debug allocator. - **Native boundaries.** Anything that touches C/WASM/HPy needs an integration test with a real extension. - **No tricks for green.** Do not skip, loosen or delete a test to make a change pass; fix the cause. ## Pull requests State which area the change touches, confirm the definition of done (suite green, golden test added, spec/docs updated), and write explicitly that no invariant is violated. Read the test output before you commit — a red suite is a reason to stop, not to push. ## Every commit is a release The project releases on every commit: `build.zig.zon` is bumped, `CHANGELOG.md` gets an entry, the commit is tagged `vX.Y.Z` and pushed together with the tag. Maintainers handle tagging; see [Releasing](https://noxlang.com/docs/internals/releasing/) for what the release machinery checks. ## Documentation These docs live in `docs/` as Markdown. Add the page to `docs/_toc.yml`, put runnable examples in `nox` blocks (add an `output` block to assert the output; use `nox-fragment` for snippets that cannot run standalone) and run `python3 scripts/check_docs.py` before sending the change. The check also verifies links, the table of contents and that every public standard-library name is documented. --- # Releasing How a version reaches users, and the gates in between. ## Version numbers Semantic versioning (`MAJOR.MINOR.PATCH`, pre-releases like `2.0.0-rc.1`). The single source of truth is `.version` in `build.zig.zon`; the git tag is `v` plus that string. The policy for what each part means is in [Versioning](https://noxlang.com/docs/reference/versioning/) and [Stability](https://noxlang.com/docs/apis/stability/). Bump with `scripts/bump_version.sh {patch|minor|major}` (patch by default, minor for genuine new features). ## The release gate `scripts/release.sh` is the local gate; run it before tagging. | Step | Check | |---|---| | 1 | the version in `build.zig.zon` is valid semver, `CHANGELOG.md` has a `## [version]` entry, the tag does not exist yet, the working tree is clean | | 2 | `zig fmt --check` | | 3 | `zig build` | | 4 | `zig build test` — and no IR snapshot changed | | 5 | `zig build backend-differential-corpus-test` — LLVM and QBE agree on the whole corpus | | 6 | (with `--stress`) stress, both torture suites and the HTTP soak test | | 7 | (with `--tag`) create `vX.Y.Z`, push `main` and the tag | ```sh scripts/release.sh # checks only (a dry run) scripts/release.sh --tag # checks, then tag and push scripts/release.sh --tag --stress ``` ## CI On every push to `main`, `ci.yml` runs the full suite on Linux x86-64, Linux aarch64 and macOS arm64 (all required) and a Windows job (the Debug `zig build test` corpus plus end-to-end smoke tests of both back ends). Extra workflows run the opt-in stress suites and the external-integration fixtures (the Aether and Nyx frameworks compiled against the new compiler). ## Publishing Pushing a `v*` tag triggers `release.yml`: 1. **Gate job** — verifies that the tag, `build.zig.zon` and `CHANGELOG.md` agree, then **waits for the `ci.yml` run on the tagged commit and fails the release unless it succeeded**. A red commit is never published. 2. **Build jobs** — build `noxc`, `noxlsp`, `noxrt.o`, `noxrt-freestanding.o` and the standard library in `ReleaseFast` for macOS arm64, Linux x86-64, Linux arm64 and Windows x86-64 (with explicit `-Dcpu` baselines so the binaries run on older machines), bundle `qbe` where applicable, and upload archives plus SHA-256 files to the **draft** GitHub release (opened by the `create-release` job). The Windows job also builds the **installer** (`packaging/windows/nox.iss`, Inno Setup) and runs `packaging/windows/test-installer.ps1` on it — silent install, reinstall (no duplicate `PATH` entry), uninstall, and a check that the user's `PATH` is restored byte for byte — before uploading `nox-lang--windows-x64-setup.exe` and its SHA-256. A failing installer test stops the release. To iterate on the installer without cutting a release, push to a branch that changes `packaging/windows/**` (or run *Windows installer* manually): it builds the installer from an existing release's archive and runs the same test. **Publishing is atomic.** The release stays a draft, invisible to `noxc upgrade`, the installers and the website, until every core archive (macOS arm64, Linux x86-64, Linux arm64, Windows zip and installer) is uploaded; only then the `publish` job flips it to public and marks it *Latest*. If any build job fails the release stays a draft, so a half-uploaded version is never visible — fix the cause and re-run the failed jobs. (Before v2.0.173 each job published the release as soon as its own archive landed, and `noxc upgrade` could see a "latest" release whose archive for your platform did not exist yet and fail with HTTP 404.) The Homebrew, AUR, AppImage, Snap and site-image jobs run after `publish`. **Signing and SBOM.** Each build job signs its archives with `actions/attest-build-provenance` (keyless, GitHub/Sigstore) before uploading them; the `publish` job generates `nox-lang--sbom.spdx.json` with `scripts/gen_sbom.py`, attaches it to the draft and signs it. `gen_sbom.py` reads the SQLite, QBE and Zig versions from the repository and fails if one cannot be read, and CI runs `gen_sbom.py --check` on every change. The attest steps are required: the release is a draft until `publish`, so a failed signing step never exposes a half-signed version, and re-running the failed job is enough. Users verify with `gh attestation verify` ([Install](https://noxlang.com/docs/install/#verify-where-an-archive-came-from)). 3. Tags containing a `-` (such as `v2.0.0-rc.1`) are published as **pre-releases**, so `noxc upgrade` and the installers keep pointing at the latest stable release. 4. **Homebrew tap job** — for stable tags only, after the build jobs, it generates `Formula/noxc.rb` from the release's `.sha256` files (`scripts/update_homebrew_formula.py`, template `packaging/homebrew/noxc.rb.in`) and pushes it to [`mburakmmm/homebrew-nox`](https://github.com/mburakmmm/homebrew-nox). It needs a repository secret `HOMEBREW_TAP_TOKEN` (a fine-grained personal access token with *Contents: Read and write* on that one repository); without it the job only warns and the release is unaffected. The tap's own CI then audits, installs and tests the formula on macOS arm64, Linux x86-64 and Linux arm64. 5. **AUR job** — for stable tags only, it builds the `noxc-bin` package from the release in a clean Arch Linux container (`packaging/aur/test-in-arch.sh`: `makepkg`, `.SRCINFO` identical to `makepkg --printsrcinfo`, install, run, upgrade guard, remove), then pushes `PKGBUILD` and `.SRCINFO` (`scripts/update_aur_package.py`, template `packaging/aur/PKGBUILD.in`) to `ssh://aur@aur.archlinux.org/noxc-bin.git`. The push needs a repository secret `AUR_SSH_PRIVATE_KEY` (the private half of an SSH key registered in your AUR account); without it only the container test runs. To iterate without a release, push to a branch that changes `packaging/aur/**` (or run *AUR package* manually). 6. **AppImage jobs** — x86-64 and aarch64, each on its own runner: `packaging/appimage/build-appimage.sh` assembles an AppDir from the release archive (checksum verified) and runs `appimagetool`; `test-appimage.sh` runs the result (`version`, `run`, the QBE back end, the `noxlsp` dispatch, the upgrade guard) before `noxc--.AppImage` and its SHA-256 are uploaded to the release. No account or secret is involved. 7. **Snap jobs** — stable tags only, amd64 and arm64: `scripts/update_snap_package.py` writes `snapcraft.yaml` (classic confinement, built from the release archive with `patchelf` so the binaries use the core24 libraries), `snapcraft pack --destructive-mode` builds it and `packaging/snap/test-snap.sh` installs it with `--classic`, runs it and removes it; the `.snap` is attached to the release. If the repository secret `SNAPCRAFT_STORE_CREDENTIALS` exists (`snapcraft export-login --snaps noxc --acls package_access,package_push,package_release -`) the job also uploads to the Snap Store's `stable` channel; this needs the name registered (`snapcraft register noxc`) and [classic confinement approved](https://forum.snapcraft.io/c/store-requests/19) by the Snap Store reviewers first. The upload step never fails the release. To iterate on AppImage, Snap or AUR packaging without a release, push to a branch that changes `packaging//**` (or run the matching workflow manually): each builds from the newest release that has all the needed assets and runs the same tests. Because the workflow concurrency cancels a superseded CI run, a later push can cancel the CI run of an earlier tag and make that tag's release fail its gate; push one release at a time and wait for CI. ## Installers and upgrades `install.sh` and `install.ps1` download the archive for the platform from the latest GitHub release. `noxc upgrade` replaces the running installation with the latest (or a requested) release after verifying the checksum. ## Documentation and website The documentation in `docs/` is built into the website; the site and the noxpkg registry are deployed from `services/`. Docs are checked in CI-adjacent tooling (`scripts/check_docs.py`) so a release never ships examples that do not compile. A stable release also publishes the website image to GHCR (the `site-image` job), and the production machine picks it up on its own; see [Deploying](https://noxlang.com/docs/internals/deployment/#automatic-site-updates). --- # Deploying noxlang.com and the registry This page documents how the project's own web presence is run: the **noxlang.com** site and the **noxpkg** package registry. Both are Nox programs, they run as containers on one machine, and one Cloudflare Tunnel exposes them. Nothing here is needed to *use* Nox; it is for maintainers. ## Topology | Hostname | Service | What it is | |---|---|---| | `noxlang.com` | `noxlang-site` | A [Nyx](https://github.com/mburakmmm/nyx) application (`services/noxlang-site/`) that serves the generated site | | `www.noxlang.com` | `noxlang-site` | Redirects (301) to `noxlang.com` | | `nyx.noxlang.com` | `frameworks-site` | The Nyx guide. Same process as the two rows below; the `Host` header picks the tree | | `aether.noxlang.com` | `frameworks-site` | The Aether guide | | `aura.noxlang.com` | `frameworks-site` | The Aura guide | | `noxpkg.noxlang.com` | `noxpkg` | The package index and admin panel (`services/noxpkg/`) | | `noxpkg.2mtechnology.org` | `noxpkg` | The registry's **previous** name, kept so older `noxc` releases keep working | The stack is described by one Compose file, `deploy/web/docker-compose.yml`, with five services: `noxlang-site`, `frameworks-site`, `noxpkg`, `noxpkg-backup` and `cloudflared`. Containers publish only to `127.0.0.1`; the tunnel is the only way in, and the host has no open ports 80 or 443. It is the same tunnel as before (`10d2b429-9912-44a6-8615-11ef5910ba74`); the framework hostnames are extra ingress rules, not a second tunnel. ## Framework sites `services/frameworks-site/` is one Nyx application. `scripts/build_framework_sites.py` writes three static trees, `public/nyx`, `public/aether` and `public/aura`, from `services/frameworks-site/content/`. They reuse the noxlang.com stylesheet and script. `html[data-site]` swaps the brand color. Every page’s top bar links to `https://noxlang.com`, and the Nox site’s Frameworks menu links back. The process reads `Host` (`nyx.noxlang.com`, `aether.noxlang.com`, `aura.noxlang.com`) and serves that tree. `SITE_NAME=nyx|aether|aura` is the override for a request that arrives without one of those names (a local `curl` to `127.0.0.1:8082`). Content is loaded on the first request, once per worker, from each tree’s `manifest.tsv`. ```sh python3 scripts/build_framework_sites.py ``` DNS for the three names is a proxied `CNAME` to the **existing** tunnel, created in the Cloudflare dashboard before the new ingress will answer: ```text nyx CNAME .cfargotunnel.com aether CNAME .cfargotunnel.com aura CNAME .cfargotunnel.com ``` ## How the site is built The documentation is plain Markdown in `docs/`, ordered by `docs/_toc.yml`. `scripts/build_site.py` turns it into a static tree: ```sh python3 scripts/build_site.py # writes services/noxlang-site/public/ python3 scripts/build_site.py --verify # also compiles and runs the landing-page examples with noxc python3 scripts/check_docs.py # checks every link, page, and ```nox block in docs/ ``` The builder highlights code with a Nox lexer, rewrites links between pages, writes a client-side search index, and emits `manifest.tsv`, the list of files the server will serve. The Nyx app reads that manifest at start-up and keeps every file in memory (about 7 MB), so a request is a dictionary lookup. Nyx supplies the configuration, router, security headers, content-security policy, request ids, rate limiting and `/healthz`. Two properties of Nox's module-level state shape the app. Each scheduler worker has its own copy of module variables, so the content is loaded by *initialiser expressions* (not by assignments in the entry file), and the Nyx application is opened lazily, once per worker, on the first request ([Concurrency](https://noxlang.com/docs/language/concurrency/#the-scheduler)). ## Configuration Copy `deploy/web/.env.example` to `deploy/web/.env` and fill it in. Docker Compose treats `$` in values as a variable reference, so every `$` in the Argon2 hash must be written `$$`. | Variable | Meaning | |---|---| | `NYX_SECRET_KEY` | secret for the site's Nyx app, at least 32 characters | | `NOXPKG_ADMIN_PASSWORD_HASH` | Argon2id hash of the registry admin password (`noxc run services/noxpkg/scripts/gen_admin_hash.nox -- ''`) | | `NOXPKG_SESSION_SECRET` | secret for the registry's session cookie | | `NOXPKG_GITHUB_CLIENT_ID` | client id of the GitHub OAuth App behind `noxc login`. Create it under *GitHub > Settings > Developer settings > OAuth Apps*, tick **Enable Device Flow**; the callback URL is unused (any value works) and no client secret is needed. Leave empty to disable login (and so publishing) | | `NOXPKG_ADMIN_GITHUB` | the administrator's GitHub login; packages listed before accounts existed are assigned to it the first time it signs in | | `NOXPKG_DATA_DIR` | directory with the registry database `noxpkg.db` (default `services/noxpkg/data`) | | `BACKUP_DIR` | where local snapshots are kept (default `services/noxpkg/backups`) | | `RESTIC_REPOSITORY`, `RESTIC_PASSWORD`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | optional off-site backup to an S3-compatible bucket such as Cloudflare R2 | ## DNS and the tunnel `deploy/web/cloudflared.yml` routes the four hostnames above through the existing tunnel. In the Cloudflare dashboard, create these proxied (orange-cloud) `CNAME` records pointing at `.cfargotunnel.com`: ```text noxlang.com CNAME .cfargotunnel.com (apex; Cloudflare flattens it) www CNAME .cfargotunnel.com noxpkg CNAME .cfargotunnel.com nyx CNAME .cfargotunnel.com aether CNAME .cfargotunnel.com aura CNAME .cfargotunnel.com ``` ## Deploying From the repository root on the host: ```sh docker compose -f deploy/web/docker-compose.yml --env-file deploy/web/.env up -d --build docker compose -f deploy/web/docker-compose.yml ps ``` The first build compiles Zig, QBE and `noxc` inside the image and takes several minutes; later builds reuse the cache. Check `https://noxlang.com/healthz` and `https://noxpkg.noxlang.com/index.json` afterwards. To roll back, check out the previous commit and run the same command again. ## Automatic site updates The documentation, the download page and the Playground's compiler are baked into the `noxlang-site` image, so they only change when a new image is deployed. This is automated with a *pull-based* flow that needs no inbound access to the machine and no secrets: 1. **Publish.** On every stable release (`vX.Y.Z`, not `-rc`), the `site-image` job of `release.yml` builds the site image on an arm64 runner and starts it with the production settings. `scripts/site_image_smoke.sh` then checks the contract — `/healthz`, the strict content-security policy on ordinary pages, the relaxed one only on `/playground`, the Playground files and the WebAssembly front end, `/api/release`, and `/version.txt` equal to the tagged version. Only if every check passes is the image pushed to `ghcr.io/mburakmmm/noxlang-site` as `X.Y.Z` and `latest`. The job runs after the release archives have been built, which itself waits for a green CI. 2. **Update.** On the production machine, `deploy/web/update-site.sh` pulls `latest`; if it differs from what is running it restarts **only** the `noxlang-site` service with it and waits (up to two minutes) for the container to become healthy *and* for `/version.txt` to report the new version. If that fails it puts the previous image back (kept as `:previous`), and remembers the bad image so it is not retried every cycle. Overlapping runs are prevented with a lock, a failed pull leaves the site untouched, and `--check` only reports whether an update is waiting. ```sh deploy/web/install-update-timer.sh install # launchd runs update-site.sh every 15 minutes deploy/web/install-update-timer.sh uninstall tail -f ~/Library/Logs/nox-site-update.log ``` macOS keeps launchd agents out of `~/Documents`, `~/Desktop` and `~/Downloads`, so `install` copies what the updater needs (`update-site.sh`, `prune-docker.sh`, `docker-compose.yml` and `.env`, the latter mode `0600`) to `~/.nox-site-update/deploy/` and points the agent there; run `install` again after you change the compose file or `.env`. One-time setup: after the first release has pushed the image, open the package on GitHub (*your profile > Packages > noxlang-site > Package settings*) and set its visibility to **Public**, so the machine can pull it without credentials. The compose file keeps `build:` as well, so `up -d --build` still builds locally if you prefer. **Disk and cache housekeeping.** Every build or pull leaves old image versions, untagged layers and build cache behind, and the machine hosts other projects too. `deploy/web/prune-docker.sh` keeps that bounded: it removes the `noxlang-site` version tags other than `latest` and `previous` (the rollback point), untagged images from our releases (and any untagged image older than 24 hours), and build cache older than 48 hours. It never touches an image a running container uses, nor volumes or networks, and it never fails the update. `update-site.sh` runs it right after every update or rollback and at most once a day otherwise. After a manual `docker compose ... up -d --build`, run `deploy/web/prune-docker.sh` yourself. Tune it with `DANGLING_MAX_AGE` and `BUILD_CACHE_MAX_AGE`. The *download page* does not depend on any of this: it reads the latest GitHub release at request time (`/api/release`, cached for ten minutes), so new archives appear there without a redeploy. `deploy/web/test_update_site.sh` exercises the update script against a fake `docker` and runs in CI. ## Backups The registry's state is `noxpkg.db`. Accounts, comments and bug reports live only there. The package catalog and the publish inbox are mirrored to `index.json` and `inbox.json` after every write (a temporary file, then a rename). Those JSON files are never deleted: the first boot imports them once, and later writes refresh them from the database. `GET /index.json` is rendered from the database in the shape `noxc search` and `noxc add` already read. `ratelimit.txt` is still a small text file. `scripts/backup_noxpkg.sh` runs in the `noxpkg-backup` container: 1. **Every hour** it copies `noxpkg.db` with SQLite's online `.backup`, then writes `index.json` and `inbox.json` from that copy so the archive cannot contain a stale catalog. It checks integrity and that the JSON names match the database, then writes `noxpkg-.tar.gz` with a `.sha256` next to it. A bad copy is refused; the previous snapshot stays. The off-site restic copy is that archive, not a live read of the data directory. Before the database exists, the script still archives the JSON files on disk. 2. **Rotation** keeps the newest 48 snapshots, the newest one per day for 30 days, and the newest one per week for 12 weeks (`KEEP_HOURLY`, `KEEP_DAILY`, `KEEP_WEEKLY`). 3. **Off-site (optional):** when the four `RESTIC_*`/`AWS_*` variables are set, each run also pushes the data to a [restic](https://restic.net) repository. restic encrypts and de-duplicates it, so the bucket holds only ciphertext. Restoring never overwrites: the target directory must be empty or absent, and the archive's checksum is verified first. ```sh # list what exists ls services/noxpkg/backups # restore the newest snapshot into a fresh directory, then inspect it sh scripts/backup_noxpkg.sh restore latest /tmp/noxpkg-restored # prove the newest snapshot can be restored (the container's health check also watches freshness) docker compose -f deploy/web/docker-compose.yml exec noxpkg-backup /usr/local/bin/backup_noxpkg.sh verify ``` To recover production, stop `noxpkg`, restore into an empty directory, replace the data directory with it, and start `noxpkg` again. For an off-site restore, use `restic restore latest --target ` with the same environment variables. `scripts/test_backup.sh` tests the script (snapshot, rejection of corrupt data, rotation, restore, checksum failure) and runs on both busybox and GNU/BSD shells. ## Security notes - The site container runs as an unprivileged user with a read-only root file system; it needs no writable storage. - The content-security policy allows only same-origin resources; the site loads no third-party scripts, fonts or analytics. - The registry approves *metadata*, not code. See [Security model](https://noxlang.com/docs/reference/security/). --- # Mobil toolchain Sayılar bu makinede okundu. Uydurulmadı. ## Apple Xcode 27.0 (build 27A266a). iPhoneOS SDK 27.0. `iPhoneOS27.0.sdk/SDKSettings.plist`: | Alan | Değer | |---|---| | MinimumDeploymentTarget | 15.0 | | RecommendedDeploymentTarget | 17.0 | | DefaultDeploymentTarget | 27.0 | Derleyici `RecommendedDeploymentTarget` değerini kullanır: `17.0`. LLVM üçlüleri `arm64-apple-ios17.0` ve `arm64-apple-ios17.0-simulator`. SDK kökü `xcrun --sdk iphoneos|iphonesimulator --show-sdk-path` ile okunur. ## Android Kurulu NDK: `28.2.13676358` (`darwin-x86_64` önderlemesi). Kurulu platformlar arasında `android-35` vardır. | | | |---|---| | En düşük API | 29 (Android 10: ELF TLS desteği; v2.1.39 — API 24-28 desteği kaldırıldı) | | Hedef API | 35 | | Sayfa | 16 KiB | API 35, Android 15 ile gelen 16 KiB sayfa kuralının hedeflediği seviyedir. Üçlüler `aarch64-linux-android29` ve `x86_64-linux-android29`. Paylaşılan kütüphane `-Wl,-z,max-page-size=16384` ile bağlanır. ## Destek iddiası Bu dört ad `experimental`dir. `supported` ancak o hedefin CI'si yeşilken yazılır. Stable cümlesi [matris](https://noxlang.com/docs/internals/mobile-matrix/) kapısı dolmadan kurulmaz. --- # Mobil destek matrisi Hiçbir mobil hedef `supported` değildir. Stable kapısı aşağıdakilerin hepsi geçmeden açılmaz. | Hedef | Derleme | Çalıştırma | Katman | |---|---|---|---| | ios-arm64 | statik arşiv, LLVM | cihaz laboratuvarı yok, yalnız derleme | experimental | | ios-simulator-arm64 | statik arşiv, LLVM | simülatörde stdlib paketi ve Aura proof/notes/chat | experimental | | android-arm64 | paylaşılan kütüphane, 16 KiB | arm64 emülatörde stdlib paketi ve Aura proof/notes/chat | experimental | | android-x64 | paylaşılan kütüphane, 16 KiB | API 34 x86_64 emülatöründe CI'da stdlib paketi, çalışma zamanı ve yığın/iş parçacığı probe'u (Aura çalıştırılmadı) | experimental | `ios-simulator-x64` ve Android 32-bit bu tabloda yoktur. Metin şekillendirme, emoji ve sağdan sola yerleşim `not supported`. `nox.os` argüman, ortam ve çalışma dizini okur; süreç başlatmaz. Süreç başlatma `nox.process` üzerindedir ve mobil maske onu vermez. `nox.base64` ve `nox.jwt` saf Nox olduğu için mobil hedefte geçerlidir. `nox.mysql` ve `nox.postgres` konak paylaşılan kütüphanesini açtığı için reddedilir. `nox.http` TLS sunucu çağrıları `libssl` açtığı için reddedilir. `nox.http` istemcisi, `nox.tls`, `nox.websocket` ve `nox.smtp` açık kalır. `async def`, `spawn` ve `await` mobil hedefte derlenir ve kütüphane girişinin iş parçacığındaki fiber zamanlayıcısında çalışır. WebSocket el sıkışması bu fiberin içinde çağrılırsa işletim sistemi iş parçacığına alınır. Simülatörde `nox.tls` `example.com:443` el sıkışması `suite 0 pending 0` ile ölçüldü. Aynı paket `base64("foo") == "Zm9v"` ve HS256 doğrulamasını da içerir ve simülatörde yine `suite 0 pending 0` döndü. `android-arm64` emülatöründe aynı paket `suite 0 pending 0` döndü. Simülatör ve arm64 emülatör `mobile_runtime_probe` için `probe 0 pending 0` yazdı: `await spawn` toplamı 42, `nox.thread.start` sonucu 42, `wss://ws.postman-echo.com/raw` çerçevesi `nox`. `nox.smtp` bu ikiliye bağlandı; canlı SMTP oturumu açılmadı. DebugAllocator bir sızıntı satırı bastı ve sürecin çıkış kodunu değiştirmedi. `ios-arm64` ve `android-x64` Skia raster arşivleri bağlandı; bu dilimler çalıştırılmadı. `android-x64` `libnoxapp.so` `PT_LOAD` hizası 16384. Erişilebilirlik: VoiceOver açıkken `aura-ax 12`; arm64 emülatörde `uiautomator` dökümünde `Aura 0.3` ve `Noto Sans` etiketleri var. Emülatör yatay konumda `aura-resize 914.2857 411.42856` ve yeni `aura-frame` yazdı. `am send-trim-memory RUNNING_CRITICAL` `aura-memory 15` yazdı. iOS yaşam döngüsü `aura-background` sonrası yeni `aura-frame` yazdı. Açık iPhone simülatörünün tek ekran kipi dikeydir; yatay geometri reddedildi. iOS bellek uyarısı geri çağrısı bağlıdır, sistem enjekte etmedi. Yığın ve iş parçacığı güvenliği (`scripts/mobile_stack_probe.sh`, `tests/golden/mobile_stack_probe.nox`): iOS simülatöründe ve `android-arm64` emülatöründe 20000 çerçevelik ana-yığın özyinelemesi, 192 KiB fiber yığınına sığan 1500 çerçevelik özyineleme ve 16 `nox.thread` iş parçacığının başlatılıp birleştirilmesi doğru sonuç verir (20000, 1500, 240). Sonsuz özyineleme fiber yığınını taşırsa süreç guard page'de sinyalle sonlanır (iOS simülatörü SIGBUS/138, Android SIGSEGV/139); sessiz bellek bozulması ya da takılma olmaz. Debug ve ReleaseFast çalışma zamanıyla ölçüldü. Ölçülmedi: arm64e işaretçi doğrulaması (yalnızca fiziksel cihazda vardır), fiziksel cihazlar, iş parçacığı-yerel yıkıcıların gözlemlenebilir yan etkisi. Android 16 KiB sayfa boyutu çalışma anında doğrulandı (`scripts/mobile_android_16k.sh`): Android 15 `google_apis_ps16k` arm64 emülatöründe (`getconf PAGE_SIZE` = 16384) yığın probe'u (20000, 1500, 240, taşma SIGSEGV), stdlib paketi (`suite 0 pending 0`) ve çalışma zamanı probe'u (`probe 0 pending 0`) çalışır. Nox çalışma zamanından üretilen paylaşılan kütüphane `-Wl,-z,max-page-size=16384` ile `dlopen` edilir; aynı kütüphane 4096 hizalı üretildiğinde 16 KiB çekirdekte yüklenirken çöker (negatif kontrol: test ayırt edicidir). Fiziksel 16 KiB cihaz ve imzalı AAB ölçülmedi. Ağ matrisi (`scripts/mobile_network_probe.sh`, `tests/golden/mobile_network_probe.nox`, senaryo sunucuları `scripts/mobile_net_servers.py`): iOS simülatörü, `android-arm64` emülatörü ve 16 KiB sayfalı Android emülatörünün üçünde de geçer. IPv4 literal, IPv6 literal (`[::1]`), çift yığınlı ad (`localhost`), bağlantı reddi, bağlantı sıfırlama, boşta zaman aşımı (`HttpTimeoutError`), kesik gövde, kendinden imzalı TLS sertifikasının reddi, geçerli sertifika (`example.com`), çözülemeyen ad ve cevap vermeyen adres (ikisi de `timeout_ms` içinde biter), süreç dondurulup sürdürülürken (SIGSTOP/SIGCONT) süren istek ve ardından aynı süreçte yeni istek. Android'de ayrıca uçak modu: çevrimdışıyken istek temiz hatayla biter, ağ dönünce toparlanır ve istek sürerken ağ kesilirse hata verir. Bu matris üç gerçek hata buldu ve düzeltti: IPv6 literal URL'ler her platformda hata veriyordu; Android yalnızca IPv4 çözümlüyordu (IPv6-only/DNS64 ağlar çalışmazdı); `timeout_ms` DNS ve TCP bağlanmayı kapsamıyordu (çözülemeyen ad 30 sn, kara delik adres 75 sn bloke ederdi). Ayrıca bionic'te `fflush(NULL)` başka bir iş parçacığı `getaddrinfo` içindeyken DNS bitene kadar bloke olduğundan çalışma zamanı yalnızca `stdout`u boşaltır. iOS işi matrisi CI'da koşar. Ölçülmedi: gerçek hücresel ağ geçişi (Wi-Fi'dan LTE'ye), iOS'ta çevrimdışı (simülatör Mac ağını paylaşır), uygulama yaşam döngüsü olarak arka plana alma (süreç dondurma onun yaklaşığıdır). Disk dolu ve SQLite (`scripts/mobile_sandbox_probe.sh`, `tests/golden/mobile_sandbox_probe.nox`): yazma başarısız olduğunda `write_string_atomic` `FsError` verir, hedefin ESKİ içeriği bozulmaz ve kısmi `.nox-tmp` dosyası kalmaz; düz `write_string` `FsError` verir; SQLite büyük ekleme `SqliteError` verir ve veritabanı yeniden açıldığında `integrity_check` temiz ve satır sayısı tutarlıdır. Sınır yokken aynı program TEMP tablo, büyük `ORDER BY` ve `VACUUM` çalıştırır. Üç hedefte geçer: iOS simülatöründe `RLIMIT_FSIZE` (EFBIG) ve GERÇEK ENOSPC (32 MB macOS RAM diski, 64 KB boş bırakılır; boşluk geri gelince baseline yeniden geçer); android-arm64 emülatöründe `RLIMIT_FSIZE`; 16 KiB Android emülatöründe ek olarak `/data` bölümü ~2 MB boş kalana kadar doldurularak gerçek ENOSPC. Bu koşu bir gerçek hata buldu: disk dolduğunda `write_string_atomic` kısmi geçici dosyayı silmeden hata veriyordu (belgesi silineceğini söylüyordu); düzeltildi. SQLite dosya yolları açılışta kök sınırından (`embed.allowsPath`) geçer. SQLite'ın geçici dosyaları (büyük sıralama/`VACUUM`) işletim sisteminin ya da `TMPDIR`/`SQLITE_TMPDIR`in belirttiği dizine gider; gömme `temp_dir`ine ayrıca yönlendirilmez (iOS uygulamalarında `TMPDIR` zaten uygulama kabına işaret eder). Ölçülmedi: gerçek cihaz depolama kotası, `cache`/`temp` kökleri için sistem tarafından otomatik temizlik (iOS purge). Saat, entropi ve log (`scripts/mobile_clock_probe.sh`, `tests/golden/mobile_clock_probe.nox`): iOS simülatöründe ve android-arm64 emülatöründe, 4 sn'lik bir `sleep_ms` sırasında süreç 3 sn dondurulup sürdürülür (SIGSTOP/SIGCONT, arka plana alma benzetimi); monoton saat, uyku dahil monoton saat (`nox.time.boot_ms`) ve duvar saati üçü de ~4 sn ve birbirleriyle 300 ms içinde tutarlı ilerler (ölçülen: 4005/4005/4005 iOS, 4104/4104/4104 Android). `secure_random_hex(16)` iki çağrıda farklı 32 karakter verir, `nox.log` seviye filtresi ve `redact` doğru çalışır. Platform farkı: `instant_now` Linux/Android'de cihaz uykusunu saymaz, Darwin'de sayar; `boot_ms` her yerde sayar (belge: `docs/stdlib/time.md`). Ölçülmedi: gerçek CİHAZ uykusu (suspend) emülatörde/simülatörde yoktur. ## Stable kapısı Kapı, imzalı IPA ve AAB, 16 KiB ölçümü, simülatör ve emülatörde aynı Counter, Notes ve Chat kaynakları, erişilebilirlik, bellek baskısı ve yaşam döngüsü kanıtı durunca kapanır. Kanıt `mobile-evidence/` altındadır. İşler `|| true` ile yeşile zorlanmaz. Mağaza imza anahtarı depoya girmez. Fixture korpusu (`scripts/mobile_corpus.py`, `tests/golden/mobile_cases`, `tests/golden/mobile_corpus_denylist.txt`): `tests/golden/codegen_cases` altındaki tüm programlar (+ mobil kök politikasına uyarlanmış varyantlar) iOS simülatöründe (`simctl spawn`) ve Android emülatöründe (`adb`) çalıştırılır ve çıktı `.expected` ile karşılaştırılır; WASM korpusunun (`zig build wasm-corpus-test`) mobil karşılığıdır. Yerel sonuç: iOS simülatörü ve Android arm64 emülatörü her biri 468 fixture, 462 ok, 1 mobil maskesince reddedildi (`process`), 5 gerekçeli atlama (`os_args_basic`: gömme ana programında argv yok; `wasm_call_builtin`: depo-göreli dosya; üç fixture mobil varyantıyla değiştirildi), 0 hata. Göreli ve `..` içeren yolların reddi bir hata değil politikadır; korpus bunu gevşetmez, test ana programı `NOX_MOBILE_TEMP` ile yalnızca geçici dizin kökünü bildirir. CI: iOS PR işi her değişiklikte, Android x86_64 emülatörü gece (`mobile_android_ci.sh full`). Veritabanı istemcileri (`scripts/mobile_db_probe.py`, `runtime/stdlib_shims/tcp_native.zig`): mobil hedeflerde `nox.postgres` ve `nox.mysql` ana makine kütüphanesi yüklemez; WASM için yazılan saf Zig protokol istemcileri yerel soketlerle çalışır (`tcp_native.zig`, `startTls` aynı soket üzerinde `std.crypto.tls` ile). iOS simülatöründe ve Android arm64 emülatöründe GERÇEK sunuculara karşı doğrulandı: PostgreSQL (SCRAM-SHA-256, basit ve genişletilmiş protokol), MySQL 8.4 (`caching_sha2_password` tam ve hızlı yol, `mysql_native_password`, kaçışlama, hata yolları) ve iki TLS güvenlik denetimi (`sslmode=require` ile kendinden imzalı sertifika `TlsCertificateNotVerified` ile REDDEDİLİR; sunucu TLS'siz iken düz metne DÜŞÜLMEZ). Doğrulanmayan: güvenilir bir sertifikayla başarılı TLS oturumu (simülatöre/emülatöre test kök sertifikası kurulmadı). Sınırlar: MySQL'de TLS yok; okuma zaman aşımı yok. Mobil CI matrisi (`.github/workflows/mobile.yml`, `mobile-nightly.yml`, `scripts/mobile_android_ci.sh`): her PR'da iki iş çalışır. `ios-simulator` (macOS): stdlib paketi, yığın/iş parçacığı, ağ matrisi, sandbox/disk-dolu, saat/entropi/log probe'ları ve iOS kütüphane kontrolleri. `android-emulator` (Linux, KVM): `android-x64` hedefi API 34 x86_64 emülatöründe GERÇEKTEN çalışır (stdlib paketi, çalışma zamanı probe'u, yığın/iş parçacığı probe'u); `NOX_ANDROID_ABI=x64` betikleri x86_64 ABI'ye çevirir. Gecelik iş akışı aynı korpusu API 29 ve 34'te TAM matrisle (ağ, sandbox/disk-dolu, saat/entropi/log) ve AddressSanitizer'lı yığın probe'uyla çalıştırır. Bekçi ve temizlik: her adım `timeout` ile sınırlıdır, iş `timeout-minutes` ile sınırlıdır, betik çıkışında `adb reverse` ve `/data/local/tmp/nox-*` artıkları silinir, emülatörü `android-emulator-runner` kapatır. AddressSanitizer: Android 16 arm64 imajında NDK'nin ASan çalışma zamanı, düz bir C programında bile ilk `pthread_create`te SIGILL ile ölür (işaretçi doğrulaması `autiasp` başarısız; lldb ile `___interceptor_prctl` dönüşünde yakalandı, `-mbranch-protection=none` çözmez). Bu Nox'tan bağımsızdır; bu yüzden ASan altında stdlib paketi (HTTP iş parçacığı kullanır) yalnız x86_64 emülatöründe (PAC yok) gecelik çalışır, arm64'te yalnız iş parçacığı kullanmayan yığın probe'u koşar. Android'de sızıntı denetimi (LSan) yok; gerçek cihaz yok. --- # ADR-MOB-001 Kütüphane modeli Durum: kabul. Mobil hedef bir yürütülebilir dosya üretmez. ## Karar Host bir `NoxEmbedSlot` sahiplenir. Yaşam döngüsü `create`, `start`, `pump`, `request_stop`, `destroy` sırasıdır. Aynı slotta ikinci `create` `NOX_EMBED_ERR_EXISTS` döner. Süreç genelinde gizli bir uygulama örneği yoktur. Kütüphane modu `$main` üretmez; kullanıcı programı `$nox_embed_user_entry` olur ve çalışma zamanını kendisi başlatmaz. `nox_embed_bind`, Nox kütüphanesinin tanımladığı semboldür. Host onu `start` öncesinde çağırır. Çalışma zamanı bu sembolü tanımlamaz. ## Reddedilen Tek süreç-geneli `NoxApp` değişkeni. Geri alma: slot alanını silip eski `main` yoluna dönmek. Masaüstü `main` bu karardan etkilenmez. --- # ADR-MOB-002 Hedef adları Durum: kabul. Dört ad birleşmez. ## Karar `ios-arm64`, `ios-simulator-arm64`, `android-arm64`, `android-x64`. Üçlüler, sayfa boyu ve önerilen dağıtım sürümü [toolchain](https://noxlang.com/docs/internals/mobile-toolchain/) belgesindedir. `ios-simulator-x64` ve Android 32-bit yoktur. ## Reddedilen Tek bir `ios` veya `android` adı. Simülatör dilimi cihaz dilimi diye paketlenmez. Geri alma: `hostedTargetInfo` kayıtlarını silmek masaüstü hedeflerini bırakır. --- # ADR-MOB-003 İş parçacığı ve fiber Durum: kabul. Mobil `async` tek iş parçacığındaki fiber zamanlayıcısında çalışır. ## Karar `runtime/async_rt/swap_aarch64.S` x18'i ofset 168'de saklar ve geri yükler. Apple hedefinde kayıtlı dönüş adresi `xpaclri` ile ham adrese indirilir ve `ret` bu adrese döner. Çağıranın yığın çerçevesindeki imzalı dönüş adresine dokunulmaz. Kütüphane girişi mevcut runtime üzerinde `nox_async_init`, `nox_async_spawn` ve `nox_async_run_to_completion` çağırır; runtime'ı kendisi kurmaz veya yıkmaz. Havuz açılmaz. iOS arka planda sınırsız bir zamanlayıcı çalıştırmaz. Android süreç yeniden kurulunca host yeni bir slot açar; eski kuyruk taşınmaz. ## Reddedilen Mobil `async`ı derleme hatası olarak bırakmak. GPU, kamera, konum, bildirim, push, derin bağlantı, satın alma, metin şekillendirme, emoji ve sağdan sola yerleşim bu kararın parçası değildir. --- # ADR-MOB-004 Yetenek maskesi Durum: kabul. Üçüncü bir profil yoktur. ## Karar Mobil hedef `hosted` üzerinde bir maskedir. Maske `process`, `shared_memory` ve `dynamic_code` vermez. `nox.process`, `nox.sharedmem`, `nox.native`, `nox.plugin` ve `nox.hpy` bu yüzden derleme hatasıdır. Bilinmeyen bir `nox.*` modülü de reddedilir. `nox.fs` ve `nox.sqlite` yalnızca hostun verdiği `documents`, `support`, `cache` ve `temp` köklerinin altında yol kabul eder. `..` reddedilir. Kökler hostun ödünç verdiği dizelerdir. Masaüstünde gömme oturumu yoktur; mevcut çağrılar aynı kalır. HTTPS tarafında sertifika doğrulamasını kapatan bir stdlib anahtarı yoktur. Anahtar zinciri ve Keystore host hizmetidir. ## Reddedilen `extern def` içine yeni bir sandbox koymak. Geri alma: `Checker.mobile_mask` varsayılan `.none` kalır. --- # ADR-MOB-005 Bağlama Durum: kabul. ## Karar iOS çıktısı statik arşivdir. Android çıktısı konumdan bağımsız `libnoxapp.so` olur ve ELF yük hizası en az 16 KiB'dir. İndirilen kod JIT veya `dlopen` ile çalıştırılmaz. Skia Aura deposundadır; bu depo onu gömmez. Lisans ve SBOM, kullanılan Skia arşivinin kendi bildirimine aittir. ## Reddedilen iOS'ta paylaşılan kütüphane ve Android'de çalışma anında inen kod. Geri alma: emit bayraklarını kapatmak. --- # ADR-MOB-006 Olay kuyruğu Durum: kabul. Kamuya açık başlık bu karardan sonra `include/nox_embed.h` oldu. ## Karar `post_event` baytları kopyalar (en fazla 256, geçerli UTF-8). `pump` kullanıcı arayüzü iş parçacığındadır. Süre bütçesi 0 ise o andaki kuyruk boşalır; sıfırdan büyükse mutlak nanosaniye sonuna kadar sürer. Kullanıcı kodu içinden `start`, `pump` veya `destroy` `NOX_EMBED_ERR_REENTRANT` döner. `post_event` kuyruğa yazabilir. `destroy` ikinci çağrıda çökmez. Kapanıştan sonra olay `NOX_EMBED_ERR_STATE` döner. Kuyruk doluysa `NOX_EMBED_ERR_FULL` döner; hata kodları [ADR-009](https://noxlang.com/docs/internals/adr/009-embed-allocator/)da. ## Reddedilen Geri çağrı içinden serbest yeniden giriş. Geri alma: `in_user` bayrağını yok saymak. --- # ADR-MOB-007 Tanı Durum: kabul. ## Karar Hata ayıklama sembolleri yayın işinde ayrı durur: iOS için dSYM, Android için soyulmamış `.so`. Release paketinde bir hata ayıklama soketi açık kalmaz. Günlük, hata ayıklamada OSLog ve logcat köprüsüdür; release'te kısadır. Anahtar malzeme günlüğe veya Nox yığınına yazılmaz. ## Reddedilen Release ikilisine bir debug sunucusu bırakmak. Geri alma: köprüyü hosttan çıkarmak. --- # ADR-MOB-008 Backend Durum: kabul. Mobil backend LLVM'dir. ## Karar Dört mobil ad `--backend qbe` ile desteklenmez. `--emit-asm` ve `-g` de bu adlarda reddedilir. Masaüstü `--target` adları QBE yolunda kalır. QBE, aynı ABI fixture'ları geçmeden açılmaz. ## Reddedilen Mobil `--target`ın sessizce QBE'ye düşmesi. Geri alma: `resolveRelease` içindeki mobil dalı silmek. --- # ADR-MOB-009 Gömme ayırıcısı ve hata sözleşmesi Durum: kabul (v2.0.32). ## Karar `NoxHostConfig.size` düzeni ayırır; ABI numarası 1 kalır. Eski host `sizeof(NoxHostConfigV1)` verir ve sistem ayırıcısı kullanılır. Yeni host `sizeof(NoxHostConfig)` verir ve sonuna eklenen `allocator` alanını doldurur (`NULL` olabilir). Tanınmayan boyut `NOX_EMBED_ERR_VERSION` döner. `NoxHostAllocator` iki geri çağrı taşır: `alloc(ctx, len, alignment)` hizalı bellek döner ya da `NULL`, `free(ctx, ptr, len, alignment)` aynı `len` ve `alignment` ile bırakır. Çalışma zamanının yönetilen heap'i (liste, sözlük, ARC nesneleri, `RuntimeState`) buradan ayrılır. Yerinde büyütme yoktur; çalışma zamanı yeniden ayırır. Hizasız dönen bellek reddedilir ve geri verilir. Ayırıcı iş parçacığı-güvenli olmalı ve `nox_app_destroy` dönene kadar yaşamalıdır. `nox.thread` çocukları ve havuz iş parçacıkları sistem ayırıcısını kullanır ([ADR-003](https://noxlang.com/docs/internals/adr/003-threads/)). Bellek yetersizliği: `nox_app_create` `NOX_EMBED_ERR_NOMEM` döner ve slota dokunmaz. `nox_app_start` host `alloc`ı `NULL` verirse `NOX_EMBED_ERR_NOMEM` döner; uygulama `created` kalır, host ayırıcıyı düzeltip `start`ı yeniden deneyebilir ya da `destroy` çağırabilir. Sızıntı olmaz. Hata kodları: `NOX_EMBED_ERR_FULL` kuyruk doluyken `post_event` döner (olay kopyalanmaz, sonra yeniden denenir). Durdurulmuş uygulama `ERR_STATE` döner. `NOX_EMBED_ERR_EXCEPTION` giriş noktası veya olay işleyicisi dönerken bekleyen bir Nox istisnası olduğunu bildirir. Nesne bekleyen kalır; host `nox_exception_take` ile alır. `pump` bu durumda durur, kalan olaylar kuyrukta kalır. ## Reddedilen Host ayırıcısını sürüm 2'ye taşıyıp ABI numarasını artırmak: eski host'ları kırar. Tüm çocuk çalışma zamanlarına host ayırıcısını yaymak: çağrıların hangi iş parçacığından geldiği host sözleşmesine eklenmeliydi; ayrı görev olarak açık. ## Dosya sandbox'ı: kanonik yol Gömme oturumunda `nox.fs` ve `nox.sqlite` yolu, metinsel denetimden sonra `realpath` ile kanonikleştirilip kanonik köklere karşı yeniden denetlenir. Sembolik bağ kökün dışını gösteriyorsa yol reddedilir. Henüz olmayan hedefte var olan en uzun önek çözülür. Kanonikleştirilemeyen yol reddedilir. --- # ADR-010 Güvenilmeyen kaynak: `noxc run --sandbox` Durum: kabul (v2.0.43). Kapsam: TODO 7.2 ve 7.3. ## Karar `noxc run --sandbox` derlenen ikiliyi işletim sistemi düzeyinde kısıtlanmış bir süreçte çalıştırır. Derleme güvenilirdir (kullanıcı kodu çalıştırmaz). Kısıt ikilinin çalışmasına uygulanır ve `extern def` ile `lowlevel` dahil tüm yerel kodu kapsar. `extern def`e "yarım güvenli mod" eklenmez; sınır işletim sistemidir. Varsayılanlar: ağ yok; yazma yalnızca `$TMPDIR`; okuma sistem kitaplıkları, çalışma dizini, ikilinin dizini ve `$TMPDIR`. Ev dizini ve `/etc` okunamaz. Açma bayrakları: `--allow-net`, `--allow-write=DİZİN`, `--allow-read=DİZİN` (mutlak yol; tırnak, parantez ve ters bölü yok). Bayraklar `--sandbox` olmadan reddedilir. Platformlar: macOS `sandbox-exec` (SBPL profili, `deny default`). Linux `bwrap` (bubblewrap): salt-okunur kök, yeni `/tmp`, `--unshare-net`. Windows desteklenmez. Araç yoksa ya da platform desteklenmiyorsa program çalıştırılmaz ve açık hata verilir: "sandbox istendi ama uygulanamadı" durumunda kısıtsız çalıştırmak güvenli değildir. Ağ kapalıyken başlatıcı `NOX_SANDBOX_NO_NET=1` ayarlar. Zig'in `std.Io` katmanı beklenmeyen `EPERM`i programcı hatası sayıp süreci düşürdüğünden, `nox.http`, `nox.tls`, `nox.smtp` ve `nox.websocket` bağlanmadan önce bunu denetler ve reddi temiz bir bağlantı hatasına (`HttpError`, `TlsError`...) çevirir. ## Sınırlar Bu bir capability sistemi değildir: eklenti `capability` bildirimleri hâlâ rıza meta verisidir ([Plugin API](https://noxlang.com/docs/apis/plugin-api/)). Sandbox CPU, bellek ve süre sınırlamaz. Linux yolu birim testlidir ama CI'da gerçek `bwrap` ile çalıştırılmaz (GitHub runner'larında kullanıcı ad alanları kısıtlı olabilir). ## Reddedilen `extern def` çağrılarını sarmalayan süreç içi filtre: yerel kod filtreyi atlar. Kapsayıcı imajı zorunluluğu: kurulum yükü; kapsayıcı kullanmak isteyen `docker run` ile `noxc run`ı zaten birleştirebilir. --- # ADR-011 `nox.lock` imzalama Durum: kabul (v2.0.43). Kapsam: TODO 7.1. ## Karar Yayıncı bir Ed25519 anahtar çifti üretir (`noxc sign keygen `: gizli tohum `$NOX_HOME/keys/.key`, kip 0600, asla üzerine yazılmaz; açık anahtar `.pub`). `noxc sign lock --key [dizin]` `nox.lock` baytlarının SHA-256'sını `"nox-lock-v1\n"` alan ayracıyla imzalar ve ayrık `nox.lock.sig` yazar (`nox-sig-v1`, `signer=`, `sig=<128 hex>`). Parmak izi, açık anahtarın SHA-256'sının ilk 16 baytıdır (32 hex). Tüketici güven kökünü kendi makinesinde tutar: `noxc sign trust ` anahtarı `$NOX_HOME/trusted/.pub` altına koyar. Otomatik ilk-kullanımda-güven (TOFU) yoktur; güven açık bir komutla verilir, parmak izi yayıncıyla başka bir kanaldan doğrulanmalıdır. `noxc sign verify [dizin]` çevrimdışı doğrular ve yalnızca geçerli imzada 0 döner. İptal: `noxc sign revoke ` parmak izini `$NOX_HOME/revoked.txt`e ekler; iptal her zaman güvenden önce gelir. Anahtar yenileme: yeni anahtarı güvenilir ilan et, eskisini iptal et, kilidi yeni anahtarla yeniden imzala. ## Sınırlar Bu, imzanın var olduğunu ve kilit dosyasının imzadan sonra değişmediğini kanıtlar; paketin kodunun iyi niyetli olduğunu kanıtlamaz. `noxc fetch`/`add` imzayı henüz otomatik zorunlu kılmaz ve noxpkg sunucusu yayıncı anahtarını hesaba bağlamaz; ikisi sonraki adımdır (hesap altyapısı v2.0.28'den beri var). İptal listesi yerel bir dosyadır, bir dağıtım kanalı değildir. ## Reddedilen Merkezi kök anahtar: tek hata noktası ve anahtar saklama sorumluluğu. İmzayı `nox.lock` içine gömmek: imzalanan baytlar imzayı içerirdi; ayrık dosya bunu önler. --- # ADR-012 WASM derleme hedefi Durum: kabul. Nox kodu `--target wasm32-wasi` ile LLVM üzerinden WebAssembly'ye derlenir. ## Karar - WASM bir **derleme hedefidir**, ikinci bir arka uç değildir. Yol: aynı tiplenmiş IR → `.ll` → `zig cc -target wasm32-wasi` (wasi-libc + `noxrt-wasm32-wasi.o`) → `.wasm`. QBE'ye WASM arka ucu eklenmez (AGENTS İlke #5); `--backend qbe`, `--emit-asm` ve `-g` bu hedefte hatadır. - Hedef `wasm32`'dir, `wasm64` değildir. Nox'un derlenmiş kodu her yerde 64-bit sözcük kullanır (işaretçiler dahil); wasm32'de işaretçi 4 bayttır. İkisi şöyle bağdaşır: - **Çağrı noktası uyarlaması.** `scripts/gen_wasm_abi.py` runtime'ın `export fn` imzalarını tarar ve `compiler/codegen_qbe/wasm_abi_table.zig` tablosunu yazar (`--check` CI'da güncelliği doğrular). `llvm_emit.zig` bir `$sembol` çağrısında tablodaki gerçek imzayı bildirir: işaretçi/`usize`/32-bit argümanlar `trunc i64→i32`, sonuçlar `zext`. libc için (`printf`, `strcmp`) küçük bir elle tablo vardır; `printf` her çağrıda variadic imzayla yazılır. - **Geri çağrı tipleri.** Derlenmiş kodun adresini runtime'a verdiği yerlerde (`$Sınıf_release`, dispatch tabloları, kapanış başlıkları, görev girişleri) fonksiyon işaretçisinin imzası derlenmiş fonksiyonunkidir (işaretçi = `i64`). Runtime bu tiplerde `abi_ptr.Arg` (`wasm32`'de `u64`) kullanır. - **Sekiz baytlık yuvalar.** Nesne alanları, liste elemanları, iz arabelleği çocukları ve global yuvalar her zaman 8 bayttır (`FIELD_SLOT_SIZE`); runtime bunları `abi_ptr.Slot` ile okur/yazar. - **Statik veri.** `ptrtoint ... to i64` wasm32'de statik ilklendiricide desteklenmez; vtable ve metadata sabitleri `{ i32 adres, i32 0 }` çiftleri olarak yazılır. - Varsayılan kipte ARC düz (atomik olmayan) yükle-topla-sakla ile çalışır: tek iş parçacıklıdır; M:N havuzu, `nox.thread` OS iş parçacıkları ve fiber yığın değiştirme yoktur. Bu ilk karardır; sonradan `--asyncify` (gerçek fiber, ADR-014) ve `--threads` (paylaşımlı bellek, atomik ARC, M:N, ADR-015) kipleri eklendi ve yalnızca onlarda geçerli değildir. - Asenkron (`spawn`/`await`/`Channel`) varsayılan olarak `runtime/async_rt/bridge_wasm.zig`deki **iç içe çalıştırma benzetimiyle** çalışır (gerçek fiber için `--asyncify`, ADR-014): bir görev, onu bekleyen görevin yığınında sonuna kadar çalışır. Bir görev, yığında kendi altında bloke olan bir görevin sonucunu bekliyorsa ilerleyemez ve "deadlock" bildirilir. Sıra FIFO'dur ve deterministiktir. - Runtime dar bir kümedir (`runtime/lib_wasm.zig`): asap/arc/döngü çözücü/errors/str/format/dict/list, ve stdlib kabuklarından strings, math, os, path, time, random, json, unicode, atomic, io, fs, crypto, regex, gzip. Soket, süreç, `dlopen`, paylaşılan bellek, HPy/WASM köprüleri ve OpenSSL yoktur. - Olmayan modüller (`nox.http`, `transfer`, `reflect`, `router`, `tls`, `websocket`, `smtp`, `sqlite`, `postgres`, `mysql`, `process`, `sharedmem`, `native`, `plugin`, `hpy`) ve `hpy_*`/`wasm_call` yerleşikleri **derleme zamanında** açık bir iletiyle reddedilir (`Checker.wasm_target`); bağlayıcı hatası kullanıcıya sızmaz. - Değişmez ilkeler aynen geçerlidir: ownership sözdizimi eklenmedi, `lowlevel` dinamik tip kaçışı değildir, unwind tablosu / landing pad üretilmez (hata yayılımı örtük error-union zinciri), C eklentilerine ham işaretçi verilmez, gizli global durum yoktur. Gömülü WASM yorumlayıcısı (`wasm_call`, bir WASM modülünü Nox'a içe aktarma) ayrı bir mekanizmadır ve bu hedefte yoktur. ## Doğrulama `zig build test` içinde `tests/golden/wasm_target_test.zig` (duman kümesi), opt-in `zig build wasm-corpus-test` ile tüm `codegen_cases/` korpusu (`node` + WASI). Korpusta üç bilinçli fark: `thread_spawn_ordering` (gerçek iş parçacığı yok), `task_local_basic` (zamanlayıcı sırası), `mathx_trig_log_constants` (musl `exp(1.0)` 1 ULP). ## Bilinen sınırlar - Transandantal matematikte (`exp`, `sin`, ...) sonuçlar wasi-libc/musl'e aittir ve platform libm'den son basamakta ayrılabilir. - Kullanıcı `extern def` ile native kütüphane bağlayamaz; wasm32 ABI tablosunda olmayan bir sembol çağrısı 64-bit işaretçi tipleriyle kalır. - Nox'un çekirdeğindeki `round` fonksiyonu wasi-libc/compiler-rt'nin `round` sembolüyle aynı adı taşıyordu (v2.0.81'e kadar yalnızca wasm'da, yalnızca `round` için bir IR son geçişiyle yeniden adlandırılıyordu). v2.0.86'dan beri bu bir genel sembol politikasıdır (tüm hedefler, iki backend): bkz. [Sembol adları](https://noxlang.com/docs/reference/symbols/). Geri alma: `qbe_target.hostedTargetInfo`daki `wasm32-wasi` kaydını ve `build.zig`deki `wasm-rt` adımını silmek. --- # ADR-013 `wasm32-freestanding` ve `nox_host` Durum: kabul (kullanıcı kararı: Nox'a özel import ad alanı). `--target wasm32-freestanding`, WASI'ye ve libc'ye bağlı olmayan bir WebAssembly modülü üretir; dış dünya yalnızca `nox_host` ad alanındaki import'lardır. ## Karar - Aynı LLVM yolu (ADR-012): `.ll` → `zig cc -target wasm32-freestanding` + `noxrt-wasm32-freestanding.o` (`runtime/lib_wasm_freestanding.zig`). Giriş `_start` (`runtime/wasm_libc.zig`); `main(1, ["nox"])` çağırır ve çıkış kodunu `nox_host.exit` ile verir. Tek dışa aktarım ayrıca `nox_host_abi_version`dır. - **Host sözleşmesi** (`runtime/wasm_host.zig`, sürüm 1): | import | imza | anlam | |---|---|---| | `write` | `(fd, ptr, len) -> i32` | 1 stdout, 2 stderr; yazılan bayt ya da `-1` | | `read` | `(fd, ptr, len) -> i32` | yalnız fd 0; `0` dosya sonu, `-1` hata | | `clock_ms` | `(kind) -> i64` | 0 duvar saati (epoch ms), 1 monoton | | `random_fill` | `(ptr, len)` | kriptografik rastgele bayt | | `sleep_ms` | `(ms)` | tek iş parçacıklı kipte host anında dönebilir | | `exit` | `(code)` | dönmez | İş parçacıklı modüller (`wasm32-freestanding-threads`, ADR-015) ek olarak `thread_spawn(arg) -> i32` içe aktarır ve `nox_host_thread_start(tid, arg)` dışa aktarır; paylaşımlı `env.memory` kullanırlar. Host, `nox_host_abi_version()`ı okuyup desteklemediği bir sürümü reddeder. Sürüm artışı kırıcı değişikliktir (yeni import eklemek değildir: bilinmeyen import host'ta tanımlı değilse modül yüklenmez, bu da açık bir hatadır). - **Çekirdek ayırıcı**: freestanding çıplak donanım değildir; `std.heap.wasm_allocator` (`memory.grow`) ile `nox_runtime_init_with_allocator` yolu kullanılır (`asap.zig`). - **libc yerine**: `printf` (yer tutucular `%lld %llu %d %u %s %c %g %f %%`), `strcmp`, ve eksik libm (`atan2`, `tan`) `wasm_libc.zig`dedir; kalan matematik Zig compiler-rt'den gelir. `from "m"` bildirimleri için `-lm` verilmez. - **Ortam**: işletim sistemi yoktur. `nox.os.getenv`/`set_var` modüle özel, başlangıçta boş bir tabloyla çalışır; `arg(0)` `"nox"`, `current_dir()` `"/"`. Gerçek dosya sistemi yoktur; v2.0.147'den beri `nox.fs` ve dosya tabanlı `nox.sqlite` çalışma zamanının bellek içi sanal dosya sistemi üzerinde çalışır (`runtime/wasm_vfs.zig`; host import'u gerekmez, ömrü varsayılan olarak program ömrüdür (host isteğe bağlı olarak dışa aktarımlarla önyükleyip anlık görüntüsünü alarak kalıcı kılar, v2.0.148), `/` ve `/tmp` başlangıçta vardır). Ağ/süreç modülleri ADR-012'deki gibi. - **Çalıştırıcı**: `compiler/wasm_host.mjs` tek dosyalık, bağımlılıksız ES modülüdür (Node CLI + tarayıcı için `createHost`/`runNox`). `noxc` bunu gömer; `noxc run --target wasm32-freestanding` onu `node` ile çalıştırır. Nexus Engine gibi başka bir host aynı tabloyu uygular. ## Reddedilen - WASI preview1'i aynen kullanmak: "freestanding" ayrımı anlamsızlaşır, host izin/limit denetimi WASI'nin kaba izinlerine bağlanır. - WASI Component Model / wasi-http: araç zinciri büyük, ayrı bir faz. Geri alma: `qbe_target.hostedTargetInfo`daki kaydı, `build.zig`deki ikinci `addWasmRuntimeChain` çağrısını ve `runtime/wasm_*.zig` dosyalarını silmek. --- # ADR-014 WASM'da gerçek fiber: Asyncify Durum: kabul (kullanıcı kararı: "thread kipi olmayanlar için Asyncify"). `--asyncify`, wasm32 hedeflerinde (`wasm32-wasi`, `wasm32-freestanding`) yerel M:1 fiber zamanlayıcısını gerçek yığın değiştirmeyle çalıştırır. ## Sorun WebAssembly'de yığın değiştirme (fiber) yoktur. ADR-012'nin "iç içe çalıştırma" benzetimi (varsayılan) görevleri çağıranın yığınında sonuna kadar çalıştırır; yığında kendi altındaki bir görevi bekleyen görev (karşılıklı kanal beklemeleri, `nox.thread` sleep sırası) ilerleyemez ve zamanlama native'den ayrışabilir. ## Karar - `noxc build --target wasm32-wasi --asyncify` (ya da `wasm32-freestanding`): çalışma zamanı varyantı `noxrt--asyncify.o` seçilir ve bağlamadan sonra `wasm-opt --strip-dwarf --asyncify --pass-arg=asyncify-removelist@*nox_asyncify_run_main* --pass-arg=asyncify-ignore-imports -O2` çalışır. İç adlar `-asyncify` (`qbe_target.hostedTargetInfo`); `wasm-opt` (Binaryen) PATH'te yoksa derleme açık bir iletiyle durur. - **Binaryen'in `asyncify.*` import'ları modülün içinde tanımlanır**; çıktı host'tan hiçbir ek import istemez. Her WASM motoru (Node, wasmtime, wasmer, tarayıcı, Nexus Engine) modülü olduğu gibi çalıştırır. - `runtime/async_rt/asyncify.zig`: `swap(old, new)` çağıran akışı kaydeder (`__stack_pointer`, Asyncify arabelleği, kök) ve yığını açar; en dış sürücü `nox_asyncify_run_main` (Asyncify dönüşümünden muaf) sıradaki akışın kökünü yeni gölge yığında başlatır ya da `start_rewind` ile sarar. Her fiber kendi gölge yığınına (`fiber.zig` `STACK_SIZE`) sahiptir; arabellek (256 KiB) yalnızca askıdayken tutulur ve havuza döner. - `fiber.zig` wasm32'de `nox_swap_context` yerine `asyncify.swap`, fiber kökü olarak `WasmRoot` kullanır. `scheduler.zig`/`channel.zig`/`bridge_native.zig` değişmeden çalışır (M:1 kipi); iç içe benzetim (`bridge_wasm.zig`) yalnızca `--asyncify`siz varyantta kullanılır (`wasm_options.asyncify`). - Görev girişlerinin işaretçi argümanı wasm32'de Nox'un 64-bit sözcüğüdür (`abi_ptr.TaskArg`); 64-bit atomikler `atomics` özelliği olmayan wasm'de düz yükle/sakla ile sağlanır (`atomic_compat.zig`). - Giriş: `__main_argc_argv` (wasi) ve `_start` (freestanding) artık çalışma zamanındadır (`wasm_entry.zig`); IR sarmalayıcısı kaldırıldı. ## Sonuç Tüm korpus (`wasm-corpus-test`) her dört wasm varyantında native `.expected` ile aynı çıktıyı verir; asyncify varyantlarında yalnızca libm (`mathx_trig_log_constants`, musl `exp`) ayrışır — `thread_spawn_ordering` ve `task_local_basic` artık native ile aynı sıradadır. ## Maliyet Asyncify, modülün çağrı zincirini bütünüyle dönüştürür; her akış değişimi, akışın çağrı derinliği ile orantılı çözme/sarma yapar. Ölçüm (`benchmarks/wasm/RESULTS.md`, Apple M4, Node 26): CPU-bağımlı kernellerde (`fib`, `loop`, `mandel`, `collatz`) varsayılan wasm'a göre +0-4% süre ve boyut farkı yok (`wasm-opt -O2` modülü küçültür); askıya alma sıklığı yüksek yüklerde maliyet belirgindir: `async_task_churn` (500 bin spawn/await) varsayılan iç içe çalıştırma benzetimine göre 2,6x yavaş. İlk tahmindeki "%30-50" CPU-bağımlı kodda gerçekleşmedi. Yine de varsayılan değildir (`wasm-opt` bağımlılığı, askıya alma maliyeti). Paralellik (birden çok iş parçacığı) için ayrı bir kip gerekir (`--threads`, ADR-015). **Hata dersi (v2.0.84):** `swap` her askıya almada kendi gölge yığın çerçevesini sızdırıyordu (sürücü yığın işaretçisini `swap`in İÇİNDE okunan değere kuruyor, yeniden girişte önsöz/epilog simetrik çalışıyordu); ReleaseFast'te 32 bayt/askıya alma, 8 MiB gölge yığın 2^18 görev sonra taşıp `memory access out of bounds` veriyordu. Debug çalışma zamanında görünmüyordu. İşaretçi artık çağıranın içinde (satır içi) okunur ve `wasm-rt` Debug derlemede de optimize (ReleaseSafe) üretilir; `async_task_churn_long` fixture'ı (300 bin görev) hem asyncify hem threads hedeflerinde koşar. ## Reddedilen - Yığın değiştirme önerisi (WasmFX / stack-switching): motor desteği henüz yaygın değil. - Asyncify'ı varsayılan yapmak: `wasm-opt` bağımlılığı ve çalışma zamanı maliyeti. Geri alma: `wasm_options.asyncify` ve `*-asyncify` hedef kayıtlarını silmek; `asyncify.zig` yalnızca bu varyantta derlenir. --- # ADR-015 WASM'da gerçek paralellik: `--threads` Durum: kabul (kullanıcı kararı: "wasi-threads tarzı gerçek M:N; host tarafını kendi API'mizle yazalım"). `noxc build --target wasm32-wasi --threads`, yerel M:N çalışma zamanını (iş çalan havuz + fiber'lar) WASM'a taşır. ## Karar - Hedef adı `wasm32-wasi-threads` (`--threads`, `--asyncify`i içerir): çalışma zamanı `noxrt-wasm32-wasi-threads.o` (`+atomics +bulk_memory`, `-fno-single-threaded`), bağlama `-mcpu=generic+atomics+bulk_memory -Wl,--shared-memory,--import-memory,--max-memory=1 GiB,--export=wasi_thread_start` + `wasm-opt --asyncify`. `wasm32-wasi` ve `wasm32-freestanding` (`wasm32-freestanding-threads`): freestanding'de başlatma `nox_host.thread_spawn(arg) -> tid` içe aktarımı ve `nox_host_thread_start(tid, arg)` dışa aktarımıdır (ADR-013); işçi sayısı varsayılan sabittir (ortam değişkeni yok). - **Host sözleşmesi** (WASI-threads ABI'si; wasmtime 50 `-Sthreads`ı kaldırdığından host'u Nox sağlar): modül paylaşımlı `env.memory` içe aktarır ve `wasi::thread-spawn(arg) -> tid` ister; host her çağrıda yeni bir iş parçacığında aynı belleğe bağlı yeni bir örnek kurar ve `wasi_thread_start(tid, arg)`ı çağırır. `compiler/wasm_host.mjs` bunu Node Worker'larıyla uygular (gözetmen iş parçacığı + `BroadcastChannel` ile `proc_exit`; ana wasm iş parçacığı da bir Worker'dır, böylece atomik beklemedeki bir iş parçacığı çıkışı engellemez). Başka bir host (Nexus Engine) aynı iki parçayı sağlar. - **Kendi iş parçacığı uygulamamız** (`async_rt/thread_spawn.zig`): Zig 0.16'nın `WasiThreadImpl`i kullanılmaz. Gölge yığın işaretçisini ayrılan yığın bölgesinin ALT ucuna kurar (yığın aşağı büyüdüğünden yalnızca 64 KiB kullanılabilir, ötesi komşu bloğu ezer) ve `std.Io.Threaded` futex'ine dayanır (Zig tip hatası). Burada blok (TLS + 1 MiB yığın) sıfırlanır (`__wasm_init_tls` yalnızca `.tdata`yı kopyalar), giriş `callconv(.naked)` yazılır — YENİ örneğin `__stack_pointer`ı tüm iş parçacıkları için aynı statik tepedir, sıradan bir Debug önsözü bu ortak bölgede çerçeve açıp `arg`ı eş zamanlı başlayan iş parçacıklarının birbirinin üstüne yazmasına yol açıyordu — ve iş parçacığı kendi Asyncify sürücüsü altında çalışır. - **64-bit atomikler**: Zig 0.16 wasm32'de `@atomicRmw(u64, ...)`i derlemez; ARC başlığı (64-bit) ve zamanlayıcı sayaçları `async_rt/atomic64.zig` aracılığıyla satır içi `i64.atomic.*` ile erişilir (tek iş parçacıklı wasm'de düz erişim). Üretilen Nox kodunda ARC `atomicrmw` olarak kalır (LLVM `+atomics` ile `i64.atomic.rmw.*` üretir). - **Ayırıcı**: `wasm_mt_alloc.zig` — `memory.grow` üstünde boyut sınıflı serbest listeler + `memory.atomic.wait32/notify` tabanlı tek kilit (Zig'in `WasmAllocator`ı çok iş parçacıklıda derlenmez); kök dosyadaki `os.heap.page_allocator` geçersiz kılmasıyla tüm çalışma zamanına yönlendirilir. Panic işleyicisi minimal (`wasm_panic.zig`; varsayılan `Io.Threaded`e dayanır). - Asyncify durumu iş parçacığı başınadır (`threadlocal`); bir fiber work-stealing ile başka bir işçide sarılabilir (arabellek + gölge yığın paylaşımlı bellektedir). `printf` kilit altında tek `fd_write` ile yazar (`wasm_threads_libc.zig`; wasi-libc stdio'su iş parçacığı güvenli değildir). İşçi sayısı `NOX_POOL_WORKERS` (varsayılan: `$main` havuzu için küçük sabit, `serve_multicore`/`pool_run` için 4; wasm'de CPU sayısı sorgulanamaz). - Tanılama: `NOX_WASM_NAMES=1` işlev adlarını çıktıda tutar (wasm yığın izleri adlı olur). ## Sonuç Korpus (`wasm-corpus-test`) yerel `--release` M:N denylist'iyle (zamanlayıcıya bağlı 4 fixture + libm farkı) 0 FARK. 4 eşit görevle (4 işçi) tek iş parçacıklı Asyncify'a göre ~2,7x hızlanma ölçüldü (`benchmarks/wasm/RESULTS.md`: 3,01 sn -> 1,10 sn). Bedeli: tek işçide atomik ARC/paylaşımlı bellek yüzünden bazı yükler yavaşlar (`collatz` 0,89 -> 1,39 sn) ve boş görevlerde fazla işçi çekişme yaratır (`async_task_churn` 1 işçide 0,31 sn, 4 işçide 0,68 sn). ## Sınırlar - Tarayıcıda `SharedArrayBuffer` için COOP/COEP başlıkları gerekir. `wasm_host.mjs`'in `runNoxThreads`ı `wasm32-freestanding-threads` için tarayıcı host'u sağlar (Chromium'da doğrulandı). Tasarım dersi: ana wasm iş parçacığı bir Worker'dır ve tüm iş parçacığı Worker'larını SAYFA oluşturur; iç içe Worker'larda çocuğun betik yüklemesi ebeveynin olay döngüsüne bağlıdır ve ebeveyn `atomic.wait`te bloke olunca çocuk hiç başlamaz (ilk deneme böyle kilitlendi). - `detach` edilen iş parçacıkları bir hurda listesinde tutulur; iş parçacığının SON bellek yazısı (`exited`, naked giriş kuyruğu) görüldükten sonra sonraki `spawn`/`detach`te blokları geri verilir. Liste bağlıdır ve sınırsızdır (v2.0.82'ye kadar 64 kayıtlık sabit diziydi ve fazlası sızıyordu); 200 iş parçacığını art arda başlatıp birleştiren `thread_spawn_stress` fixture'ı her iki threads hedefinde koşar. - Dosya tanıtıcıları WASI örneği başınadır (Node'da): bir iş parçacığında açılan dosya diğerinde görünmez. - Tamamlanma sinyali (`pool_run` dış yolu) pipe yerine futex bayrağıdır (`completion_pipe.zig`); işçileri uyandıran self-pipe wasm'de yoktur, boşta işçiler kısa beklemelerle yoklar. Geri alma: `wasm32-wasi-threads` kaydını ve `wasm-rt`teki beşinci çalışma zamanı nesnesini silmek. --- # ADR-016: WASM'da host yetenekleri ve derleme zamanı yetenek yasağı Durum: kabul edildi (2026-11-04). Bağlam: [ADR-012](https://noxlang.com/docs/internals/adr/012-wasm-target/) (hedef), [ADR-013](https://noxlang.com/docs/internals/adr/013-wasm-host/) (`nox_host`). ## Karar 1. **Modüller WASM'da derlenir; yetenekler host'tan gelir.** Daha önce `nox.http` gibi modüller bir tabloyla (`WASM_UNAVAILABLE_MODULES`) derleme zamanında tamamen reddediliyordu. Bu, WASM'ı genel amaçlı bir hedef yapmayı engelliyordu: `router`, `web`, `reflect` ve `http` tipleri saf Nox'tur ve soketsiz de değerlidir (yönlendirme, handler testi, çerezler). Artık modül derlenir; yalnızca gerçek bir yetenek gerektiren çağrı (soket) host'a bağlıdır. Host yeteneği sağlamıyorsa çağrı anında yakalanabilir bir hata (`HttpCapabilityError`) fırlatılır. 2. **Çalışma zamanı sembolleri stub'lanır, imza birebir korunur.** `runtime/stdlib_shims/http_wasm.zig`, gerçek `http_client.zig`/`http_server.zig`/`http_stream.zig` sembollerinin her birini aynı imzayla ihraç eder ve "yetenek yok" döner (istemci: `error_kind = 4`; sunucu: tanı + null). `scripts/check_wasm_http_stubs.py` ad ve imza eşitliğini denetler (CI). Gerçek bir yetenek (ör. `fetch`) eklendiğinde stub'ın gövdesi bir `nox_host` import çağrısına bağlanır; Nox tarafı ve ABI değişmez. 3. **Derleme zamanı yasağı her hedefte.** `--deny-capability` / `NOX_DENY_CAPABILITY` denetleyicideki mevcut yetenek sınıflandırmasının (`MODULE_CAPABILITIES`, `@capability.requires`) üzerine bir "reddedilen küme" ekler. WASM'a özel değildir; güvenilmeyen kodu derleyen her ortam için (playground, CI sandbox) geçerlidir. 4. **İki katman.** Derleme zamanı yasağı (derleyici) ve host'un ilgili import'ları hiç vermemesi (çalışma zamanı) birbirinden bağımsızdır; biri atlansa diğeri korur. ## Neden ayrı bir ADR Mevcut profil (`hosted`/`freestanding`) ve mobil maske sistemi, derlenen *hedefin* ne sağladığını tarif eder. WASM'da sağlayıcı derleme zamanında bilinmez (aynı `.wasm` Node'da, tarayıcıda ya da wasmtime'da çalışır), bu yüzden "sağlanıyor mu" sorusu çalışma zamanına kayar; derleme zamanı yalnızca *yasak* tarafını bilir. ## Sonuçlar - `nox.http` ailesi 6 WASM hedefinin hepsinde derlenir ve fixture korpusu native ile aynı çıktıyı verir (yönlendirme, `web` yapı taşları, `reflect`, akışlı yanıt, istek hata yolları). - Kalan reddedilen modüller (`tls`, `websocket`, `smtp`, `postgres`, `mysql`, `process`, `sharedmem` (v2.0.159: mysql dahil hepsi taşındı, yalnızca `sharedmem` kaldı); `native`/`plugin`/`hpy` hiçbir zaman) aynı modele taşınacaktır (`sqlite` v2.0.146'da amalgamation'ın statik bağlanmasıyla eklendi): sanal dosya sistemi v2.0.147'de çalışma zamanının içinde (host import'u olmadan), `fetch` tabanlı HTTP istemcisi v2.0.149'da (yalnızca `--asyncify` freestanding; yetenek host'un `nox_host_caps_set` çağrısıyla açılır, varsayılan kapalı) eklendi; sırada WebSocket istemcisi. - Playground: tarayıcıda derleyicinin ön yüzü çalışır ve üretilen modül `--deny-capability` ile derlenir. --- # Platforms What is supported, what is tested, and the known gaps. ## Back ends by situation | Situation | Back end | |---|---| | macOS or Linux, hosted, `clang` **or `zig`** on `PATH` | **LLVM** (`.ll` → `clang -O2`, or `zig cc -O2`), the default | | `--backend qbe` | QBE (`.ssa` → `qbe` → `cc`) | | freestanding profile, desktop `--target`, `--emit-asm`, `-g` | QBE (automatic) | | `ios-arm64`, `ios-simulator-arm64`, `android-arm64`, `android-x64` | LLVM only; `--backend qbe` is an error | | `wasm32-wasi`, `wasm32-freestanding` (and their `-asyncify` variants `wasm32-wasi-asyncify`, `wasm32-freestanding-asyncify`, selected by `--asyncify`) | LLVM only (`zig cc`); `--backend qbe`, `--emit-asm` and `-g` are errors ([WebAssembly](https://noxlang.com/docs/tools/wasm/)) | | Windows | **LLVM** through `zig cc -target x86_64-windows-gnu` when `zig` is on `PATH` (default); QBE with MinGW `cc` otherwise | | neither `clang` nor `zig` installed | QBE (automatic, with a note) | Both back ends run the whole golden corpus and must agree on program output, including fixed-width overflow (a trap on both) and plain `int` wrap-around ([Backends](https://noxlang.com/docs/tools/backends/)). ## Support tiers | Platform | Hosted programs | CI | |---|---|---| | macOS arm64 | yes (LLVM or QBE) | full test suite | | Linux x86-64 | yes (LLVM or QBE) | full test suite | | Linux aarch64 | yes | full test suite | | Windows x86-64 | yes — LLVM (`zig cc`) and QBE, end to end (classes, lists, dictionaries, tasks, f-strings, exceptions, TLS and WebSocket); installer and zip releases | the whole Debug `zig build test` corpus on `windows-latest`, plus end-to-end LLVM/QBE smoke tests | | riscv64 | hosted Linux (`--target linux-riscv64`, static musl, QEMU user-mode smoke: class, list, dictionary, loop ordering and `spawn`/`await`). Freestanding boots in QEMU `virt` (see [Freestanding](https://noxlang.com/docs/tools/freestanding/)) | QEMU user-mode smoke CI; not the full corpus | | WebAssembly (`wasm32-wasi`, `wasm32-freestanding`) | `.wasm` WASI command, or a libc-free module that talks to its host through `nox_host` imports; `--asyncify` gives real fibers through `wasm-opt`; `--target wasm32-wasi-threads` and `wasm32-freestanding-threads` (`--threads`) add parallel M:N threads through shared memory; sockets, child processes and servers are opt-in host capabilities (default off), and there are no native libraries ([WebAssembly](https://noxlang.com/docs/tools/wasm/)). The compiler itself also runs in a browser tab ([Playground](https://noxlang.com/docs/tools/playground/)). Tests in `zig build test` (Node and, where available, PostgreSQL and MySQL servers), the whole corpus under `zig build wasm-corpus-test` (Node WASI) | smoke tests; corpus is opt-in | | iOS arm64 and iOS Simulator arm64 | library only (`--emit-obj` or `--emit-static-lib`). Not a third profile | experimental; not `supported` | | Android arm64 and Android x64 | `libnoxapp.so`, 16 KiB ELF alignment | experimental; not `supported` | macOS x86-64 is expected to work (`macos-x64`) but is not part of CI or the release matrix: there is no prebuilt archive for Intel Macs, so build the compiler from source ([Installing](https://noxlang.com/docs/install/#from-source)). **Freestanding** (bare-metal) builds exist for x86-64, aarch64 and riscv64 (all three boot in QEMU as part of the test suite): an ELF with the Zig runtime and a kernel-provided allocator. The x86-64 path is proven by booting a real kernel image in QEMU as part of the test suite ([Freestanding](https://noxlang.com/docs/tools/freestanding/)). ## Toolchain requirements | To… | You need | |---|---| | compile and run Nox programs | a C toolchain for linking (`cc`); `clang` or `zig` for the LLVM back end; `qbe` is bundled for macOS/Linux | | build the compiler from source | Zig 0.16 | | use SQLite / PostgreSQL / MySQL | `libsqlite3` / `libpq` / `libmysqlclient` installed at run time (loaded on first use) | | use `serve_tls` | an OpenSSL (`libssl`, `libcrypto`) at run time; set `NOX_OPENSSL_LIB` to a specific library path if needed | ## Known constraints 1. **No bundled C compiler.** `clang` is not shipped; the driver falls back to `zig cc` and then to QBE. 2. **Windows** runs the whole Debug `zig build test` corpus and separate end-to-end smoke tests; it does not yet mirror every ReleaseFast/stress job from the macOS/Linux matrix. Under Node's WASI, `nox.fs.read_dir` is not available on Windows ([WebAssembly](https://noxlang.com/docs/tools/wasm/)). 3. **Multi-core parallelism** is a property of the LLVM back end; QBE programs run tasks on one thread. 4. `extern def`, `lowlevel`, NNI plugins and dependencies with native code run with full authority ([Security](https://noxlang.com/docs/reference/security/)). ## Reporting a platform problem Include `noxc --version`, the platform, whether `--backend qbe` reproduces it, and the smallest `.nox` program that shows it. --- # Security model Nox gives you memory safety and static typing **inside the language**. It is not a sandbox. This page states exactly where the guarantees stop, so you can decide what to trust. ## What Nox guarantees (pure Nox code) Mandatory static types, automatic memory management (no use-after-free or double-free from Nox code), bounds-checked list and string indexing, trapping fixed-width integer overflow, checked division by zero, and no unwind tables or ownership syntax to get wrong. ## Where the guarantees stop — the trust boundary | Mechanism | Authority | What Nox checks | |---|---|---| | `extern def … from ""` | raw native code with full OS authority | type marshalling and error translation only; the native function itself is **not** constrained | | `lowlevel` blocks | change the *allocation strategy*; `extern def` calls inside run with full native authority | types are still fully checked | | NNI plugins (`nox.native`) and Plugin API plugins (`nox.plugin`) | a shared library with full native authority | handles are opaque and generation-checked, so a plugin never sees a pointer into Nox's heap — but it is not sandboxed; Plugin API capabilities are *consent*, not enforcement | | HPy/CPython extensions and WASM modules | native code / WASM linear memory | opaque handles only; no raw `PyObject*` crosses; WASM is isolated to its linear memory | | `nox_allocator_install` (freestanding) | supplies **all** heap memory | not validated — a wrong allocator corrupts the whole program | **Dependencies.** A `nox.json` dependency may declare its own `extern def`s (and so may its transitive dependencies), and its code runs as part of your program. Adding a package means trusting its code. `nox.lock` pins the exact commit of every dependency and `require_signed_commit` can demand a signed commit — these protect against a moved tag or branch, not against what the code does. There is no signing of packages, no audit and no capability system in 2.0 (the same trust model as npm, PyPI and crates.io). **The registry.** noxpkg approves *metadata*; approval does not mean the code was reviewed ([noxpkg](https://noxlang.com/docs/tools/noxpkg/)). ## The standard library - `nox.fs` and `nox.os` perform **no path validation**. If a path can come from an untrusted source, confine it with [`nox.path.safe_join`](https://noxlang.com/docs/stdlib/path/#confining-untrusted-paths) before calling them (it rejects `..`, symbolic-link escapes and sibling directories such as `/srv/dataevil` for the root `/srv/data`). - `nox.process` runs the program and arguments you give it with your authority; there is no shell, but never take the program name from untrusted input. - SQL: always pass values through `Statement.bind_*`; table and column names cannot be bound and must come from your code. - `nox.template` escapes for HTML text and quoted attributes only. - `nox.random` is not cryptographically secure; use `nox.crypto.secure_random_hex`. SHA-1 is available for interoperability only. - `nox.jwt.verify` checks the signature but not `exp`/`nbf`/`aud`; enforce claims yourself. - HTTP servers cut off clients that stall while reading or writing; put a reverse proxy in front for public services and use TLS (`serve_tls`, or terminate TLS at the proxy). ## Practical guidance 1. Treat `extern def` and every dependency that contains one like a C dependency: review, pin and prefer small, audited ones. 2. Keep native calls behind a narrow Nox wrapper that validates arguments (lengths, ranges, UTF-8) before crossing the boundary. 3. Run untrusted Nox *source* with `noxc run --sandbox` (no network, writes only to `$TMPDIR`, no access to your home directory; [ADR-010](https://noxlang.com/docs/internals/adr/010-sandbox/)). Plain `noxc run` executes it with your authority. 4. Load plugins only from sources you trust; declare and grant the minimum capabilities. 5. Keep secrets out of source control; read them from the environment. ## Registry gates and incident response What the registry does today: a submission is moderated before it appears in the index; approval covers the *metadata* (name, repository, description), not the code; the index carries no version, so what you install is decided by your `nox.json` and pinned by `nox.lock` (git commit and SHA-256 of the tree). The lock file is the provenance record of a build: it names exactly which commit of which repository was used. If a package is found to be malicious or compromised: (1) the maintainers remove or hide the entry from the index, which stops new installs through `noxc add` and `noxc search`; (2) existing projects keep working from their lock file, so the advisory names the affected repository and commits and tells users to update the lock; (3) the fix and the advisory are published in the `CHANGELOG` and the repository's security advisories. A package that declares `extern def` or a `bin` entry runs native code with your authority (see the trust boundary above); read it before adding it. `noxc sbom` (since v2.1.153) writes a CycloneDX 1.5 SBOM listing every locked dependency with its commit and whether it contains native code (`extern def`, `lowlevel`, `bin`). **Publisher keys and attestations (since v2.1.154).** `noxc sign keygen` + `noxc sign register` bind an Ed25519 key to your registry account (a GitHub-authenticated publisher); `noxc publish` then signs a statement `{name, repo, ref, commit, SBOM SHA-256}` and the registry stores it only if the signing key is registered, active, and the name is yours. Consumers run `noxc sign check` to re-verify each locked commit's attestation locally (the server is not trusted for the verdict) and can pin keys with `noxc sign trust`; revoked keys show as `KEY REVOKED`. `noxc fetch`/`add` do not require attestations yet. Still not built: automatic scanning at publish time (design: `project/registry-guvenlik-tasarimi-2026-11.md`). ## Reporting vulnerabilities Please report security problems privately to the maintainers (see the repository's security policy and contact on GitHub) rather than in a public issue. ## Not in 2.0 `extern def` has no in-process sandbox: the boundary is the operating system (`noxc run --sandbox`). Plugin capabilities are consent metadata, not enforcement. `nox.lock` can be signed and verified offline (`noxc sign`, [ADR-011](https://noxlang.com/docs/internals/adr/011-lock-signing/)); `noxc fetch` does not yet require a signature, and the registry does not yet bind publisher keys to accounts. --- # Versioning and stability policy This is the long-form policy; [Stability and compatibility](https://noxlang.com/docs/apis/stability/) summarises it as a matrix. ## Version numbers Nox follows [Semantic Versioning 2.0.0](https://semver.org): `MAJOR.MINOR.PATCH`. - **MAJOR** (`X.0.0`) — may contain incompatible changes (see "What counts as a major change"). - **MINOR** (`x.Y.0`) — adds backward-compatible functionality: new syntax, a new standard-library module or function, a new CLI subcommand. No previously valid `.nox` source breaks. - **PATCH** (`x.y.Z`) — bug fixes, performance and documentation. No correct program's observable behaviour changes. Pre-release versions (`2.0.0-rc.1`) carry no compatibility promise. ## The source-compatibility guarantee Within one MAJOR version, a valid `.nox` program that builds and runs under `X.0.0` builds and behaves the same under every later `X.Y.Z`. This covers the language syntax and semantics (the set of programs the checker accepts never shrinks), the signatures and documented behaviour of the standard library, the `nox.json`/`nox.lock` formats and the existing behaviour of `noxc` subcommands. ### What is not covered - **The internal runtime ABI** — `noxrt.o`, `nox_*` symbols, reference-count headers, object layouts, QBE/LLVM IR. A Nox program is always rebuilt from source; separately compiled Nox objects of different versions are not guaranteed to link. **Exceptions, stable from 2.0:** the [Nox Native Interface](https://noxlang.com/docs/apis/nni/) (`include/nox_nni.h`), the Plugin API manifest, and the documented `extern def` C-ABI mapping. - **The text of diagnostics.** An error's *kind* (for example `TypeMismatch`) is stable; its wording may improve in any release. Tools must use `noxc`'s exit status, never parse messages. - **The format of `--dump`/`-v` output**, `noxc explain` and similar developer tools. - **Third-party packages.** A package's own API stability is its author's responsibility; `nox.lock` guarantees reproducible builds regardless. - **The Zig toolchain version** needed to *build* the compiler. ## Standard-library classes that frameworks construct Classes that frameworks and tests construct directly (`HttpRequest`, `HttpResponse`, `Row`, `Statement`, `Context`, …) keep their existing constructor parameters for the whole major version. New parameters are added only **with default values**, and fields are only added, never removed or renamed. The same holds for objects the runtime constructs and hands to your code. ## Deprecation A feature or function is marked deprecated (in the reference and the changelog) for **at least one MINOR release** before removal, and removed only in the next MAJOR release. A feature deprecated in 1.3 can disappear in 2.0 at the earliest and never in any 1.x. 2.0.0 removed the names deprecated during 1.x ([Migrating](https://noxlang.com/docs/whatsnew/migrating/)). ## What counts as a major change Anything that makes a previously valid program fail to compile or behave differently: removing or renaming a public name, narrowing a type, changing evaluation order or numeric semantics, tightening a rule so that accepted programs are rejected. Fixing a documented-incorrect behaviour that no correct program could rely on is a patch. ## "Every commit is a release" From 1.0 on, every commit on `main` is a version: it bumps `build.zig.zon`, adds a `CHANGELOG.md` entry, is tagged `vX.Y.Z` and published once CI is green on that commit ([Releasing](https://noxlang.com/docs/internals/releasing/)). A published version is never altered or deleted — a mistake is fixed by a new PATCH release. ## Supported versions The newest release of the latest MAJOR (and the latest MINOR of the previous MAJOR for security fixes, once there is one) is supported. `noxc upgrade` moves you to the newest stable release. --- # Environment variables ## Compiler and tools | Variable | Used by | Meaning | |---|---|---| | `NOX_HOME` | `noxc` | data directory for the package cache, global installs and `installed.json` (default `~/.nox`) | | `NOX_RESOURCE_DIR` | `noxc` | use this directory instead of the one next to the executable to find the runtime object and standard library | | `NOX_INDEX_URL` | `search`, `add` | the package index to query: an `https://…/index.json` URL or a local file (default `https://noxpkg.noxlang.com/index.json`) | | `NOX_PUBLISH_API_BASE` | `publish`, `login`, `logout`, `whoami` | base URL of the registry's API (default `https://noxpkg.noxlang.com`); credentials are saved per server | | `NOX_DENY_CAPABILITY` | every subcommand | same as `--deny-capability`: comma-separated capabilities the compiler rejects (`fs`, `net`, `process`, ...) | | `NOX_NO_BROWSER` | `login` | when set, `noxc login` does not try to open a browser (same as `--no-browser`) | | `NOX_RUN_CACHE_MAX_MB` | `run`, `test`, `cache prune` | size cap in MB for the `noxc run`/`noxc test` binary cache under `$NOX_HOME/cache/run` (default 512; `0` = no cap). Entries unused for 14 days are removed regardless; entries used in the last 10 minutes are never removed | | `NOX_UPGRADE_API_BASE`, `NOX_UPGRADE_DOWNLOAD_BASE` | `upgrade` | override where releases are looked up and downloaded (for mirrors and tests) | | `NOX_ALLOW_INSECURE_TRANSPORT` | package/upgrade fetches | permit non-TLS transports (testing only; never in production) | | `LC_ALL`, `LC_MESSAGES`, `LANG` | `noxc --help` | a value starting with `tr` selects Turkish help; diagnostics and status lines stay English | ## Installer | Variable | Meaning | |---|---| | `NOX_INSTALL_DIR` | where `install.sh` / `install.ps1` unpack Nox (default `~/.nox-lang`) | | `NOX_VERSION` | install a specific release tag instead of the latest | ## Programs you compile | Variable | Meaning | |---|---| | `NOX_POOL_WORKERS` | number of scheduler worker threads under the LLVM back end and `wasm32-wasi-threads` (overrides the compile-time default) | | `NOX_WASM_NAMES` | with `--asyncify`/`--threads` (wasm): set to `1` to keep function names in the `.wasm`, so wasm stack traces are readable | | `NOX_STACK_PAINT` | when set, measures fiber stack use and prints `NOX_STACK_HWM_BYTES=` at exit | | `NOX_OPENSSL_LIB` | full path of the OpenSSL library to load for `serve_tls` | | `NOX_STRESS_ROUNDS` | number of rounds for the opt-in stress test | Programs read their own environment with [`nox.os.getenv`](https://noxlang.com/docs/stdlib/os/); nothing else in the standard library depends on environment variables. ## Services (noxpkg) `NOXPKG_ADMIN_PASSWORD_HASH` (an Argon2id hash for the admin login) and `NOXPKG_SESSION_SECRET` (the session-cookie secret) configure the registry ([noxpkg](https://noxlang.com/docs/tools/noxpkg/)). --- # Symbol names A top-level Nox `def` becomes a **global symbol** in the object file, under its plain name (`$name` in QBE, `@name` in LLVM). If a C library symbol of the same name is called by the runtime or by generated code, the user function would take its place at link time: `def printf(...)` would silently break `print`, `def getenv(...)` would hijack the runtime's environment lookup, `def read(...)` would replace the `read` used by `nox.io`, and on WebAssembly a signature mismatch makes the call trap. ## Policy The **SYMBOL** of a top-level function whose name is on the **reserved-name list** — made of the runtime symbols of standard C, POSIX, libm and the target systems (Darwin, glibc/musl, Android, Windows, wasi-libc) — becomes `nox_user_`. The Nox-level name does not change: you keep writing `printf(...)` in source, and error messages, `reflect` and `noxc expand` show the original name. This is the same on both back ends and on every target (native, mobile, WebAssembly). ```python def getenv(x: int) -> int: # nox_user_getenv in the object file return x + 1 print(getenv(41)) # 42; the runtime's own getenv is unaffected ``` - The list covers the whole standard C/POSIX/libm namespace, not only the symbols linked today (`compiler/codegen_qbe/reserved_symbols.zig`); the runtime may link a new libc function tomorrow. - `extern def` declarations are NOT affected: `extern def sqrt(x: float) -> float from "m"` is meant to bind the real `sqrt`. - Nox built-ins (`abs`, `round`, `min`, ...) and keywords cannot be defined as user functions in the first place. - Embedding code (`nox_embed`) that calls a Nox function from C by name must use the `nox_user_` prefixed name for a function with a reserved name. Names that are not reserved are called by their plain name as before. - The symbols of class methods have the form `Class_method`; a reserved name can only appear if the class name collides with a libc prefix (`pthread`, `clock`, ...). There is no protection for that case (a documented limit). ## Verification - `tests/golden/codegen_cases/reserved_symbol_names.nox` defines and calls a user function for EVERY name on the list; some are also used through function values, `spawn` and `nox.thread.start`. It runs on both back ends and on all eight WebAssembly targets. When the list changes, run `scripts/gen_reserved_symbol_fixture.py`; CI checks that it is current with `--check`. - `scripts/check_reserved_symbols.py` verifies, by reading `nm -u` of the runtime objects (`zig-out/lib/noxrt*.o`), that every symbol they resolve from libc is on the list. When the runtime starts linking a new libc function, CI breaks here. --- # Frequently asked questions ## The language **Is Nox just Python?** The syntax is Python's, but Nox is statically typed and compiled to native code. Type annotations are mandatory, there is no dynamic attribute access, integers are 64-bit, and the semantics are those of a compiled language. [Differences from Python](https://noxlang.com/docs/language/python-differences/) is the full list. **Do I have to write types everywhere?** On variable declarations, parameters and return values, yes (`x: int = 5`). Later assignments, loop variables, lambda parameters and `self` need none, and the compiler infers many expression types. **How is memory managed? Is there a garbage collector?** No GC and no ownership annotations. The compiler frees values at their last use when it can prove that is safe, reference-counts the rest, and runs a cycle collector for reference cycles. You never free memory yourself ([Memory](https://noxlang.com/docs/language/memory/)). **Does Nox have exceptions?** Yes — `try`/`except`/`finally`/`raise` with class hierarchies. They are implemented as ordinary return values, not stack unwinding, so they cost nothing when not raised. **Is there `async`?** Yes: `async def`, `spawn`, `await`, `Task[T]` and `Channel[T]`. Tasks run in parallel on all cores under the default (LLVM) back end ([Concurrency](https://noxlang.com/docs/language/concurrency/)). **Why is `isinstance` missing / why no `*args`?** They are deliberately outside 2.0; adding them later will not break existing programs. Use protocols, base classes and explicit parameters. **Can I call C?** Yes: `extern def` ([Foreign functions](https://noxlang.com/docs/language/ffi/)). For distributable plugins use the [Nox Native Interface](https://noxlang.com/docs/apis/nni/) and [Plugin API](https://noxlang.com/docs/apis/plugin-api/). Python C extensions and WebAssembly modules can be loaded too ([Internals](https://noxlang.com/docs/internals/hpy-wasm/)). ## Tools and platforms **Which platforms are supported?** macOS arm64, Linux x86-64 and aarch64 are fully tested; Windows x86-64 runs the whole Debug test corpus and end-to-end smoke tests in CI and has an installer; WebAssembly is a supported compile target, and the compiler also runs in a browser ([Platforms](https://noxlang.com/docs/reference/platforms/), [Download](https://noxlang.com/download/)). **Do I need clang?** Not required. The compiler uses `clang`, or `zig cc`, or falls back to its bundled QBE back end ([Backends](https://noxlang.com/docs/tools/backends/)). **LLVM or QBE?** LLVM is the default and fastest, and is the parallel one. Use QBE for freestanding builds, cross-compilation, debug info (`-g`) and as a fallback. Both produce identical results. **How do I debug?** `print` shows any value structurally; `noxc build -g` gives line-level debugging ([Debugging](https://noxlang.com/docs/tools/debugging/)). **Where do packages come from?** Git repositories, listed in `nox.json` and pinned in `nox.lock`; the central index at helps you find them ([Packages](https://noxlang.com/docs/tools/packages/)). **Can I parse error text?** No. Diagnostics and library messages are English, but only the error *kind* and the exit status are stable ([Versioning](https://noxlang.com/docs/reference/versioning/)). `noxc --help` is Turkish when `LANG` starts with `tr`. ## Performance **How fast is it?** Across a mixed benchmark suite LLVM-compiled Nox runs at roughly 1.5× the time of C; numeric loops and dictionary-heavy code are within a small factor of C, and string/collection code is far faster than CPython. **Why is my multi-task program using only two threads?** Programs that merely `spawn` get a small default pool; use `serve_multicore`/`nox.thread.pool_run` or set `NOX_POOL_WORKERS` ([The scheduler](https://noxlang.com/docs/language/concurrency/#the-scheduler)). ## Safety **Is Nox memory safe?** Pure Nox code is. `extern def`, `lowlevel`, native plugins and dependencies containing them are outside that guarantee ([Security](https://noxlang.com/docs/reference/security/)). **Is it sandboxed?** No. Run untrusted code in an OS-level sandbox. ## Community **Where do I report bugs or ask questions?** and the project's discussion pages. **How do I contribute?** See [Contributing](https://noxlang.com/docs/internals/contributing/). --- # Glossary **ARC** — automatic reference counting. Layer 2 of the memory model: a value carries a count of its owners and is freed when the count reaches zero. **ASAP destructor** — "as soon as possible": cleanup code inserted at the point after a value's last use, with no reference count. Layer 1 of the memory model. **Backend** — the part of the compiler that turns typed IR into machine code: LLVM (default) or QBE. **Capability** — a named kind of authority (`filesystem`, `network`, `threads`, …) a standard-library module or a plugin needs; the freestanding profile permits only capability-free modules, and the Plugin API uses capabilities for consent. **Closure** — a function value together with the variables it captured from its enclosing function. **Cycle collector** — the component that frees groups of objects that reference each other, which reference counting alone cannot. **Dunder (special) method** — a method such as `__add__` or `__str__` whose name gives an operator or protocol meaning for a class. **`extern def`** — a declaration of a function implemented in native code, callable from Nox. **Fiber** — a lightweight stack-switching unit of execution; a task runs on one. **Fixed-width integer** — `u8`, `i32`, `u64`, … : integers of a given size that trap on overflow and never convert implicitly. **Freestanding** — a build with no operating system: a kernel-provided allocator and only capability-free modules. **Golden test** — a test whose expected output (or generated IR) is stored in a file and compared byte for byte. **Handle** — an opaque identifier that stands for a resource without exposing its address; NNI, the HPy bridge and the WASM bridge use handles at their boundaries. **HPy** — a handle-based API for Python C extensions; Nox implements a compatible layer. **LLVM / QBE** — the two compilation back ends. LLVM generates faster code and runs tasks in parallel; QBE is small and supports cross-compilation and debug info. **`lowlevel`** — a block that allocates from an arena and permits raw pointers; typing stays mandatory. **M:N scheduler** — many tasks (M) multiplexed over a pool of operating-system threads (N), with work stealing. **Monomorphisation** — compiling a separate specialised copy of generic code for each concrete type it is used with. **NAPI** — the Nox API: the source-level contract for libraries and frameworks. **NNI** — the Nox Native Interface: the stable C ABI for native extensions. **noxpkg** — the central package index and its web service. **Plugin API** — manifests, versioning and capability consent layered on NNI. **Prelude** — the names available without an import (`print`, `len`, `Exception`, …). **Protocol** — a structural interface: any class with the required methods satisfies it, with no declaration. **Task** — a unit of concurrent work started with `spawn`; `Task[T]` yields a `T` when awaited. **Trampoline** — a generated function at a foreign boundary that converts values and translates errors. **Trust boundary** — the line at which Nox's type and memory guarantees stop (`extern def`, `lowlevel`, plugins, dependencies with native code).