# Kairo Full Documentation > Kairo is a statically typed, compiled systems programming language with native bidirectional C++ interoperability. > This file contains the complete language documentation concatenated for LLM consumption. > Generated: 2026-11-15T08:15:52.299Z --- ======================================================================== SECTION: GETTING STARTED ======================================================================== ## Welcome to Kairo URL: https://www.kairolang.org/docs/welcome/ > [!WARNING] > The language reference describes Kairo as designed. The compiler (0.2.3) does not implement all of it yet, and the syntax and standard library may change before 1.0. See [Implementation Status](/docs/status/) for what is not compiled yet. # Kairo Kairo is an open-source, statically typed, compiled systems programming language with native bidirectional C++ interoperability. C++ projects can `#include` Kairo files directly. Kairo code calls C++ libraries without a binding layer. The compiler emits ABI-compatible object code that links with GCC, Clang, or MSVC output. ```kairo ffi "c++" import "vector" ffi "c" import "math.h" fn main() { var samples: cxx::std::vector samples.push_back(4.0) samples.push_back(9.0) samples.push_back(16.0) println(f"{samples.size()} samples") for x in samples { println(f"sqrt({x}) = {sqrt(x)}") } } ``` --- ## Why Kairo **Full control, less friction.** Kairo gives you manual memory management, raw pointer access, struct layout control, and zero-cost abstractions, with a compiler that tracks lifetimes, promotes smart pointers, and catches null dereferences at compile time. You opt into safety by default and opt out explicitly when you need to. **C++ interop that works both ways.** `ffi "c++"` imports C++ headers and makes every declaration available as a native Kairo symbol. The `kcc` driver lets C++ code `#include "file.k"` with no code generation step. Templates, concepts, classes, and smart pointers cross the boundary cleanly. **Zero-cost abstractions.** Interfaces are structural and carry no vtable. Generics are monomorphized. Panic handling compiles to tagged returns and branches: no unwinding tables, no runtime. Virtual dispatch exists only when you write `virtual`. --- ## At a Glance ```kairo ffi "c" import "math.h" struct Point { var x: f64; var y: f64; // semi-colons are optional! } extend Point { fn length(const self) -> f64 { return sqrt(self.x * self.x + self.y * self.y) // C's sqrt, called directly } fn op +(const self, const other: Point) -> Point { return Point { x: self.x + other.x, y: self.y + other.y } } } enum Shape { Circle { radius: f64 }, Rect { width: f64, height: f64 }, Empty, } interface HasArea { // structural: Shape satisfies it just by having area() fn area(const self) -> f64 } extend Shape { fn area(const self) -> f64 { match self { case .Circle(var radius) { return 3.14159 * radius * radius } case .Rect(var width, var height) { return width * height } case .Empty { return 0.0 } } } } fn describe(const item: T) -> string { return f"area {item.area()}" } enum Setting { Port, Host, Timeout } // closed: only these three values exist extend Setting { fn name(const self) -> string { match self { case .Port { return "port" } case .Host { return "host" } case .Timeout { return "timeout" } } } } fn lookup(key: Setting) -> i32? { match key { // every variant covered, so no default arm case .Port { return 8080 } case .Timeout { return 30 } case .Host { return null } } } struct Missing { var key: Setting fn op panic (const self) -> string { return f"{self.key.name()} is not set" } } fn require(key: Setting) panic -> i32 { var value? = lookup(key) if !value? { panic Missing { key: key } } return value // narrowed: value is a plain i32 here } fn main() { var a = Point { x: 3.0, y: 4.0 } var b = Point { x: 1.0, y: 2.0 } println(f"sum length: {(a + b).length()}") println(describe(Shape::Rect { width: 2.0, height: 3.0 })) try { println(f"port: {require(.Port)}") println(f"host: {require(.Host)}") } catch e: Missing { println(f"missing: {e.key.name()}") } } ``` --- ## Status Kairo is in active development. Version 0.2.3 is the third self-hosted release: the compiler is written in Kairo, compiles itself, and cross-compiles to 48 targets, building each target's sysroot the first time you use it. Prebuilt packages exist for Linux, macOS, Windows, FreeBSD and NetBSD (see [Installation](/docs/install/)). See [Implementation Status](/docs/status/) for the gaps. The original C++ implementation, Stage 0, which transpiled Kairo to C++, is retired. Language syntax and standard library APIs may change before 1.0. The documentation on this site reflects the current language design. --- ## Next Steps - [Philosophy](/docs/philosophy/): understand the design principles - [Primitives](/docs/language/primitives/): start with the type system - [Classes](/docs/language/classes/): objects, inheritance, virtual dispatch - [C/C++ Interop](/docs/language/c-cpp/): calling C++ from Kairo and back - [Example: HTTP Server](/docs/examples/http-server/): a complete project walkthrough --- ## Philosophy URL: https://www.kairolang.org/docs/philosophy/ # Philosophy Kairo is a systems programming language built on one idea: you should have full control over your program without having to fight the language to get it. ## The problem Systems languages tend to fail in one of two ways. Some give you unlimited freedom and no guardrails. You manage memory, track lifetimes, and audit every pointer yourself, and you hope that discipline holds across a million-line codebase that a rotating team maintains for a decade. When it doesn't hold, you get CVEs. Others fix this by limiting what you can express. The compiler keeps rejecting your program until you restructure it to fit its model. That does produce safe code, but you pay in cognitive overhead. Simple patterns turn into puzzles, and prototyping starts to feel like negotiating with a bureaucracy. Kairo tries to avoid both. The language should help you write correct code and leave the structure of that code up to you. ## Design principles There are four principles below, and they share one trade-off. Kairo moves accidental complexity out of your head and into the compiler, while keeping enough explicit information in the source that a person can still understand the code by reading it locally. Lifetimes, ownership, null states, and panic paths are bookkeeping. They have nothing to do with the problem you're solving, so the compiler should carry them. It shouldn't carry the meaning of the code, though. If you have to ask the compiler, or read five other files, to know what a line does, the complexity has only been hidden. Inference handles the tedious parts, and anything that changes how you reason about a piece of code stays written down where you're reading it. ### Control should exist Kairo is a systems language. You can manage memory directly, control struct layout and alignment, use raw pointers, work across ABI boundaries, call C and C++ at zero cost, and write allocators, runtimes, compilers, or kernels. None of that is hidden from you. Traditional systems languages also assume you want to do all of this by hand. Kairo doesn't. The compiler provides: - Ownership tracking and automatic smart pointer promotion - Null safety with compile-time null checks on safe pointers - Panic propagation analysis with exhaustive catch verification - Structural interface validation without explicit registration - Full-program lifetime analysis with no annotations required You can override or opt out of any of these when you need to. ### Safety should assist, not dominate Kairo's safety features mostly make problems visible. They don't stop you from writing the code in the first place. The compiler explains mistakes clearly, keeps what you meant intact, and stays out of the way while you experiment. It's lenient during development so you can move fast, and stricter when you build for release. The intended workflow is to prototype loosely, refine on purpose, and harden the code before it ships. Each escape hatch is spelled out in the source. `unsafe` blocks suspend Tether tracking. `unsafe *T` pointers skip null checks and bounds analysis. `unsafe` function overloads relax semantic invariants. Because every dangerous operation is marked, a reviewer can find all of them with grep. ### Code should explain itself You shouldn't need an IDE, knowledge of hidden compiler behavior, or a tour through dense metaprogramming to understand what code does. This matters more the more work the compiler does for you, since a reader can only go by what's on the page. - `self` is always visible in method signatures - Inheritance uses the `derives` keyword, with no implicit resolution - Pointer types look different from each other (`*T` vs `unsafe *T` vs `*const T`) - All conversions use a single `as` keyword - Interfaces are structural: if a type has the methods, it satisfies the interface - Operator overloads are declared with `fn op` syntax that mirrors the operator ```kairo class Sensor { var reading: f64 mutable var access_count: i32 fn value(const self) -> f64 { self.access_count += 1 return self.reading } fn calibrate(self, offset: f64) { self.reading += offset } } ``` Open this in a plain text editor and you can still follow it. You can see which methods mutate, which fields stay mutable through `const`, and where the visibility boundaries are. Kairo treats readability as a requirement for systems code, including code written by experts. ### Adoption should be incremental Large codebases take decades to build, whole ecosystems are written in C and C++, and most teams can't afford to rewrite everything. Kairo fits into an existing system one module at a time. You import C headers directly with `ffi "c"` and C++ headers with `ffi "c++"`. Kairo emits ABI-compatible object code (Itanium on Unix and MinGW, MSVC on `*-windows-msvc`), so its `.o` files link against GCC, Clang, or MSVC output without shims. Object layout, vtable structure, name mangling, and calling conventions all follow the platform standards. ```kairo ffi "c++" import "engine.hh" as engine fn main() { var ctx = engine::create_context() engine::run(ctx) } ``` A team can move over one file at a time, check performance as it goes, and keep its existing build system the whole way through. ## Zero-cost abstractions High-level features compile to predictable low-level code: - Interfaces are structural and have no vtable or runtime dispatch cost. A type satisfies an interface by having the right methods, with no registration or indirection. - Generics are monomorphized at compile time, so there's no boxing, type erasure, or runtime cost. - Panic handling compiles to tagged return values and branches. There are no unwinding tables, no runtime exception handler, and no stack unwinding. - Tether runs at compile time. There's no garbage collector, and reference counting only appears where the analysis decides ownership is actually shared. - Virtual dispatch exists only when you write `virtual`. Non-polymorphic classes have no vtable pointer. If you don't use a feature, it costs you nothing. ## Familiar, but cleaner Kairo should feel familiar if you've written systems code before. Most concepts carry over from C++, minus the complexity that doesn't earn its keep: | C++ complexity | Kairo simplification | |---|---| | `static_cast` / `dynamic_cast` / `reinterpret_cast` / `const_cast` | Single `as` keyword | | Implicit `this` | Explicit `self` parameter | | `public:` / `private:` / `protected:` sections | Per-declaration `pub` / `priv` / `prot` | | `const int*` vs `int* const` ambiguity | Left-to-right `const` binding rule | | Header/source split | Single `.k` files | | `friend` declarations | Module-level visibility (`priv`, `prot`) | | `#define` preprocessor | Scoped token macros and AST attributes | | Implicit special member generation/suppression | Always generates unless explicitly deleted | | Exception unwinding tables | Zero-cost panic returns | Kairo isn't trying to be novel. It's trying to remove the friction C++ picked up over decades of evolution while keeping the power that makes C++ worth using. ## Who Kairo is for Kairo is meant for projects that keep growing, such as: - Compilers and language toolchains - Game engines and real-time systems - Distributed systems and infrastructure - Operating systems and embedded firmware - Long-lived enterprise codebases It's for engineers who want the performance and control of systems programming without the maintenance burden that usually comes with it. --- ## Installation URL: https://www.kairolang.org/docs/install/ # Installation Kairo 0.2.3 ships as a **prebuilt package** for 14 host platforms: Linux (static musl, runs on any distribution), Windows, macOS and the BSDs. Pick your archive in the table below, or let the install script choose it. A host without an archive can [build from source](#building-from-source). The compiler, `kairo`, is written in Kairo and compiles itself. The package holds everything it needs: `kairo`, `kcc`, `kld`, `kfmt`, `ksys`, `kals` (the language server), the `builtin`, `std` and `rt` libraries, `compiler-rt`, the host's own sysroots and the sources `ksys` builds every other target's sysroot from. Clang and LLD run inside `kairo`, `kcc` and `kld`, so no separate `clang` or `lld` binaries ship. You do not need a system C or C++ toolchain. --- ## Prebuilt Package ### Quick install Linux, macOS, FreeBSD and NetBSD (any shell, fish included): ```bash curl -fsSL https://www.kairolang.org/install.sh | sh ``` Windows (PowerShell 5.1 or 7): ```powershell irm https://www.kairolang.org/install.ps1 | iex ``` Both are the same script. It detects your OS and CPU, downloads the matching archive and `SHA256SUMS`, verifies the checksum before unpacking, and never needs root or administrator rights. On Linux, macOS and the BSDs it unpacks to `~/.local/share/kairo/` and links the tools into `~/.local/bin`. On Windows it unpacks to `%LOCALAPPDATA%\Kairo\` and adds that `bin` directory to your user `Path`. It honours `KAIRO_VERSION`, `KAIRO_PREFIX`, `KAIRO_BASE_URL` and `KAIRO_TRIPLE`; set `KAIRO_TRIPLE` to pick a different archive from the table (for example `armv7-windows-gnu`). ### Manual download Download the archive and `SHA256SUMS` from the [release page](https://github.com/kairolang/kairo/releases/tag/v0.2.3), verify it, extract it, and add `bin` to your `PATH`. | Platform | Architecture | File | |---|---|---| | Linux (static, musl) | x86_64 | `kairo-0.2.3-x86_64-linux-musl.tar.xz` | | Linux (static, musl) | aarch64 | `kairo-0.2.3-aarch64-linux-musl.tar.xz` | | Linux (static, musl) | armv7 | `kairo-0.2.3-armv7-linux-musl.tar.xz` | | Linux (static, musl) | i686 | `kairo-0.2.3-i686-linux-musl.tar.xz` | | Linux (static, musl) | riscv64 | `kairo-0.2.3-riscv64-linux-musl.tar.xz` | | Windows (MinGW) | x86_64 | `kairo-0.2.3-x86_64-windows-gnu.zip` | | Windows (MinGW) | aarch64 | `kairo-0.2.3-aarch64-windows-gnu.zip` | | Windows (MinGW) | armv7 | `kairo-0.2.3-armv7-windows-gnu.zip` | | Windows (MinGW) | i686 | `kairo-0.2.3-i686-windows-gnu.zip` | | macOS 11+ | arm64 | `kairo-0.2.3-arm64-apple-macosx11.0.zip` | | macOS 10.15+ | x86_64 | `kairo-0.2.3-x86_64-apple-macosx10.15.zip` | | FreeBSD | x86_64 | `kairo-0.2.3-x86_64-unknown-freebsd.tar.xz` | | FreeBSD | aarch64 | `kairo-0.2.3-aarch64-unknown-freebsd.tar.xz` | | NetBSD | x86_64 | `kairo-0.2.3-x86_64-unknown-netbsd.tar.xz` | ```bash sha256sum -c --ignore-missing SHA256SUMS tar -xJf kairo-0.2.3-x86_64-linux-musl.tar.xz ``` The archive contains: - `bin/`: `kairo`, `kcc`, `kld`, `kfmt`, `ksys`, `kals`, `llvm-symbolizer`, `llvm-ar`, `llvm-ranlib`, `llvm-lib` - `lib/`: the clang resource directory, `builtin`, `std` and `rt` - `sysroot/`: the sysroots of the archive's own host (below); Linux archives hold the musl and glibc 2.31 roots of their architecture, Windows archives their `-windows-gnu` root, BSD and macOS archives none - `share/kairo/sysroot/`: the input tree `ksys` builds every other target's sysroot from (libc sources and headers, glibc symbol lists, mingw-w64 and wasi-libc sources, BSD base trees, licenses) - `scripts/`: `msvc-sysroot.sh` / `msvc-sysroot.ps1` (they fetch the CRT and Windows SDK with xwin if you accept Microsoft's license) and `darwin-sysroot.sh`, which build the macOS and MSVC sysroots from your own SDK ([below](#macos-and-msvc-targets)) - `share/kairo/runtimes/`: the LLVM runtimes source (libc++, compiler-rt builtins) that `ksys` and those scripts compile - `LICENSE`, `NOTICE`, `LICENSES/`, `THIRD-PARTY-NOTICES` The compiler is built on an LLVM 22 toolchain from Kairo's [patched fork](https://github.com/kairolang/llvm-project), linked in-process. > [!NOTE] > The test suite runs on x86_64 Linux only. Cross-compiled output for other targets has not been through the suite on those platforms. ### Sysroots A sysroot is the C library, headers and runtime libraries of a target. The archive ships the sysroots of its own host and builds every other one on demand, so it is also the cross-compiler for the [supported targets](/docs/toolchain/ksys/#supported-targets) with no extra download: - Linux musl: x86_64, x32, i686, aarch64, aarch64_be, armv6, armv7, thumbv7, riscv64, riscv32, powerpc, powerpc64, powerpc64le, s390x, mips, mipsel, mips64, mips64el, loongarch64; Linux glibc (2.17 to 2.42, 16 architectures): x86_64, i686, aarch64, aarch64_be, armv7, riscv32, riscv64, powerpc, powerpc64(le), s390x, mips, mipsel, mips64, mips64el, loongarch64 - Windows (MinGW): x86_64, aarch64, i686, armv7 (`*-windows-gnu`) - FreeBSD: x86_64, aarch64; NetBSD: x86_64 - WebAssembly: wasm32-wasi Pass `--target=` to pick one. The first time you name a target whose sysroot is not in the archive, `kairo` and `kcc` build it with [ksys](/docs/toolchain/ksys/) from `share/kairo/sysroot` and cache it (in `~/.cache/kairo/sysroot`, or `$KAIRO_SYSROOT_CACHE`); it takes 5 to 30 seconds and needs no network. Later builds find it in the cache. `--no-sysroot-build` turns the build into an error, `--sysroot=` names a sysroot you have, and `--freestanding` compiles without system headers and libraries. A target whose sysroot cannot be built, and for which there is no input tree, warns (`P008W`) and names the flag to pass. The target name can carry a glibc version: `x86_64-linux-gnu-glibc2.28` or `x86_64-linux-gnu.2.28`, any version from 2.17 to 2.42. Without one, Linux programs build against glibc 2.31, so they run on any distribution with glibc 2.31 or newer. Apple's SDK and Microsoft's MSVC / Windows SDK are never shipped or generated, on any host. To target macOS or MSVC-ABI Windows, build that sysroot once with the scripts in `scripts/` (next section): they read the SDK you have installed (or, for MSVC, fetch it with xwin after you accept Microsoft's license) and put the result under `sysroot/`, where Kairo finds it with no flags. Without one, `--target` for those triples stops with an error naming the script. See [ksys](/docs/toolchain/ksys/) and [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/). ### macOS and MSVC targets Apple's and Microsoft's licenses forbid redistributing their SDKs, so the package cannot include `*-apple-macosx` or `*-windows-msvc` sysroots, and `ksys` never builds them from the shipped tree. Instead it ships scripts in `scripts/` that build them from your own copy. They compile libc++ and compiler-rt from the LLVM source in `share/kairo/runtimes` using the package's own `kcc` and `kld`, and write the root to `sysroot/`, where `kairo --target` finds it with no flags. You need `cmake`, `ninja` and `python3`. For MSVC on Linux, macOS or WSL, `msvc-sysroot` gets the CRT and Windows SDK for you with [xwin](https://github.com/Jake-Shadle/xwin): ```bash /scripts/msvc-sysroot.sh x86_64 ``` It prints Microsoft's license and asks you to accept it; `--accept-license` or `KAIRO_ACCEPT_MSVC_LICENSE=1` accepts it up front (a non-interactive run with neither stops). It uses `xwin` from `$XWIN_BIN`, else `PATH`, else downloads a pinned release (checked against its sha256) into `share/kairo/tools/`, and keeps the download in `share/kairo/msvc-cache/` for later runs. To use a splat you made yourself: ```bash xwin --accept-license --arch x86_64,aarch64,x86 splat --output ~/xwin XWIN=~/xwin /scripts/msvc-sysroot.sh x86_64 ``` On Windows, the same script uses the installed Visual Studio (the "Desktop development with C++" workload) and Windows SDK: ```powershell powershell -ExecutionPolicy Bypass -File \scripts\msvc-sysroot.ps1 x86_64 ``` For macOS, on a Mac with the Command Line Tools installed (`xcode-select --install`): ```bash /scripts/darwin-sysroot.sh arm64 ``` Each script accepts several architectures at once (`x86_64 aarch64 i686`, or `arm64 x86_64 arm64e`). Keep the generated roots on your machine: they contain Apple's or Microsoft's files. You often do not need to run them. On a Mac, the first `kairo` or `kcc` build for macOS (the native default, or `--target arm64-apple-macosx` / `x86_64-apple-macosx`) assembles the root itself from the SDK it finds (`SDKROOT`, the selected Xcode or the Command Line Tools) and the prebuilt libc++ in `share/kairo/sdk-overlays/`, in a few seconds, into the `ksys` cache. On Windows, the first `--target x86_64-windows-msvc` build does the same from an xwin splat (`XWIN`, or the one `msvc-sysroot` cached) or, with Visual Studio's C++ tools installed, by running `msvc-sysroot.ps1` for you. With neither, it stops with an error giving the exact command: the CRT and Windows SDK download asks for Microsoft's license, so Kairo never starts it on its own. The scripts remain the way to build `arm64e` (no prebuilt overlay) or to rebuild libc++ from source. A macOS target without a version (`x86_64-apple-macosx`) compiles for the oldest macOS the roots support, 11.0 on arm64 and 10.15 on x86_64; name one (`arm64-apple-macosx13.0`) to raise it. ### System requirements - **Linux x86_64:** any distribution. The compiler is statically linked against musl and needs no system libc, libc++ or libunwind. - **Windows:** the native `*-windows-gnu` archives need no extra runtime; they are MinGW builds. ### Add to PATH If you used the install script, add `~/.local/bin` to your `PATH` if it is not already there. For a manual extract: ```bash export PATH="$PATH:/path/to/kairo-0.2.3-x86_64-linux-musl/bin" ``` Add that line to your `~/.bashrc` or `~/.zshrc` to make it permanent. ### Validate Create a file called `test.k`: ```kairo fn main() -> i32 { var x = 5 var y = 10 io::println(f"Hello, world! Sum of {x} and {y} is {x + y}") return 0 } ``` Compile and run it: ```bash kairo test.k -o test ./test ``` ``` Hello, world! Sum of 5 and 10 is 15 ``` Without `-o`, the executable is written to `a.out`. The executable targets the machine you compile on. On Linux that is the host's glibc triple (`x86_64-linux-gnu`), which links dynamically against the system libc. For a static executable, pass `--target=x86_64-linux-musl`. To build for another platform, pass its triple with `--target`. --- ## Building from Source Build from source if you need unreleased changes or are developing Kairo itself. The compiler is written in Kairo, so building it needs a seed: a prebuilt Kairo release (0.2.0 or newer) from above. Building without a seed is not possible. ### Requirements - A prebuilt Kairo release (0.2.0+) as the seed, with its `bin/` on your `PATH` (or named with `--kairo`) - **git** and **Python 3** - **CMake** and **Ninja**, used once to build the patched LLVM - About 30 GB of free disk and plenty of RAM for the first build; the patched LLVM is built once and reused You do not need a system Clang or xmake. The earlier C++ bootstrap compiler, Stage 0, is retired. ### Build ```bash git clone https://github.com/kairolang/kairo/ cd kairo git submodule update --init --recursive # pulls the patched LLVM (large download) python3 build.py --release --kairo /path/to/kairo-0.2.3-x86_64-linux-musl/bin/kairo kairo kcc kld kfmt ksys kals ``` The first build also builds the patched LLVM (once; later builds reuse it). `--kairo` names the bootstrap compiler; it can be left out when that `kairo` is on your `PATH`, and later builds use the last one they produced. `build.py` builds the compiler with the bootstrap compiler, rebuilds it with the result (so the final compiler is built by itself), and stages a self-contained package in `build//release/`, where `` is your host's static musl triple (`x86_64-linux-musl` on x86-64 Linux): `bin/` holds `kairo` and `kcc` beside `kld`, `kfmt`, `ksys`, `kals`, `llvm-symbolizer` and the `llvm-ar` family (there are no `clang` or `clang++` binaries: `kairo` and `kcc` run clang in-process and `kld` runs lld in-process), and `lib/` holds the clang resource directory, the `builtin`, `std` and `rt` libraries and every shared library the binaries need. The compiler finds all of it from its own location, so it runs with no flags: ```bash build/x86_64-linux-musl/release/bin/kairo main.k -o main ``` `--debug` builds an unoptimized compiler that is quicker to rebuild. `--resource-dir`, `--builtins-dir`, `--std-dir` and `--sysroot` override what the compiler finds. If one of them cannot be found the compiler warns, naming the path it searched and the flag to pass. Not having a sysroot is a warning too, unless you pass `--freestanding`. To run the compiler's test suite: `build/llvm/bin/llvm-lit Tests -s` (it tests the most recently built compiler; set `KAIRO_BIN` to pick one). `Scripts/package_release.py` turns a built tree into a release archive. --- ## VSCode Extension VSCode is currently the only editor with LSP support and `.k` syntax highlighting. The language server ships as part of the compiler, so there is nothing extra to run: the extension only needs to locate `kairo`. ### Install Pick whichever is easiest: - **Marketplace:** install from the [Kairo extension page](https://marketplace.visualstudio.com/items?itemName=KSF.kairo). - **Prebuilt VSIX:** download the latest `.vsix` from [kairo-lsp](https://github.com/kairolang/kairo-lsp/) (e.g. `kairo-0.5.5.vsix`), then in VSCode: **Extensions** -> **...** -> **Install from VSIX...** - **Build from source:** ```bash git clone https://github.com/kairolang/kairo-lsp/ cd kairo-lsp npm install npm run build --omit=dev npx @vscode/vsce package ``` This produces a `.vsix` you install the same way. ### Configure If `kairo` is on your `PATH`, the extension finds it automatically, no configuration needed. Otherwise set `kairo.path` in your VSCode `settings.json` to the compiler's location. If it cannot find the compiler, you get a single "path not set" warning. ### Debugging - **Run Kairo File** - runs and attaches the debugger - **Run Kairo File with Args** - prompts for comma-separated args (e.g. `arg1,arg2,arg3`) Both work with `fn main()` or `fn Test()` entry points. > [!WARNING] > With `fn Test()`, VSCode redirects to a temporary file during debugging. Breakpoints work, but > **edits are not saved back to your original file**. Re-running the debugger resets everything. Use `fn main()` for active development. --- ## Troubleshooting **`warning [P008W]: no sysroot found for target ...`.** The target has no sysroot in the archive and there is no `share/kairo/sysroot` to build one from (or the `sysroot/` directory is not next to `bin/`). Pass `--sysroot=`; see [Sysroots](#sysroots). **`error [P009E]` with `--target`.** `ksys` refused to build the sysroot: the target is not one it knows (`ksys probe ` says why), the input tree does not match its hashes, or a tool is missing. Nothing was built. `kairo --explain P009E` lists the causes; a build that ran and failed is `P010E` and names a log. See [ksys](/docs/toolchain/ksys/#diagnostics). **`error [P008E]: no sysroot found for target ...` (a `*-apple-macosx` or `*-windows-msvc` target).** These sysroots are never bundled; build one with the scripts in `scripts/`, see [macOS and MSVC targets](#macos-and-msvc-targets). **The install script says the archive "is not listed in SHA256SUMS".** Your OS/CPU has no prebuilt archive (the error lists the ones that exist). Build from source, see [Building from Source](#building-from-source). --- ## Compiler Compliance URL: https://www.kairolang.org/docs/compilence/ # Kairo Compiler Standards & Compliance This document covers every standard, ABI, and specification Kairo targets, what compliance means in practice, and where Kairo intentionally deviates and why. It is written for engineers who need to know exactly what guarantees the compiler makes and what it doesn't. --- ## Floating-Point: IEEE 754-2019 Kairo targets **IEEE 754-2019** (the 2019 revision of IEEE 754-2008) for all binary floating-point types: `f16`, `f32`, `f64`, `f128`. What this means concretely: - All four basic arithmetic operations (`+`, `-`, `*`, `/`), `sqrt`, and `fma` produce correctly rounded results in round-to-nearest-even mode (the IEEE default). The result is the representable value closest to the infinitely precise result, with ties going to even. - Every operation is rounded on its own. The compiler never fuses a multiply and an add into one FMA by default (FP contraction is `off`), so `a * b + c` rounds twice, exactly as written. Opt in with `--fp-contract=on` (fuse within an expression) or `--fp-contract=fast`; results can then differ in the last bit from the unfused form. Call `fma` explicitly when you want one rounding. - Math functions never set `errno`. A Kairo call to `sqrt`, `pow`, and the rest reports a domain or range error through its result (`NaN`, `inf`) only, so the compiler is free to use the hardware instruction. - Overflow produces `inf`, underflow produces `0.0`. Operations that produce `NaN` (e.g., `0.0 / 0.0`, `sqrt(-1.0)`) propagate `NaN` per IEEE 754; no crash, no trap. Test for `NaN` with `x != x` (`x == f64::NAN` is always `false`); the infinities are [`f64::INFINITY` and `f64::NEG_INFINITY`](/docs/language/primitives/#limits). - NaN payload bits are not guaranteed to be preserved across arithmetic operations and are not guaranteed to be portable across architectures. Inspecting NaN bit patterns is explicitly unsupported behavior. If you need NaN payloads, use `f32::from_bits` / `f64::from_bits` and document why. - The 2019 standard deprecated the non-associative `minNum`/`maxNum` operations from 2008 and replaced them with `minimum`/`maximum` which have well-defined NaN handling. Kairo's `min`/`max` builtins follow the 2019 semantics. - Subnormal (denormal) numbers are handled per IEEE spec by default. Flush-to-zero mode is not enabled unless you explicitly opt in with `--fp-model=fast` or the `@float_mode(fast)` block annotation. - These rules cover Kairo code only. C and C++ keep C++'s floating-point rules: C/C++ files compiled alongside Kairo, and the code in headers imported with `ffi "c"` / `ffi "c++"`, even though a header is compiled in the same unit as the Kairo that imports it. On that code contraction is `on`, and `errno` follows the target's C++ default (set on glibc Linux, not on musl or Apple platforms), as with `clang++`. An explicit `--fp-contract`, `--fp-model` or `-ffast-math` applies to both alike. **What Kairo does not guarantee:** - Reproducibility of floating-point results across different optimization levels, different target architectures, or different LLVM versions. If you need bitwise-reproducible results, keep the default `--fp-contract=off`, add `--fp-model=strict`, and target a specific CPU with `--mcpu`. - Strict exception observability by default. FP exceptions (divide-by-zero, overflow, underflow, inexact, invalid) are not observable through `fenv.h` equivalents unless you compile with `--fp-model=strict`. The default (`precise`) treats exceptions as ignorable, which is what lets the optimizer e.g. hoist FP computations out of loops. **FP mode quick reference:** | Mode | What it does | When to use | |---|---|---| | `precise` (default) | IEEE arithmetic, no unsafe rewrites, no FMA contraction, no `errno` | General use | | `strict` | IEEE + observable exceptions + no FMA | Scientific code, reproducibility audits | | `fast` | Everything unsafe on (`-ffast-math`) | SIMD kernels, numerical code you've already validated | | `@float_mode(fast)` | Block-scoped fast-math | Hot inner loops only | --- ## Text Encoding: Unicode 15.1 / UTF-8 ### Source Files Kairo source files are **UTF-8** only. No BOM. No other encoding is accepted. The lexer validates UTF-8 byte sequences and rejects invalid sequences as hard errors with a diagnostic pointing at the exact byte offset and offending bytes. A BOM at the start of a `.k` file is an error. ### String Internal Representation Kairo's `string` is a four-word value (32 bytes on 64-bit): `{data, len, cp_len, cap}`, a UTF-8 byte sequence with the byte count and codepoint count carried alongside. There is no small-string optimization. A literal is a borrowed view of static storage (`cap == 0`) and allocates nothing; an owned string has `cap` bytes of heap behind `data`. Both keep a NUL byte after `len`, so a C string view is O(1). - **Codepoint indexing:** `s[i]` returns a `char` (a `u32` Unicode scalar value) at codepoint position `i`. For string literals, the compiler pre-populates a breadcrumb cache at codegen time mapping codepoint positions to UTF-8 byte offsets, making indexing O(1) with zero runtime cost. For strings constructed at runtime from a raw `*u8` or `*u32` pointer, no cache is available and indexing is O(n); use sequential iteration or copy into a `string` first if you need repeated random access. - **Byte indexing:** `s.bytes[i]` returns a raw `u8` at byte offset `i`. This is O(1) always but returns raw UTF-8 bytes, not characters. - **Iteration:** `for ch in s` yields `char` values (decoded codepoints) sequentially. See [Primitives](/docs/language/primitives/#strings) for the full string API. ### Identifiers Kairo identifiers may contain any Unicode scalar value that has the `ID_Start` or `ID_Continue` property (Unicode UAX #31), **plus** emoji and other non-letter code points that UAX #31 excludes. This is an intentional extension beyond the standard identifier grammar. Concretely: - Letters and digits from any script: Latin, Arabic, Chinese, Cyrillic, Devanagari, etc. are all valid. - Emoji: valid. - Combining marks: valid as continuation characters. - Whitespace, control characters: never valid in identifiers. Two identifiers are equal if and only if their sequences of scalar values are equal. Kairo does not perform Unicode normalization on identifiers. This matches the behavior of most modern languages. If you want normalization, normalize your source before feeding it to the compiler. ### String Indexing Indexing a `string` by integer (`s[i]`) returns the codepoint at position `i`, not a grapheme cluster. For most text this is the same thing, but for combining sequences and emoji with modifiers it is not: - `"hello"`: `s[1]` returns `'e'`. Five codepoints, five elements. - A string with a combining sequence (e.g., `e` + combining acute): the base character and the combining mark are separate codepoints and separate indices. - Emoji with ZWJ sequences (e.g., family emoji): multiple codepoints, multiple elements. `length()` returns the codepoint count, not the visual glyph count. Grapheme cluster iteration is not currently in the standard library. If you need to operate on user-visible characters, use a third-party ICU binding. ### Conversions and C/C++ Interop `string` provides explicit conversion methods. When calling C++ functions with Kairo primitives, conversions to C++ string types are implicit: | Conversion | Output | Use case | |---|---|---| | `as cxx::std::string` | UTF-8 `std::string` | Natural fit; Kairo strings are UTF-8 internally | | `as cxx::std::u16string` | UTF-16 `std::u16string` | Windows WinAPI (`LPWSTR`), Java interop | | `as cxx::std::u32string` | UTF-32 `std::u32string` | APIs expecting `char32_t` sequences | | C `const char*` | Null-terminated UTF-8 `u8` pointer | Implicit conversion; no `unsafe` block required | See [C/C++ Interop](/docs/language/c-cpp/) for the full FFI model. ### What Kairo Does Not Do - **Locale-sensitive operations**: `string` comparison is binary (codepoint by codepoint). Locale-sensitive collation is not in the standard library. Use a third-party ICU binding if you need locale-aware sorting. - **Encoding detection**: Kairo does not detect or guess source file encoding. UTF-8, no BOM. - **Signed byte interpretation**: The internal backing type is `u8`. There is no `i8` / C `char` ambiguity in Kairo's string representation. --- ## ABI: Platform psABIs Kairo follows the platform processor ABI for the target triple. It does not define its own ABI and does not need to because Kairo compiles to native object files via Clang's backend. The relevant documents per platform: ### x86-64 Linux / BSD / macOS - **System V AMD64 psABI v1.0** - calling convention, register usage, stack alignment (16-byte at call site), parameter passing, return value encoding, varargs layout, TLS model, ELF object format. - Kairo respects the red zone (128 bytes below RSP) by default. Kernel code should compile with `--kernel-mode`. - SIMD types (`f32x4`, `f32x8`, etc.) follow the psABI's XMM/YMM/ZMM classification rules. Vectors passed on the stack are 16-byte aligned minimum. ### AArch64 Linux - **ARM64 ELF psABI (AAPCS64)** - 8 general-purpose argument registers (x0-x7) and 8 floating-point/SIMD argument registers (v0-v7), caller-saved x0-x17, callee-saved x19-x28. - Pointer authentication is not enabled by default. Use `--mbranch-protection` to opt in. ### macOS (Mach-O) - **Apple ARM64 ABI** on Apple Silicon - extends AAPCS64. Stack pointer must be 16-byte aligned at all call sites. Clang enforces this. - **System V AMD64** on Intel Mac. - `--macos-version-min` is required if you target macOS older than the build machine SDK. Kairo does not guess a deployment target. ### Windows (PE/COFF) - **Microsoft x64 calling convention** - 4 register parameters (rcx, rdx, r8, r9 for integers; xmm0-xmm3 for floats), shadow space requirement (32 bytes), caller cleans stack. - The C++ ABI is decided by the target triple. `*-windows-gnu` (MinGW-w64, the default Windows target) uses the Itanium C++ ABI and links with GCC- and Clang-built MinGW code. `*-windows-msvc` uses the Microsoft C++ ABI and links with MSVC- and clang-cl-built code. There is no separate flag. ### WASM / WASI - **WebAssembly MVP + proposals** per the flags you enable. WASI preview1 or preview2 depending on `--wasi-version`. The WASM calling convention is defined by the Wasm binary format spec; there is no psABI in the traditional sense. --- ## Debug Info: DWARF 5 When compiled with `-g` / `--debug-info`, Kairo emits **DWARF 5** by default. DWARF 4 is available via `--dwarf-version=4` for targets that require it (e.g., older GDB versions, some embedded targets). What Kairo emits: - `DW_AT_language` is set to `DW_LANG_C_plus_plus_14` so existing C++ debuggers and tooling work unchanged. A proper `DW_LANG_Kairo` language tag will be registered with the DWARF committee once the language spec stabilizes. - Source file paths in DWARF use the paths as given to the compiler, resolved relative to `--working-dir` if set. Use `--remap-path-prefix` or `--debug-prefix-map` to strip build-machine-specific paths for reproducible builds. - Line tables include column information (DWARF 5 `DW_LNS_set_column`), which allows debuggers to point at the specific expression within a line. - Split DWARF (`--split-dwarf`) produces `.dwo` files. This reduces link-time memory usage on large projects. The `.dwo` files must be accessible at debug time (either in the same directory or via `debuginfod`). - Type units are emitted for types defined in headers, reducing debug info size in multi-TU builds. **Comments and trivia in debug info:** The Kairo AST preserves comments and whitespace trivia. These are currently not emitted into DWARF (there's no standard DWARF attribute for them). They are preserved in the AST for tooling use (formatters, LSP, etc.) but stripped before codegen. --- ## Object Format: ELF / Mach-O / PE-COFF / WASM Kairo emits the native object format for the target: | Platform | Format | Notes | |---|---|---| | Linux, BSD, Android | ELF64 (ELF32 with `--m32`) | | | macOS, iOS | Mach-O 64-bit | | | Windows | PE/COFF | | | WASM | WebAssembly binary | | | Bare metal | ELF (usually) | depends on target ABI | | All platforms | `.klib` | Platform-agnostic library distribution format | Kairo does not emit its own intermediate object format for native targets. The output of a native compilation is a standard object file that any conformant linker for that platform can process. ### klib: Kairo Library Format `.klib` is Kairo's platform-agnostic binary format for distributing libraries. It contains no object code. A `.klib` file contains: - Full serialized AST for all exported modules - Macro definitions - Type information and symbol table - `.amt` module summary (ownership and lifetime metadata consumed by sema passes) `.klib` files are imported identically to source files: `import my_lib` resolves whether `my_lib` is a `.k` source tree or a `.klib` package. ELF/Mach-O/PE output is still available for consumers that link against Kairo code from other languages; `.klib` is the distribution format for the Kairo package ecosystem and is what gets uploaded to package repositories. Because `.klib` carries the AST rather than object code, monomorphization and codegen happen on the consumer's machine for their target platform. This makes `.klib` files self-contained and inherently cross-platform. --- ## C++ Interop ABI When Kairo calls into C++ via `ffi "c++" import`, the C++ code is compiled by Clang using the same backend invocation. Headers are compiled by the pinned Clang at the standard `--cxx-std` selects: `c++20`, `c++23` (default), or `c++26`, or the `gnu++` spelling of each. C++ sources compiled alongside Kairo (`.cc`, `.cpp`, `.mm`) get the same standard. What that covers, and what it does not yet (named modules, for one), is listed in the [coverage matrix](/docs/language/c-cpp/#coverage-matrix). The ABI boundary between Kairo-emitted code and C++-emitted code is: - **Itanium C++ ABI** on every triple except `*-windows-msvc`, including `*-windows-gnu`. - **MSVC C++ ABI** on `*-windows-msvc` triples. - Name mangling follows whichever C++ ABI the triple selects. Kairo functions exported across the FFI boundary use C++ name mangling to support overloading and seamless interop with Clang-compiled C++ code. Explicit `ffi "C"` linkage (no mangling) is only used for C interop or when specifically requested. - Kairo never throws: panics are returned as tagged union values, and a Kairo `try`/`catch` around a Kairo call lowers to one tag compare per `catch` arm on that union. - A C++ exception is unwound by the platform unwinder (libunwind on Unix-like systems) using the standard unwind tables (`.eh_frame` / `__eh_frame`). Every Kairo function is `noexcept` unless marked `@unwind` (or built with `-funwind`), so a C++ exception that reaches a Kairo frame calls `std::terminate` unless that frame lets it through. A Kairo `try`/`catch` can catch one that every frame below it lets through. - Virtual dispatch into C++ classes works without special handling because Kairo lowers method calls on C++ objects directly to Clang, which handles vtable dispatch normally. - C++ smart pointers (`std::unique_ptr`, `std::shared_ptr`, `std::weak_ptr`) map to Kairo's Tether-tracked equivalents (`std::Unique`, `std::Shared`, `std::Weak<*T>`) automatically. No `unsafe` block is required for FFI calls using smart pointers, references, move references, or value types. Only raw pointer parameters (`T*`, `void*`) require an `unsafe` block. See [C/C++ Interop](/docs/language/c-cpp/) and [Unsafe](/docs/language/unsafe/) for the full FFI safety model. --- ## Linker: LLD / Platform Linker `kld` (Kairo's linker driver) defaults to **LLD** for all targets. LLD's compatibility targets: | Mode | Compatibility | |---|---| | ELF | GNU ld compatible | | Mach-O | Apple ld64 compatible | | PE/COFF | MSVC link.exe compatible | | WASM | wasm-ld (LLD's WASM mode) | Kairo does not require LLD. You can use the platform linker by passing `--ld-flags` to forward arguments directly, though the default flag translation assumes LLD syntax. GNU ld is supported for ELF targets. --- ## Reproducible Builds Kairo supports reproducible builds when the following conditions are met: 1. Same source, same flags, same `--target`, same `--cxx-std`. 2. `--no-timestamps` is set (strips all embedded timestamps). 3. `--remap-path-prefix` is used to normalize absolute paths. 4. `SOURCE_DATE_EPOCH` environment variable is set (Clang reads this for embedded timestamps in DWARF; `--source-date-epoch` sets it for you). 5. `--lto=off` (LTO can produce non-deterministic output across runs due to parallel section ordering in ThinLTO). 6. Same LLVM version. The backend is not byte-for-byte stable across LLVM major versions. Kairo does not guarantee reproducibility across different `--opt` levels or when `--fp-model=fast` is used (fast-math can produce different reassociations depending on whether the optimizer's heuristics fire). --- ## What Kairo Explicitly Does Not Target - **POSIX.1-2024**: Kairo's standard library does not wrap POSIX. You call POSIX functions via FFI if you need them. The Kairo stdlib provides its own file, threading, and memory abstractions that map to the platform without requiring POSIX compliance from the target. - **C++ standard (ISO/IEC 14882)**: Kairo is not C++ and does not attempt C++ conformance. C++ interop works through Clang, not through implementing the C++ standard in Kairo. - **MISRA / CERT / SEI coding standards**: These are auditable properties of specific programs, not language-level guarantees. Kairo does not ship a MISRA checker, and Kairo does not generate source in any other language to hand to one. The only C++ it generates is headers, for interop or integrated CI checks (e.g. when shipping a C++ library written in Kairo). - **ISO/IEC 9899 (C standard)**: Same as C++. C interop works through the FFI layer. Kairo is not a C compiler. --- ## Version Pinning | Standard | Version targeted | |---|---| | IEEE floating-point | 754-2019 | | Unicode | 15.1 | | UTF-8 encoding | RFC 3629 | | DWARF debug info | 5 (default), 4 (opt-in) | | x86-64 psABI | System V AMD64 v1.0 | | AArch64 psABI | AAPCS64 (ARM IHI0055) | | Itanium C++ ABI | Current (Clang tracks this) | | C++ interop | Pinned Clang, `--cxx-std` c++20/c++23 (default)/c++26 | | WASI | preview1 (default), preview2 (opt-in) | | WebAssembly binary | MVP + explicit proposals | | ELF | System V gABI + platform psABI | | Mach-O | 64-bit Mach-O | | PE/COFF | Microsoft PE32+ | --- ## Implementation Status URL: https://www.kairolang.org/docs/status/ # Implementation Status The language reference describes Kairo as designed. This page lists where the compiler, version 0.2.3, falls short of it. Each entry is removed when the gap closes. ## What 0.2.3 is 0.2.3 is the third self-hosted release, after 0.2.0 and 0.2.1. The compiler (Stage 1) is written in Kairo and has built itself since 2026-11-06; the C++ transpiler it was bootstrapped from (Stage 0) is retired. The test suite is about 2,475 lit tests, of which 43 are expected failures that name the feature they wait on and 4 are known failures. Only x86_64 Linux is covered by the suite; prebuilt packages exist for Linux, macOS, Windows, FreeBSD and NetBSD ([Installation](/docs/install/)). Built and working: the lexer, preprocessor, parser, name and type resolution, the semantic checks (including purity inference and the [visibility levels](/docs/language/modules/)), generics, classes with the copy / move model, nullables, panics, closures, generators, `eval`, pattern matching, C and C++ interop in both directions (`ffi` imports and `kcc`), parallel Sema and code generation, `--emit-headers`, and [incremental compilation](/docs/language/c-cpp-toolchain/) phase 1 (unchanged files skip code generation), and the language server, [kals](/docs/toolchain/kals/), with clients for VS Code, Zed and Neovim. Not built yet: - [Tether](/docs/language/tether/), the lifetime and memory-safety analysis, is Stage 2 work. Using a moved-from value is already an error; the rest of Tether's checks come later. - Virtual interfaces (calls through `*Iface`) and async (`await`, `spawn`, `thread` expressions) are not compiled. - The parser still hands some malformed input to later passes as ordinary nodes. Poison nodes for invalid syntax, and fully safe pointers through the compiler's own AST, are scheduled before 0.3.5. - Incremental compilation phase 2 (reusing work inside a changed file's neighbours) is planned for a later release. - Targets: 48 cross targets, each built on first use by [ksys](/docs/toolchain/ksys/#supported-targets). Not available yet: glibc on `sparc64` and `x32`, C++ on big-endian `powerpc64` with glibc, and FreeBSD or NetBSD versions other than 14.4 and 10.1. The new glibc architectures are tested by linking, not running. macOS and MSVC targets are built from your own SDK (a Mac assembles its root itself on the first build; see [Installation](/docs/install/#sysroots)). The list below is the detailed set of gaps in what is built. --- --- ## Not Compiled Yet | Feature | Status | Meanwhile | |---|---|---| | Initializing a `const` field or a [field without a default](/docs/language/classes/#fields-without-a-default) in a constructor | Compiles, including in a generic constructor and for an array field built element by element (also an array of arrays, or of a generic length). Not yet ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)): a constructor with an expression body; `try`, an `inline` block, `label!` or `jump!` before the last such initialization; a `static` or array local declared before it and used after it | Move that code after the last initialization, or give the field an initializer | | Virtual interfaces (`virtual interface`, calls through `*Iface`) | Not compiled yet: the declaration is accepted, but `&conformer` does not convert to `*Iface` (SC063E) | Dispatch through a base class with `virtual` methods | | An initializer on an `eval` array-typed field (`eval E: [i32; 2] = [1, 2]` in a class) | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Declare the constant at module scope | | A generic record's field default that reads another field (`class G { var a: i32 = 1 var b: i32 = a + 1 }`) | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Repeat the value instead of reading the field | | Struct destructuring (`var {a, b} = s`) | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Read the fields one by one: `var a = s.a` | | Functions, classes and enums declared inside a function body | Compile. Not yet ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)): one that uses a generic parameter of the function (or class) around it, and an `extend` inside a function body | Declare such a declaration at file scope with its own generic parameter | | In a [script](/docs/language/modules/#scripts): a top-level variable of nullable type whose initializer is not a constant (`var g: i32? = find()`), and top-level destructuring (`var (a, b) = pair()`) | Rejected (`... is not supported yet`) | `var g: i32? = null`, then `g = find()` on the next line; destructure inside a function | | Top-level statements in an imported module (module initialization) | Rejected: only the file the program starts from runs top-level statements | Put the code in a function and call it from the script | | `for ... in` over a Kairo string | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported): the library string does not declare its `op in` yet. Vectors, sets and maps work | Loop over a slice, an array or a range, or index the string | | `eval for` directly in a `module` or class body | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Use an `eval for` in a function body | | In an `eval for`: a label (`outer: eval for ...`), a `return` of a class or struct value from inside the loop, and iterating an array whose length is a generic value parameter | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Return after the loop | | An `eval if` branch that is valid only for some instantiations of a generic (`eval if typeof T == i32 { return int_to_bytes(value) }`, the [Type-based branching](/docs/language/eval/#type-based-branching) example) | Compiles when every branch is valid for every `T`. A branch invalid for the chosen `T` is not skipped: it type-checks without a diagnostic, then the compiler stops with an internal error (I003E "poisoned expr reached codegen"). Waits on per-instantiation branch selection | Use [overloads](/docs/language/functions-overloading/) | | Vectors, sets, maps and f-strings at compile time (`eval V: [i32] = [1, 2]`, `f"n={n}"` in an `eval fn`) | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Use an array; string literals, integers, floats, `bool`, `char`, arrays and tuples are evaluable | | An `eval` field computed by an `eval fn` used as an array length in a field of its own class (`class B { eval J = two() var b: [i32; J] }`) | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported): the class is incomplete inside its own body | Declare the constant at module scope, or make the constant fold (literals and arithmetic over `eval` constants) | | A generic value parameter of a type other than an integer or an [eval class](/docs/language/generics/#eval-classes-as-value-parameters) (``, ``) | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Use an integer parameter | | A generic class's `requires` predicate that names an `eval` constant or `eval fn` (`class B requires sizeof T <= LIMIT`) | Accepted and not checked (a predicate of the class's own parameters, literals and `sizeof` is checked) | Write the limit as a literal in the class's clause, or check it in a constructor's `requires` | | A function that reads a `priv` member of a class in its file, when that class declares a constructor, and whose signature names a nested type (`fn f(k: Outer::Inner, v: *Vault)`) | Fails in the C++ step with I003E (the emitted C++ does not let the function read the private member) | Make the member `pub`, or move the nested type to file scope | | `v.insert(v.begin(), ...)` on a `cxx::std::vector` (an `iterator` where the function takes a `const_iterator`) | Rejected with SC063E: the conversion between the two iterator types is a C++ converting-constructor template, which is not considered | Pass `v.cbegin()` / `v.cend()` | | An unqualified call of a function declared in an imported header's namespace (`tag(b, x)` with `b: adl::Box`), found in C++ by argument-dependent lookup | Not found (R020E) when no function of that name is visible otherwise; with a Kairo function of the same name in scope, the C++ ones are found and ranked with it as in C++. Operators are always found this way | Qualify the call: `adl::tag(b, x)` | | Inheriting constructors in an imported C++ class (`using Base::Base;`) | The class imports, but the inherited constructors are not callable from Kairo: `Der(5)` is [SC063E](/docs/language/diagnostics/) "no matching overload" | Default-construct and assign, or add a forwarding constructor in a header | | A C++ template value argument the parameter cannot hold (`Narrow<256>` for `unsigned char`, `Flag<2>` for `bool`) | Not checked by the compiler; the C++ step rejects it at the use (C115E, clang's wording) | Write a value in the parameter's range | | `for x in v` over an imported C++ template used inside a generic Kairo function over its own parameter (`fn f(v: cxx::std::vector)`) | Fails with an internal compiler error (I003E, "EmitIR: ranged for"). `v.size()`, `v.begin()` and `v.end()` in such a function work | Loop with `v.begin()` / `v.end()` and an iterator, write the function for the concrete element type, or pass the values in a Kairo container | | `map::operator[]` (and any C++ member that default-constructs its element) with a Kairo [ADT enum](/docs/language/enums-adt/) as the element (`cxx::std::map`, then `m[1] = ...`) | Fails in the C++ step ("no matching constructor"): an ADT has no default value | Use `insert_or_assign` / `at`, or wrap the value in a nullable (`map`) | | An imported class template whose non-type parameter's default depends on an earlier parameter (`llvm::SmallVector`, whose `N` is computed from `T`) | The argument must be written (`SmallVector`); omitting it is [R032E](/docs/language/diagnostics/) "requires at least 2 generic arguments" | Write the inline size | | `await`, `spawn` and the `thread` expression (`thread work()`) | Can be declared as operators, but using `spawn` or `thread` is rejected as not yet supported (SC116E), and `await` on a type with `op await` is rejected (SC086E: only a `Future` can be awaited). (A [`thread` variable](/docs/language/variables/#thread-local-variables) is a different construct and is compiled.) | - | | [Panic](/docs/language/panic/) (`panic`, `try`/`catch`/`finally` around a panicking call, the C++ view `::builtin::value_or_throw`) | Compiled and run. Panic sets are inferred and checked, as specified: unhandled calls, declared sets and where they are required, the subset rules for overrides, conformers and function types, `main`, `panic` with `-> !`, constructors and destructors (which never panic), the error-type rules, and `try`/`catch` arms (dead, duplicate, after a bare `catch`); an expression arm may `return`, `break` or `continue`. A panicking function returns its error as a value (no unwinding): propagation, both `try` forms, re-panic (keeping the original site), `finally` (one written after a `try` runs when its block exits, like any `finally`, and warns), `where` groups, closures and function values work, in registers up to 16 bytes. [Generic functions](/docs/language/panic/#generic-functions) and methods of generic types panic too: the set is computed at the definition (a bound's requirement adds its declared set at the bound's arguments, a generic callee its set at the call's), and one C++ template serves every instantiation, its set ordered per instantiation. Not supported ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)): panics in generators and `async` functions, and in generic closures; a function type whose set names a generic parameter; a `for` loop over a panicking `op in`, a panicking `op []` that returns a pointer, a panicking `op as`, and `===` through a panicking `op ==` (every other panicking operator works, derived forms included); a method that implements two requirements, or overrides a method and implements a requirement, whose panic sets differ; a panicking interface requirement whose result names `Self`; keeping a bare `catch e` binding in another variable. The [C++ view](/docs/language/c-cpp-exceptions/#the-value-api) works through `#include "foo.k"` and `--emit-headers`: the inspection helpers, `value_or_throw` and `what()` (from `op panic`, a type's own or an `extend`'s), and a header declaring `[[nodiscard]] Panic`. A [C++ exception arm](/docs/language/c-cpp-exceptions/#c-to-kairo) (`catch e: cxx::std::exception`) works in both `try` forms. The source location in `what()` and `::builtin::site()` is found on ELF (Linux, the BSDs) only so far: elsewhere `what()` gives the type without a location, and a C++ host linked against a Kairo `--shared` library gets no location for an error raised inside the library. An `extend` of a generic type supplying `op panic` is not used by `what()`. `crash!()` and the asserting downcast `p as *D` (a crash on a miss) work | Without a location, log `::builtin::type_id` | | [Variadic enums](/docs/language/enums-adt/#variadic-enums) (`enum `, pack-expanded variants `V { ... }...`) and [generic variadic functions](/docs/language/functions-parameters/#generic-variadic-functions) | Compile: pack parameters, forwarding with `...`, `for` over a pack (including a `return` from inside it), packs in class and base arguments, and pack-expanded variants built and matched by payload type. Not yet ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) or a not-viable call): writing a pack's types as generic arguments (`f(...)`), a pattern over a pack (`Box...`), a pack-expanded field typed other than the pack itself (`e: *E`), and building or matching a pack-expanded variant in a generic function. A partial specialization whose pattern holds a pack, as an argument or nested in one (`Traits, Args...>`, `Traits>`), is [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Pass the types through arguments; build and match the variant where its type is concrete; specialize without the pack | | The checked `as` into a [closed enum](/docs/language/enums-plain/#closed-and-open-enums), and `unwrap!()`, in a file-scope initializer (`var c = f() as Color` outside a function) | Fails in the C++ compiler ("statement expression not allowed at file scope"); a constant operand is checked at compile time and works | Initialize the variable from a function, or with a constant | | `n as E?` from an integer into a nullable plain enum | Fails in the C++ compiler | Assign `n as E` to an `E?` instead | | A C string (`*const std::c_char`, a C++ `const char*`) in an f-string (`f"{e.what()}"`) | Compiles, and prints the pointer (`const c_char @ 0x...`): there is no C-string formatter yet | Pass it on to C or C++ code to print it | | `@unwind` on a closure | Rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) (it parses as an expression attribute) | Use a named `@unwind` function, or build with `-funwind` | | Attributes on expressions other than `@create T(args)` / `@destroy p` (which compile, with no import), and the initializer form `@create T{...}` | Parsed; rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | Write `@create T(args)`, or call `create(...)` | | [`where` guards](/docs/language/where/) on functions | Compile on free functions and methods (methods of generic classes too), with the fallback, priority order, coverage and the unreachable / overlap warnings. Generic functions group too when their overloads differ only in the names of their generic parameters (type and value parameters alike); they must name those parameters alike and have the same bounds. Not yet ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)): on a generic function or method with a pack parameter; a `virtual` or `override` method, an `extend` member, an operator or constructor, an out-of-line method definition, a forward declaration, a generator, an `async` function, a variadic function, or an overload with default arguments. An `unsafe` overload that differs from a guarded one only in `unsafe` is rejected (R039E): it is one function redeclared | Test the condition with an `if` inside one function | | [`typeof`](/docs/language/type-system/#typeof-identity-semantics) | Compiles as a variable's whole declared type (`var y: typeof x`). Not yet, each a compile error: as a value (`var info = typeof x`; `TypeInfo` is not implemented), nested in another type (`*typeof x`), or as a parameter, return, field or cast type | Write the type out | | [Closures](/docs/language/closures/) and lambdas (`fn () { ... }` as a value) | Compile, with every capture mode (by copy, `\|*\|`, `\|*x\|`, `\|const *x\|`, mixed, `\|\|`), stored in a `fn` variable or field, passed, returned and nested. One that captures nothing can be passed where a C function pointer is expected; one that captures, or a `fn` value, is a compile error there. A closure's default parameter values work when it is called through the variable it was written into (`var f = fn (a: i32, b: i32 = 5) ...; f(1)`). Not yet: generic closures (`fn (x: T)`) are rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported); once the closure is copied to another variable or typed as a `fn` value, its default values are gone and a call must pass every argument ([SC099E](/docs/language/diagnostics/)); `async` on a closure is ignored (it runs as a plain closure). Copying a closure that holds a moved-in MOVE value stops the program | Use a named generic function; pass every argument; capture a MOVE value by pointer (`\|*x\|`) when the closure is copied | | [Nullables](/docs/language/nullables/) (`T?`, `null`, `x?`, `== null`, `??`, `?.`, `?->`, `===`, `unwrap!()`, `match` on a `T?`) | `T?` and `null` compile: a `T?` is `::builtin::Nullable` in C++, and a value or `null` converts into one anywhere a `T?` is expected (including `*T?`, a nullable pointer `(*T)?`, and nested `(T?)?`). `var x? = e`, the null test `x?`, `== null` / `!= null`, `??`, `?.`, `?->`, `===`, `unwrap!()`, a `match` on a `T?` and the checked downcast `p as *D?` compile. [Narrowing](/docs/language/nullables/#narrowing) works: a checked nullable reads as its `T`, through conditions, early exits, loops, `match` arms, `@inout` and mutable-`self` calls, pointers and closures, and an unchecked read is a compile error. Not yet: `bool?` is not one byte (a `bool` has no spare value the compiler uses yet); `T? -> U?` between different inner types fails in the C++ compiler; a nullable reached through `->` or a subscript is not narrowed by a check; a checked downcast from a nullable pointer (`maybe_animal as *Dog?`) is rejected (SC027E) | Copy a nullable reached through `->` or a subscript to a local before checking it; unwrap a nullable pointer before downcasting it (`if a? { unwrap!(a) as *Dog? }`) | | A [partial specialization selected by `requires`](/docs/language/requires/#partial-specializations-selected-by-requires) whose clause needs more than literals and the `sizeof` / `alignof` of builtins, pointers and arrays (a struct's size, an `eval` function), or names a conformance (`requires P impl I`) | The first is an error ([SC001E](/docs/language/diagnostics/#generics)) where an instantiation is used, the second is rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported); two constrained partials with the same pattern that both hold are ambiguous even where C++ would order them | Select by the argument's pattern (`

X<*P>`), or by a size of a builtin type | | A generic class whose body names a pointer to itself at a growing argument (`var p: *L>` inside `L`) | Rejected with [SC001E](/docs/language/diagnostics/#generics) "instantiation depth exceeds 128", although nothing is instantiated through a pointer | Name the pointer at a fixed argument, or type-erase it (`*void`) | | A [float-to-integer cast](/docs/language/casting/#float-to-integer) of an out-of-range value, an infinity or NaN | Compiles, but does not saturate: the result is whatever the target's conversion instruction gives (on x86_64, `1.0e18 as i32` is `i32` min and `-1.0 as u8` is 255) | Clamp the value into the target's range before the cast | | `x as bf16` on an `f16`, and `x as f16` on a `bf16` | Fail in the C++ step | Go through `f32`: `x as f32 as bf16` | | `x as f16` on an `i128` or `u128`, `x as i128` / `as u128` on an `f16`, and `x as bf16` on an `f80` | Fail to link: the runtime's conversion routines for these pairs are missing | Go through `f32` (or `i64` for an in-range value) | | An integer literal where a [`byte`](/docs/language/primitives/#byte) is expected (`var b: byte = 0xFF`) | Rejected ([SC028E](/docs/language/diagnostics/) "cannot convert 'i32' to 'byte'") | `0xFFu8 as byte` | | A `char` literal outside ASCII (`'漢'`, `'é'`) | Fails in the C++ step | Build it from its code point: `0x6F22u32 as char` | --- ## Checked by C++, Not by Kairo An assignment to a `const` variable (`const x: i32? = 42` then `x = null`, or to a `static const` / `thread const`) is reported by the C++ compiler at build time rather than as a Kairo diagnostic: `--type-check-only` does not report it. One case is caught by neither: an assignment to a top-level `const` of a [script](/docs/language/modules/#scripts) whose initializer is not a constant (`const LIMIT = load()` then `LIMIT = 6`) compiles and runs. Float `%` and float `<=>` pass the type checker and are rejected by the C++ backend, so a generic bounded by an interface that needs them does not accept `f32` or `f64`. --- ## Not Diagnosed Passing a slice literal to a function that **stores** the slice is not caught. The literal's storage ends with the statement, so the stored slice dangles. This becomes an error when [Tether](/docs/language/tether/) lands; until then, pass a `var` or a `[T]` to any function that keeps what it is given. See [Primitives](/docs/language/collections/#how-long-a-slice-literals-storage-lives). [kld](/docs/toolchain/kld/) does not compare C++ ABI flags across objects. Objects built with different `-fshort-enums` (or another flag that changes layout) link without a warning and disagree at run time; a `-frtti` / `-fno-rtti` mix fails as an ordinary undefined symbol. Build every C++ object of a program with the same flags. Assigning to a `const` binding introduced by a `match` pattern (`case .Error(const message)`) is not reported. See [Enums](/docs/language/enums-adt/#destructuring-with-match). Declaring `var x: T` with no initializer in a generic body is not reported when no bound requires a default constructor. See [Generic Bodies](/docs/language/interfaces/#generic-bodies). Calling a method that a generic class inherits from a generic base with an argument of the wrong type (`Const().put(x)` where `put(self, v: T)` is declared in `Source` and `Const` derives it) is not reported by Kairo: the base's `T` is taken from the argument, and the C++ step rejects the call. A method the class declares itself is checked against the instance's type. A class or struct that declares `impl I` but does not conform to `I` (a missing method, a missing associated type, or two interfaces it declares giving one inherited associated type different defaults) is not reported at its declaration, only where the conformance is used (passing it to a `T impl I`). See [Conformance](/docs/language/interfaces/#conformance). Four [`extend`](/docs/language/extends/) rules are not diagnosed yet: - A plain `extend` outside the type's file, or an `extend ... impl` in neither the type's nor the interface's file, is accepted. See [Same-File Restriction](/docs/language/extends/#same-file-restriction). - Calling an extension member whose bounds the type arguments do not satisfy is not reported at the call site. See [Generic Extends](/docs/language/extends/#generic-extends). - An `extend ... impl` that is missing interface methods is not reported at the `extend` declaration. See [Interface Conformance](/docs/language/extends/#interface-conformance). - An extension member is only meant to be visible in files that import the extension's file, directly or through other imports. A generic bound checks this (a type that meets `T impl I` only through an extension the file does not import is an error there), but a plain member call does not: `m.scale()` can find an extension the file never imports, depending on the order files are compiled in. A [generator](/docs/language/functions-generators/#generator-lifetimes) that outlives the object it was created from, or an `@inout` argument it was given, is not caught; it dangles. This becomes an error when [Tether](/docs/language/tether/) covers generators. Until then, do not keep a generator longer than the object it came from. A [closure](/docs/language/closures/#tether-and-lifetime-safety) that captures a local by pointer (`|*x|`, `|*|`) and outlives it, by being returned or stored, is not caught; the pointer dangles. This becomes an error when [Tether](/docs/language/tether/) lands. Until then, capture by copy in a closure that leaves its scope. --- ## Not in This Release - [Tether](/docs/language/tether/), Kairo's memory-safety system, is not part of this release. Using a moved-from value is already a compile error; the rest of Tether's checks come later. - Some generic code is checked less strictly than it will be in 1.0. - The standard library is minimal: printing goes through `std::io::println`. - A program cannot read its command-line arguments yet: `main` takes no parameters, and `sys::args` (for scripts and programs alike) is planned. - Objective-C headers cannot be imported with `ffi` yet; C and C++ headers can. Plain C and Objective-C files cannot `#include` a `.k` file yet; C++ and Objective-C++ files can. --- ## Language Gaps - A string literal passes to a C `const char*` parameter as it is, and any other Kairo `string` through `s.c_str()`. See [C & C++ Interoperability](/docs/language/c-cpp-calling/#strings-and-const-char). --- ======================================================================== SECTION: LANGUAGE ======================================================================== ## Primitives URL: https://www.kairolang.org/docs/language/primitives/ # Primitives Kairo's primitive types are built into the language and available without imports. They map directly to hardware-supported representations where possible, falling back to software emulation for extended-width types. --- ## Integers All integer types have a fixed, guaranteed size. An integer literal takes the type expected by its context (annotation, parameter, return position, the other operand) and must fit it. With no expected type the default is `i32`; only if the value does not fit `i32` does the compiler fall back to the smallest signed type that can hold it, up to `i512`. See [Literal inference](#5-literal-inference-a-separate-mechanism). | Type | Size | Description | C++ Equivalent | |---|---|---|---| | `u8` | 1 byte | Unsigned 8-bit integer | `uint8_t` | | `u16` | 2 bytes | Unsigned 16-bit integer | `uint16_t` | | `u32` | 4 bytes | Unsigned 32-bit integer | `uint32_t` | | `u64` | 8 bytes | Unsigned 64-bit integer | `uint64_t` | | `u128` | 16 bytes | [Unsigned 128-bit integer](#extended-width-integers-u128-u512-i128-i512) | `__uint128_t` | | `u256` | 32 bytes | [Unsigned 256-bit integer](#extended-width-integers-u128-u512-i128-i512) | | | `u512` | 64 bytes | [Unsigned 512-bit integer](#extended-width-integers-u128-u512-i128-i512) | | | `i8` | 1 byte | Signed 8-bit integer | `int8_t` | | `i16` | 2 bytes | Signed 16-bit integer | `int16_t` | | `i32` | 4 bytes | Signed 32-bit integer | `int32_t` | | `i64` | 8 bytes | Signed 64-bit integer | `int64_t` | | `i128` | 16 bytes | [Signed 128-bit integer](#extended-width-integers-u128-u512-i128-i512) | `__int128_t` | | `i256` | 32 bytes | [Signed 256-bit integer](#extended-width-integers-u128-u512-i128-i512) | | | `i512` | 64 bytes | [Signed 512-bit integer](#extended-width-integers-u128-u512-i128-i512) | | | `usize` | Platform-dependent | Unsigned, pointer-width integer | `size_t` | | `isize` | Platform-dependent | Signed, pointer-width integer | `ptrdiff_t` | `i64` and `u64` are spelled as the target's `int64_t` / `uint64_t`, not hard-coded: `long` on 64-bit Linux and FreeBSD; `long long` on Windows, on every 32-bit target, and on Darwin (a 64-bit platform that still spells `int64_t` as `long long`). This keeps C++ name mangling and header signatures matching on every target. Integer literals default to signed. Use a type suffix to specify: ```kairo var a = 42 // i32 (default) var b = 42u8 // u8 var c = 42i64 // i64 var d = 1_000_000 // i32 underscores are ignored, use freely as separators var e = 0xFF // i32 hexadecimal var f = 0b1010_0011 // i32 binary var g = 0o77 // i32 octal var h = 64usize // usize: the target's pointer width var i = 5f32 // f32: a float suffix on an integer body makes it that float ``` The integer suffixes are `i8` `i16` `i32` `i64` `i128`, `u8` `u16` `u32` `u64` `u128`, in lower or upper case (`42U8`), and `usize` and `isize`. A suffix is a declaration, not a hint: `42u8` is a `u8` wherever it stands, so it selects the `u8` overload and a generic called with it deduces `T = u8`. A value that does not fit the suffix's type is an error, and so is a suffix that names no type (`1u7`, [SC074E](/docs/language/diagnostics/)). Prefixes and separators combine with a suffix: `0xFF_FFu16`, `0b1010u8`. ### Overflow behavior Integer arithmetic wraps around: `+`, `-`, `*`, unary `-`, `~`, `++`, `--`, the shifts and the matching compound assignments compute modulo 2N of the operand's type, two's complement, signed or not, in every build. The result has the operand's type, with no promotion: `~x` on a `u8` is a `u8`, and `a * b` on two `u16` values never overflows an `i32` on the way. ```kairo var a: i32 = 2147483647 var b = a + 1 // -2147483648 var p: u16 = 65535 var q = p * p // 1 var z: u8 = 0 var n = ~z // 255 ``` A shift count is taken modulo the register width: 32 for types up to 32 bits, else the type's width: with `n` a runtime 33, `1i32 << n` is `2`; with `n` a runtime 9, `1u8 << n` is `0`, since a narrow type shifts in 32 bits and then truncates. A constant count must be below the width. See [Bitwise operators](/docs/language/operators/#bitwise). Division and remainder by zero crash the program (like [`crash!()`](/docs/language/panic/#main-and-crash), not a panic). `MIN / -1` is `MIN` and `MIN % -1` is `0`. Overflow is never undefined behavior, and the checks cost nothing where the plain operator would not overflow: the compiled code is the same as C++'s for those inputs. Code imported from C or C++ keeps its own rules. Kairo code writing an imported value follows Kairo's: `++` on a C struct's `uint8_t` field, or `+=` on an `int&` returned by a C++ `operator[]`, wraps. A C bit-field wraps at the field's own width. ### Extended-width integers (u128-u512, i128-i512) If the target hardware supports wide registers (e.g., AVX-512), these types map directly to hardware. Otherwise, the compiler stores them as structs of smaller integers and emits SIMD-accelerated arithmetic when available, falling back to scalar multi-word operations. Extended-width integers are always stack-allocated they are value types, not heap-allocated objects. `i128` and `u128` exist on 32-bit targets too (`i686`, `armv7`, `wasm32`, ...), as structs of smaller integers. --- ## Floating-Point All floating-point types except `f80` follow the IEEE 754 standard. A float literal takes the type expected by its context and must fit it. With no expected type the default is `f64`; only if the value does not fit `f64` does the compiler fall back to the smallest float type that can hold it, up to `f512`. | Type | Size | Precision | C++ Equivalent | |---|---|---|---| | `f16` | 2 bytes | Half (IEEE 754-2008) | `_Float16` | | `f32` | 4 bytes | Single | `float` | | `f64` | 8 bytes | Double | `double` | | `f80` | 16 bytes (12 on i386); 10 hold the value | x87 extended; only on some targets, see below | `long double` | | `f128` | 16 bytes | Quadruple | `__float128` | | `f256` | 32 bytes | IEEE binary256, in software | `::builtin::num::f256_t::F256` | | `f512` | 64 bytes | binary512 (see below), in software | `::builtin::num::f512_t::F512` | `f8e4m3` (OCP E4M3, finite-only) and `f8e5m2` (OCP E5M2) are 1-byte floats. A literal is rounded once; an `f8e4m3` overflow saturates to ±448 and an infinity converts to NaN. Arithmetic rounds the exact result once. `as` converts to and from every float and integer type, and `{x}` prints the shortest digits that read back as the same value. They have no methods yet, are not supported in eval contexts (SC116E), and convert to `f256`/`f512` only through `f32` or `f64` (SC116E). ```kairo var x = 3.14 // f64 (default) var y = 3.14f32 // f32 var z = 1.0e-10 // f64 scientific notation var w = 0x1.8p3f32 // f32 hexadecimal float: 12.0 var b = 1.5bf16 // bf16 ``` The float suffixes are `f16`, `bf16`, `f32`, `f64`, `f80`, `f128`, `f256` and `f512` (`f80` and `f128` only where the target has them, see below), in lower or upper case. A literal is rounded once, to the type it is used at, from its decimal digits: `16777217.0f32` is `16777216.0` and `16777217.0f64` is exact, and `var q: f128 = 0.1` is `0.1` at `f128` precision, not the `f64` value `0.1` widened. An unknown float suffix (`1.5f8`, `1.5xyz`) is [SC074E](/docs/language/diagnostics/). Overflow produces `inf`, underflow produces `0.0`. Operations that produce `NaN` (e.g., `0.0 / 0.0`, `sqrt(-1.0)`) propagate `NaN` per IEEE 754 no crash, no trap. Test for `NaN` with `x.is_nan()` (or `x != x`): a `NaN` compares unequal to everything, itself included, so `x == f64::NAN` is always `false`. An infinity is an ordinary value to compare with: `x == f64::INFINITY`. See [Limits](#limits). > [!NOTE] > `f256` and `f512` are not natively supported on any current hardware and are implemented entirely in software (no LLVM type exists at these widths). Like extended-width integers, they are stack-allocated value types. Expect them to be far slower than hardware floats: on x86_64 at `-O2`, an `f256` add or multiply takes about 0.2 to 0.3 µs and a divide about 0.4 µs; `f512` up to about twice that. ### `f256` and `f512` `f256` is IEEE 754 binary256: a sign bit, a 19-bit exponent (bias 262143) and a 236-bit fraction, so 237 bits of precision (about 71 decimal digits) and a range of about 10^±78913. IEEE 754 defines no 512-bit format. `f512` carries the standard's rule for its interchange formats (IEEE 754-2019, 3.6) to k = 512: precision p = k − round(4·log₂ k) + 13 = 489, leaving w = k − p = 23 exponent bits (bias 4194303) and a 488-bit fraction. The same rule gives the 15 exponent bits of binary128 and the 19 of binary256. That is about 147 decimal digits and a range of about 10^±1262612. Both behave as every other IEEE format does: each operation (`+ - * /`, conversions, square root, fused multiply-add) is rounded once, to nearest with ties to even; there are signed zeros, subnormals and infinities, and an operation that has no value gives a quiet NaN. That NaN is always the same one (sign 0, top fraction bit set); `-x` and `abs` only change the sign bit, NaN or not. There are no floating-point exceptions or flags. - **Conversions.** `x as T` between `f256`/`f512` and any float the target has (`f16`, `bf16`, `f32`, `f64`, `f80`, `f128`, each other) is rounded once, never through an intermediate format. To an integer it truncates toward zero and saturates at the type's limits, and NaN converts to 0, as for every float. From every integer type, `i8` to `u512`, it rounds to nearest even. - **Literals.** `1.5f256`, or any float literal used where an `f256` or `f512` is expected, is rounded once from all its digits, decimal or hex, as `var q: f128 = 0.1` is. A literal is converted when the code runs, not at compile time: an `f256` or `f512` value in an `eval` context (an `eval` constant, an `eval fn`'s parameter or result, an `eval if` condition) is not supported yet ([SC116E](/docs/language/diagnostics/)). - **Limits.** `f256::MAX`, `f256::EPSILON`, `f512::NAN` and the rest are the formats' own, as for every float ([Limits](#limits)). - **Methods.** The same as every float's ([Float methods](#float-methods)); `to_bits()` gives a `u256` / `u512`. - **Formatting.** In an f-string, `{x}` writes the shortest digits that read back as the same value (at most 73 for `f256`, 149 for `f512`); a precision (`{x:.30e}`, `{x:.10}`) gives that many digits, every one exact, the last rounded to even. Width, fill, alignment and sign work as for `f64`. ### `f80` follows the target's `long double` `f80` is the x87 80-bit extended format, and it is C's `long double`. It exists only where the target ABI's `long double` is x87 extended precision. That is a property of the ABI, not the CPU: | Target | `long double` | `f80` | |---|---|---| | x86_64 Linux, BSD, macOS | x87 extended | available | | i386 Linux | x87 extended | available | | x86_64 Windows (MSVC) | binary64, despite the x87 hardware | not available | | x86_64 Android | binary128 | not available | | AArch64 and RISC-V Linux | binary128 | not available | | Apple ARM, Windows on ARM | binary64 | not available | Anywhere else, writing `f80` is an error ([P003E](/docs/language/diagnostics/#p003e-a-primitive-type-is-not-available-on-the-target)). The error names the target and what its `long double` is, and suggests `f64` where `long double` is binary64 and `f128` where it is binary128. Kairo never silently substitutes another float type for `f80`. Where `f80` exists it formats in an f-string like the other floats (`f"{x}"` with `x: f80`). ```kairo // building for x86_64-unknown-linux-gnu var x: f80 = 1.0 // ok // building for aarch64-unknown-linux-gnu var y: f80 = 1.0 // error P003E: long double is binary128 here; use f128 ``` ### Float methods Every float type has the same methods: `f16`, `bf16`, `f32`, `f64`, `f80` and `f128` (where the target has them), `f256` and `f512`. The one exception is `bf16` on WebAssembly, which has no methods yet. They are called on a value, a literal or a limit: ```kairo var x: f64 = 2.0 var r = x.sqrt() // 1.4142135623730951 var y = x.fma(3.0, 1.0) // 7.0: 2.0 * 3.0 + 1.0, rounded once var n = (0.0 / 0.0).is_nan() // true var m = f64::MAX.is_finite() // true var b = (-0.0f32).to_bits() // 0x80000000 ``` | Method | Meaning | Types | |---|---|---| | `to_bits()` | The encoding as an unsigned integer of the same width: `u16` for `f16` and `bf16`, `u32`, `u64`, `u128` for `f128`, `u256`, `u512`. `f80` gives a `u128` holding the 80-bit x87 encoding in its low bits (bit 79 the sign, bit 63 the explicit integer bit), the rest 0 | all | | `sqrt()` | The square root, correctly rounded; `sqrt(-0.0)` is `-0.0`, any other negative is NaN | all | | `fma(b, c)` | `self * b + c`, rounded once | all | | `abs()` | The magnitude: the sign bit cleared, NaN included | all | | `copysign(s)` | `self`'s magnitude with `s`'s sign bit | all | | `is_nan()` | Whether `self` is a NaN | all | | `is_infinite()` | Whether `self` is `+inf` or `-inf` | all | | `is_finite()` | Neither infinite nor NaN | all | | `is_zero()` | Whether `self` is `+0.0` or `-0.0` | all | | `is_subnormal()` | Nonzero and below the smallest normal (`T::MIN_POSITIVE`) | all | | `is_normal()` | Finite, nonzero and not subnormal | all | | `is_sign_negative()` | Whether the sign bit is set: true for `-0.0` and a negative NaN | all | | `is_unordered(o)` | Whether `self` or `o` is a NaN (IEEE 754's unordered relation) | all | "all" is every type above, on every target that has the type; `f8e4m3` and `f8e5m2` have no methods yet. - **Rounding.** `sqrt` and `fma` are correctly rounded (to nearest, ties to even) on every type. `f16` and `bf16` compute in `f32` and round back, which is exact for `sqrt`; their `fma` rounds the exact result to odd at `f32` and then to nearest, so it too rounds only once. `f32`, `f64` and `f80` use the hardware instruction, or the C library's `fmaf` / `fma` / `fmal` where there is none, which are correctly rounded in glibc and musl; elsewhere the result is as exact as that library's. `f80`'s `sqrt` is the x87 `fsqrt` instruction, exact at the default 64-bit precision control. `f128`, `f256` and `f512` use Kairo's software float engine, the same on every target. - **NaN results.** `f128`, `f256` and `f512` return the canonical quiet NaN. The hardware types return what the instruction or the C library gives, which may carry an operand's payload. `abs` and `copysign` only change the sign bit, so they keep a NaN's payload on every type. - **`f128` in a file.** `f128`'s methods are loaded only into the files that spell `f128` (the type, or a literal such as `1.5f128`), as `f256` and `f512` are, so that programs that never use it do not compile the software engine. A file that only receives an `f128` value from elsewhere and never names the type does not see them; writing the type anywhere in the file (`var x: f128 = v`) does. --- ## Implicit Conversions Integer and float types can be **implicitly widened** `i32` to `i64`, `f32` to `f64` but narrowing conversions require an explicit cast. See [Casting](/docs/language/casting/) for details. ```kairo var a: i32 = 42 var b: i64 = a // ok: implicit widening var c: i64 = 1000 var d: i8 = c // compile error: narrowing requires explicit cast var e: i8 = c as i8 // ok: explicit, may truncate ``` --- ## Bool | Type | Size | C++ Equivalent | |---|---|---| | `bool` | 1 byte | `bool` | ```kairo var flag = true var other = false ``` `bool` is 1 byte in memory (not 1 bit) for addressability. Only `true` and `false` are valid values no implicit conversion from integers. --- ## Char | Type | Size | Description | C++ Equivalent | |---|---|---|---| | `char` | 4 bytes | Unicode scalar value (U+0000-U+10FFFF) | `char32_t` | A `char` holds a single decoded Unicode codepoint. It is always 4 bytes regardless of which codepoint it represents. A `char` converts implicitly to and from an integer only when the target is equal or wider: `char` to `u32`, `u64`, `u128`, `i64`, `i128`, and `u8`, `u16`, `u32` to `char`. Everything else (`char` to `u8`, `u16`, `i8`, `i16`, `i32`; `i8`, `i16`, `i32`, `i64`, `i128`, `u64`, `u128` to `char`) needs `as`. An integer literal takes `char` when it is a Unicode scalar value, and `0xD800` or `0x110000` is an error. See the [conversion lattice](/docs/language/conversion-lattice/#4-non-numeric-primitives-rationale). ```kairo var letter = 'A' var emoji = '😶‍🌫' var cjk = '漢' ``` > [!NOTE] > `char` is the *decoded* representation of a single codepoint. Strings store text as UTF-8 bytes internally, not as arrays of `char`. See [Strings](#strings) below. ### C's `char`: `std::c_char` `char` is a Unicode scalar value, which C and C++'s `char` is not. C's plain `char` is `std::c_char` (`import std::c_char`): one byte, a third type beside `signed char` (`i8`) and `unsigned char` (`u8`), signed or not as the target's C is. A C++ `char` imports as `c_char`, so a C string is `*const c_char`, which is `const char*` exactly. It is a character, not a number: `as` converts it to and from the integers, it compares with `==` and `<`, it does no arithmetic, and an integer literal takes it only in 0 through 127, where both signednesses agree. In an f-string a `c_char` prints its code, 0 through 255. ```kairo var c: c_char = 65 // ok: 'A' var d = 200u8 as c_char // the byte 200, whatever the target's char is // var e: c_char = 200 // error SC075E: only 0 through 127 fit on every target var n = (c as i32) + 1 // arithmetic on the integer ``` ### C++'s wide characters: `std::c_wchar`, `std::c_char16`, `std::c_char8` C++'s `wchar_t`, `char16_t` and `char8_t` are their own types too, and import as `std::c_wchar`, `std::c_char16` and `std::c_char8`, never as the integer of their width: `f(wchar_t)` and `f(int)` are two overloads, a `const wchar_t*` is `*const c_wchar`, and `cxx::std::wstring` is `basic_string`. They behave as `c_char` does: characters, not numbers, `as` to and from the integers, `==` and `<`, no arithmetic, and no conversion between them. `c_wchar` is 32 bits on most targets and 16 on Windows, signed or not as the target's C++ says, so a literal takes it in 0 through 0xFFFF; `c_char16` (16 bits, unsigned) takes 0 through 0xFFFF and `c_char8` (8 bits, unsigned) 0 through 255. In an f-string each prints its code. ```kairo var w: c_wchar = 0x263A // ok: fits wchar_t on every target var u: c_char16 = 0x3B1 var n = w as u32 // 9786 // var x: u32 = w // error SC028E: needs an explicit 'as' ``` --- ## Byte | Type | Size | C++ Equivalent | |---|---|---| | `byte` | 1 byte | `std::byte` | `byte` is semantically identical to `u8` in size and representation but restricted to bitwise operations and comparisons no arithmetic. It represents raw data where the value is not meant to be interpreted as a number. ```kairo var b: byte = 0xFF var mask: byte = 0x0F var result = b & mask // ok: bitwise AND // var bad = b + mask // compile error: arithmetic not allowed on byte ``` --- ## Strings | Type | Size | Encoding | |---|---|---| | `string` | 4 words (32 bytes on 64-bit) | UTF-8 | A `string` is a UTF-8 byte sequence. Its fields are public: ```kairo struct string { var data: *const u8 // the bytes var len: usize // length in bytes var cp_len: usize // number of codepoints the bytes encode var cap: usize // heap capacity in bytes; 0 for a borrowed string } ``` `len` counts bytes, not characters; `cp_len` counts codepoints, and `len == cp_len` means the string is ASCII. A string literal is a borrowed view of static storage: it allocates nothing, and its `cap` is `0`. An owned string has `cap` bytes of heap memory behind `data`. Both kinds keep a NUL byte after the last byte, so `data` can be [passed to C as a C string](/docs/language/c-cpp-calling/#strings-and-const-char). ```kairo var greeting = "Hello, Kairo! 📣" // len 18, cp_len 15, no allocation var name = "Name" // len 4, cp_len 4 ``` String literals written next to each other, separated only by spaces, tabs or newlines, are one string, whatever their prefixes: `"a" "b"`, `"a" r"\b"` and `"total: " f"{n}" " items"` are each a single literal. Each piece keeps its own prefix, so a raw piece keeps its backslashes and an `f` piece has its own `{...}` holes. If any piece is an f-string, the whole is the formatted `string` you would get by joining the pieces with `+`, holes evaluated left to right. Otherwise it stays a compile-time literal. A prefix must touch its quote (`f "b"` is a name and a string), and a character literal never joins. A literal suffix on any piece belongs to the whole string, as in C++: `"12" "3"_km` passes `"123"` to `operator""_km`, and so does `"12"_km "3"`. Because a suffix on one piece reads as if it were only that piece's, the compiler warns (SC276W) on every joined string with a suffix, with a fix-it that writes it as one literal (`"123"_km`) when the pieces can be joined as text: all have the first piece's prefix, none is an `f` or triple-quoted piece or comes from a macro, and joining does not change an escape. Two pieces with different suffixes are an error (SC277E), and a joined string with an `f` piece takes no suffix at all (SC074E). ```kairo var n = 3 var s = "total: " f"{n}" r" \items" // "total: 3 \items" var p = "C:" r"\path" // one literal, still compile-time ``` Because UTF-8 is a variable-width encoding, indexing by codepoint (`s[i]`) complexity depends on how the string was constructed. For string literals, the compiler pre-populates a breadcrumb cache at codegen time mapping codepoint positions to byte offsets, making indexing O(1) with zero runtime cost. For strings constructed at runtime from a raw pointer, no cache is available and indexing is O(n). Indexing by byte (`s.bytes[i]`) is always O(1) but returns raw `u8` bytes, not characters. ```kairo var s = "Hello 📣" s.bytes[0] // byte: 0x48 ('H') O(1) s[6] // char: '📣' codepoint indexing, O(1) for literals (compiler cache), O(n) for runtime-constructed strings for ch in s { // ch is char decoded codepoint, yielded sequentially } ``` > [!IMPORTANT] > The stdlib API for strings is still being finalized. Detailed documentation for string methods will be added in a future update. --- ## Void | Type | Size | C++ Equivalent | |---|---|---| | `void` | 0 bytes | `void` | `void` indicates the absence of a value. It can be used as a normal type and as the target of an `unsafe` pointer (`unsafe *void`), using `void` as a normal type denotes a unit type. ```kairo fn log(msg: string) -> void { // ... } var opaque: unsafe *void = get_handle() // raw, untyped pointer var void_t: MyObj = MyObj() // void is valid here ``` --- ## Pointers | Type | Size | Description | |---|---|---| | `*T` | 8 bytes | Safe pointer non-null, compiler-tracked | | `unsafe *T` | 8 bytes | Raw pointer may hold `&null`, no safety checks | `*T` is a thin pointer (8 bytes). It is non-null by construction and supports pointer arithmetic when the compiler can track its provenance via [Tether](/docs/language/tether/). See [Pointers](/docs/language/pointers/) for full details. `unsafe *T` is a raw C-style pointer with no compiler tracking. It can be null, and dereferencing a null `unsafe *T` is undefined behavior. Use `unsafe *T` for [C/C++ interop](/docs/language/c-cpp/), custom allocators, and other low-level scenarios. See [Pointers](/docs/language/pointers/) and [Unsafe](/docs/language/unsafe/) for full details. ```kairo var x = 42 var p: *i32 = &x // safe pointer to x var q: unsafe *i32 = unsafe &x // raw pointer, no tracking ``` --- Arrays, slices, vectors, list literals, maps, sets, tuples and function pointers are covered in [Collections](/docs/language/collections/). --- ## Platform-Dependent Sizes `usize` and `isize` match the target platform's pointer width: | Platform | `usize` / `isize` | |---|---| | 64-bit | 8 bytes | | 32-bit | 4 bytes | | 16-bit | 2 bytes | --- ## Limits Every numeric primitive has a fixed set of associated constants, the Kairo answer to C++'s `std::numeric_limits` and C's `` / ``. They are spelled like a class's `eval` members, `Type::NAME`: ```kairo var lo = i32::MIN // -2147483648 var hi = u8::MAX // 255 var eps = f64::EPSILON // 2.220446049250313e-16 var inf = f32::INFINITY var buf: [u8; u16::MAX as usize + 1] // a constant: legal in an array length ``` Each one is a constant of its own type, exactly as a suffixed literal is: `u64::MAX` is a `u64` in any context, `var x: u8 = i32::MAX` is the usual narrowing error ([SC028E](/docs/language/diagnostics/)), and `u8::MAX + 1` wraps to `0` like any `u8`. They are constants wherever a constant is needed: an array length, an `eval` binding, `eval if`, a generic value argument. The descriptive ones (`BITS`, `MANTISSA_DIGITS`, the exponents) are `u32` or `i32`, as listed. ### Integers `u8` through `u128`, `i8` through `i128`, `usize`, `isize`: | Name | Type | Value | |---|---|---| | `MIN` | the type | the smallest value (`0` for unsigned) | | `MAX` | the type | the largest value | | `BITS` | `u32` | the width in bits | `usize` and `isize` take the target's width: `usize::MAX` on a 32-bit target is `4294967295`. `BITS` exists for the 256- and 512-bit integers too; their `MIN` and `MAX` are not supported yet. ### Floating point `f8e4m3`, `f8e5m2`, `f16`, `bf16`, `f32`, `f64`, `f80`, `f128`: | Name | Type | Meaning | C++ | |---|---|---|---| | `MIN` | the type | most negative finite value (`-MAX`) | `lowest()` | | `MAX` | the type | largest finite value | `max()` | | `MIN_POSITIVE` | the type | smallest positive normal value | `min()` | | `MIN_SUBNORMAL` | the type | smallest positive subnormal value | `denorm_min()` | | `EPSILON` | the type | the next value after `1.0`, minus `1.0` | `epsilon()` | | `INFINITY` | the type | positive infinity | `infinity()` | | `NEG_INFINITY` | the type | negative infinity | `-infinity()` | | `NAN` | the type | a quiet `NaN` | `quiet_NaN()` | | `MANTISSA_DIGITS` | `u32` | significand bits, the implicit bit included | `digits` | | `DIGITS` | `u32` | decimal digits that survive text to float to text | `digits10` | | `MAX_DIGITS` | `u32` | decimal digits float to text to float needs | `max_digits10` | | `MIN_EXP` | `i32` | one more than the smallest normal binary exponent | `min_exponent` | | `MAX_EXP` | `i32` | one more than the largest binary exponent | `max_exponent` | | `MIN_10_EXP` | `i32` | smallest `n` with `10^n` normal | `min_exponent10` | | `MAX_10_EXP` | `i32` | largest `n` with `10^n` finite | `max_exponent10` | | `RADIX` | `u32` | always `2` | `radix` | | `BITS` | `u32` | storage width in bits | `sizeof(T) * CHAR_BIT` | > [!WARNING] > **`MIN` is not C++'s `min()`.** `std::numeric_limits::min()` is the smallest positive normal value. Kairo's `f64::MIN` is the most negative finite value, spelled the same way as `i32::MIN`, so `T::MIN` is the bottom of the range for every numeric type. C++'s `min()` is `MIN_POSITIVE`. | | `MANTISSA_DIGITS` | `EPSILON` | `MAX` | `MIN_POSITIVE` | `MIN_SUBNORMAL` | `DIGITS` | `MAX_DIGITS` | `MIN_EXP` | `MAX_EXP` | `MIN_10_EXP` | `MAX_10_EXP` | |---|---|---|---|---|---|---|---|---|---|---|---| | `f8e4m3` | 4 | 2⁻³ | 448 | 2⁻⁶ | 2⁻⁹ | 0 | 3 | −5 | 9 | −1 | 2 | | `f8e5m2` | 3 | 2⁻² | 57344 | 2⁻¹⁴ | 2⁻¹⁶ | 0 | 2 | −13 | 16 | −4 | 4 | | `f16` | 11 | 2⁻¹⁰ | 65504 | 2⁻¹⁴ | 2⁻²⁴ | 3 | 5 | −13 | 16 | −4 | 4 | | `bf16` | 8 | 2⁻⁷ | ≈3.39·10³⁸ | 2⁻¹²⁶ | 2⁻¹³³ | 2 | 4 | −125 | 128 | −37 | 38 | | `f32` | 24 | 2⁻²³ | ≈3.40·10³⁸ | 2⁻¹²⁶ | 2⁻¹⁴⁹ | 6 | 9 | −125 | 128 | −37 | 38 | | `f64` | 53 | 2⁻⁵² | ≈1.80·10³⁰⁸ | 2⁻¹⁰²² | 2⁻¹⁰⁷⁴ | 15 | 17 | −1021 | 1024 | −307 | 308 | | `f80` | 64 | 2⁻⁶³ | ≈1.19·10⁴⁹³² | 2⁻¹⁶³⁸² | 2⁻¹⁶⁴⁴⁵ | 18 | 21 | −16381 | 16384 | −4931 | 4932 | | `f128` | 113 | 2⁻¹¹² | ≈1.19·10⁴⁹³² | 2⁻¹⁶³⁸² | 2⁻¹⁶⁴⁹⁴ | 33 | 36 | −16381 | 16384 | −4931 | 4932 | | `f256` | 237 | 2⁻²³⁶ | ≈1.61·10⁷⁸⁹¹³ | 2⁻²⁶²¹⁴² | 2⁻²⁶²³⁷⁸ | 71 | 73 | −262141 | 262144 | −78912 | 78913 | | `f512` | 489 | 2⁻⁴⁸⁸ | ≈2.07·10¹²⁶²⁶¹¹ | 2⁻⁴¹⁹⁴³⁰² | 2⁻⁴¹⁹⁴⁷⁹⁰ | 146 | 149 | −4194301 | 4194304 | −1262610 | 1262611 | The values are the formats' own (IEEE 754 for `f16`, `f32`, `f64`, `f128` and `f256`; `f512`'s rule, see above; bfloat16; x87 extended; OCP FP8 E4M3FN and E5M2), computed by the compiler from each format's layout, never read from the host's ``. Every finite one is exact. Comparing with an infinity works as with any value; comparing with `NAN` never does, because a `NaN` is unequal to everything, itself included: ```kairo if x == f64::INFINITY { } // true for +infinity if x != x { } // true exactly for a NaN if x == f64::NAN { } // always false ``` ### Limits a type does not have A limit a format does not have is not defined, and naming it is an error ([R024E](/docs/language/diagnostics/)), never a substitute value: - `f8e4m3` is the FN format: it has no infinity, and overflow saturates to 448. `f8e4m3::INFINITY` and `f8e4m3::NEG_INFINITY` are errors; it has a `NAN`. - `f80` exists only where the target's `long double` is x87 extended. Elsewhere, `f80::MAX` is the same [P003E](/docs/language/diagnostics/) as spelling `f80` at all. - The float limits (`EPSILON`, `INFINITY`, ...) are not defined on integers. ### `char`, `byte`, `bool` | Type | Members | |---|---| | `char` | `MIN` = `'\0'`, `MAX` = `'\U0010FFFF'`, `BITS` = 32 | | `byte` | `BITS` = 8. No `MIN` or `MAX`: a byte is not a number. | | `bool` | none | `char::MAX` is the largest Unicode scalar value. The range between `MIN` and `MAX` is not contiguous (the surrogates U+D800 to U+DFFF are not `char`s); the constants name the ends. > [!NOTE] > `T::MAX` on a generic parameter `T` is not supported yet. --- ## Summary ```kairo // Integers var a = 42 // i32 var b = 42u8 // u8 var c = 0xFF // i32 (hex) var d = 0b1010 // i32 (binary) var e = 1_000_000 // i32 (underscores as separators) // Floats var f = 3.14 // f64 var g = 3.14f32 // f32 // Bool, char, string var h = true // bool var i = '📣' // char (4 bytes, Unicode scalar) var j = "Hello, Kairo!" // string (UTF-8) // Byte var k: byte = 0xFF // raw byte, no arithmetic // Pointers var x = 42 var *p = &x // *i32 var q: unsafe *i32 = unsafe &x // Collections var nums: [i32] = [1, 2, 3] // vector var view: [i32;] = [1, 2, 3] // slice var rgb: [u8; 3] = [255, 128, 0] // array var ages: {string: i32} = {"Alice": 30, "Bob": 25} // map var primes: {i32} = {2, 3, 5, 7} // set var point: (f64, f64) = (1.0, 2.0) // tuple // Function pointer fn add(a: i32, b: i32) -> i32 { return a + b } var f: fn (i32, i32) -> i32 = add ``` --- The full conversion rules between primitive types are covered in the [Conversion Lattice](/docs/language/conversion-lattice/). ## 5. Literal inference: a separate mechanism Literals are **untyped** until a type is assigned. Literal typing is not conversion and does not consult this lattice. 1. If an expected type is available from context (annotation, parameter, return position, the other operand of a binop, aggregate element type), the literal takes that type directly, and the compiler checks the value fits. `var b: u8 = 42` is fine. `var b: u8 = 300` is an error at the literal, with the range in the diagnostic. The other operand of a binop gives its type whichever side the literal is on: `1 + b` and `b + 1` are both `u8` additions, and `300 + b` is the same error as `b + 300`. A shift's result is its left operand's type, so a literal on the left of `<<` / `>>` takes the expected type when there is one (`var m: u16 = 1 << n` is a `u16` shift) and otherwise the count's integer type (`1 << 4u8` is a `u8` shift). When both operands are untyped literals, neither gives the other a type and rule 2 applies (`1 << 4` is `i32`). 2. With no expected type, the default is `i32` for integer literals and `f64` for float literals. Only if the value does not fit does the "smallest type that holds it" rule from [Integers](#integers) apply. Rule 1 comes first on purpose. If promotion fired unconditionally, `var x: u32 = 3000000000` would type the literal as `i64` before looking at the annotation, and then fail to narrow it. Expected-type-first removes that whole class of error. Suffixed literals (`42u8`) are typed at the literal and then participate in conversion normally. --- ## See also - [Collections](/docs/language/collections/) - [Conversion Lattice](/docs/language/conversion-lattice/) - [Casting](/docs/language/casting/) - [Implicit Conversions](/docs/language/casting-implicit/) - [Pointers](/docs/language/pointers/) - [Type System](/docs/language/type-system/) - [Calling C/C++](/docs/language/c-cpp-calling/) --- ## Variables & Bindings URL: https://www.kairolang.org/docs/language/variables/ # Variables & Bindings | Keyword | Mutable | Storage | Initializer | Type annotation | |---|---|---|---|---| | `var` | Yes | Automatic | Optional (default-initialized) | Optional (inferred) | | `const` | No | Automatic | Required | Optional (inferred) | | `static` | Yes | Static | Optional | Optional (inferred) | | `thread` | Yes | Thread-local (one instance per thread) | Optional | Optional (inferred) | | `eval` | No | Compile-time | Required | Optional (inferred) | > Variables in Kairo are mutable by default. `const` bindings at local scope require an initializer, but class-level `const` members can be left uninitialized at declaration and assigned exactly once in the constructor body. See [Classes](/docs/language/classes/#const-members-in-constructors) for details. ```kairo var x = 42 var y: string = "Hello, World!" ``` Multi-variable declarations on a single line are not supported. Each binding gets its own statement. --- ## Identifiers An identifier is a run of letters, digits, `_`, `#` and any non-ASCII (UTF-8) characters, and it cannot begin with a digit. `#` has no special meaning: it is an ordinary name character, valid at the start, in the middle or at the end of a name, as many times as you like. There is no length limit. ```kairo var count = 0 var größe = 12 var item#2 = "second" var a#b##c__42 = true ``` Keywords are spelled only with ASCII letters, digits and `_`, so a name containing `#` (or any non-ASCII character) is never a keyword. That makes `#` a convenient way to use a keyword's spelling as a name: `#op`, `#match` and `#type` are plain identifiers. Each is its own name, distinct from the keyword and from any other spelling: `#op` and `op#` are two different variables, and you write the `#` every time you use one. ```kairo var #type: string = "circle" std::io::println(#type) ``` --- ## Naming Conventions Kairo recommends the following conventions. They are not enforced as hard errors, but the compiler emits readability warnings when they are not followed. | Kind | Convention | Example | |---|---|---| | Variables | snake_case | `my_value` | | Functions | snake_case | `get_name` | | Constants | UPPER_SNAKE_CASE | `MAX_SIZE` | | Types (classes, structs, enums) | PascalCase | `HttpServer` | --- ## Type Inference The compiler infers the type from the initializer when no annotation is provided. Explicit annotations are optional but can be used to force a specific type. ```kairo var a = 42 // inferred as i32 var b = 3.14 // inferred as f64 var c: u8 = 42 // explicitly u8 var d = "hello" // inferred as string ``` See [Primitives](/docs/language/primitives/) for default type rules integer literals default to `i32`, float literals default to `f64`. --- ## Declaration Shorthands When the type is fully determined by the initializer, the `*` or `unsafe *` qualifier can be placed on the variable name instead of writing out the full type annotation: ```kairo var *ptr = @create i32(10) // equivalent to: var ptr: *i32 = @create i32(10) var unsafe *raw = unsafe std::alloc(sizeof i32 * 1) // equivalent to: var raw: unsafe *i32 = unsafe std::alloc(sizeof i32 * 1) ``` The [nullable shorthand `?`](/docs/language/nullables/#shorthand-declaration) works the same way: ```kairo var name? = get_name() // equivalent to: var name: string? = get_name() ``` The stars give the pointer depth, to any depth, and they combine with `?`: ```kairo var x = 5 var *p = &x // *i32 var **pp = &p // **i32 var ***ppp = &pp // ***i32 var *n? = &x // (*i32)?: a nullable pointer, wrapped once var *m? = find_ptr() // find_ptr() -> (*i32)?: m is (*i32)?, not ((*i32)?)? ``` These are purely syntactic sugar the compiler infers the full type from the right-hand side. The shorthand never converts anything: the stars must match the initializer, and a mismatch is a compile error whose fix-it writes the right spelling: ```kairo var *bad = &p // error: '*bad' states a pointer of depth 1, but its initializer is '**i32', a pointer of depth 2; write '**bad' var *notp = x // error: '*notp' declares a pointer, but its initializer has type 'i32', which is not one var unsafe *s = &x // error: 'unsafe *s' declares an unsafe pointer, but its initializer is the safe pointer '*i32'; write '*s' var *m2 = find_ptr() // error: '*m2' is initialized with a nullable '*i32?'; write '*m2?' so the declaration says it may be null ``` `unsafe` describes the outermost pointer only, as in the type `unsafe **i32` (an unsafe pointer to a safe `*i32`). A shorthand and a type annotation on the same name (`var *p: *i32`, `var x?: i32`) is an error: write one or the other. Fields declare their type and never take a shorthand. The long form is always valid and preferred when clarity matters. A binding with neither an annotation nor a shorthand whose inferred type is nullable or a pointer gets a warning, so the declaration always shows what the binding is. The fix-it writes the shorthand: ```kairo var n = find() // warning: 'n' is nullable; write 'n?' so it reads as one var p = &x // warning: 'p' is a pointer; write '*p' var pp = &p // warning: 'pp' is a pointer; write '**pp' var r = raw() // raw() -> unsafe *i32. warning: 'r' is a pointer; write 'unsafe *r' var m = find_ptr() // warning: 'm' is a nullable pointer; write '*m?' so it reads as one var q: *i32 = &x // no warning: the type is written ``` Destructuring and `for` bindings are not checked, and neither is a binding whose type depends on a generic parameter. --- ## Default Initialization Types with a default value are zero-initialized when declared without an initializer. Integers default to `0`, strings to `""`, collections to empty. ```kairo var a: i32 // 0 var b: string // "" var d: [i32] // [] ``` `bool` has no default value: declaring a `bool` without an initializer is an error. The same applies to a struct or class with no default constructor, including one whose default constructor is explicitly deleted, to an [enum with payloads](/docs/language/enums-adt/) (no variant is its default), and to an array of any of these. A class field of such a type is initialized by the constructor instead; see [Classes](/docs/language/classes/#fields-without-a-default). A struct or class that declares no constructor at all has an implicit default constructor, which builds each base and field from nothing: a field with an initializer takes it, any other field takes its type's default. It exists only when every one of them can be built that way, so a field with no initializer whose type has no default (a `bool`, a record without a default constructor, ...), a `const` field with no initializer, or a base with no default constructor leaves the type with none, and the error names that field or base. Declaring any constructor, a `@copy` or `@move` one included, means there is no implicit one. ```kairo struct Point { var x: i32 var y: i32 = 5 } var p: Point // ok: x is 0, y is 5 struct Flag { var on: bool } var f: Flag // error: Flag has no default constructor: field 'on' has no initializer ``` ```kairo var c: bool // error: c must be initialized class Token { fn Token(self) = delete } var t: Token // error: Token has no default constructor ``` --- ## Constants Immutable bindings use `const`. A `const` variable cannot be reassigned after initialization. ```kairo const x = 42 const name: string = "Kairo" // x = 100 // compile error: x is const ``` Unlike `var`, a `const` binding without an initializer is a hard compile error constants must always be explicitly initialized. ```kairo const x: i32 // compile error: const requires an initializer ``` --- ## Compile-Time Constants (`eval`) For values that must be resolved at compile time, use `eval`. This is equivalent to C++'s `consteval` the expression **must** be evaluable at compile time, and a compile error is raised if it cannot be. ```kairo eval PI = 3.14159 eval MAX_SIZE = 1024 * 1024 ``` `eval` bindings are implicitly `const`. See [Eval](/docs/language/eval/) for full details on compile-time evaluation, including `eval` functions and restrictions. --- ## Static Variables `static` declares a binding with static storage duration it lives for the entire program. Its type follows the same rule as `var`: write a type, an initializer, or both, and with an initializer the type is inferred. A `static` with neither is an error. ```kairo static counter: i32 = 0 static limit = 64 // i32 static *top = &limit // *i32 ``` `static` can be combined with `const` for immutable static data, in either order: `static const` and `const static` are the same declaration. The `const` applies to the binding itself, so the static cannot be reassigned; a `const` deeper in the type (`static p: *const i32`) only protects what it points to. The shorthands work as usual. ```kairo static const LIMIT = 64 // const i32, static storage const static NAME: string = "k" // same thing, other order static const *ROOT = &limit // *i32 that cannot be re-pointed ``` Seen from C++, a namespace-scope `static const` is a `const` variable, a function-local one is `static const`, and a class member is a `static const` data member. `eval` is already `const`, so `eval const` and `const eval` are accepted and mean exactly `eval`. See [Modules](/docs/language/modules/) for `static` at module scope. --- ## Thread-Local Variables `thread` declares a binding with thread storage duration: every thread gets its own instance, initialized when the thread first touches it and destroyed when that thread exits. Like `static`, its type may be written or inferred from the initializer, and it may appear at file scope, class scope, or inside a function body. A function-local `thread` keeps its value across calls on the same thread, like a static local, and is independent per thread. ```kairo thread counter: i32 = 0 thread const WORKER_NAME: string = "worker" class Pool { thread current: *Pool? } fn next_id() -> u64 { thread counter: u64 = 0 counter += 1 return counter } ``` `thread` combines with `const` the way `static` does. A `thread` binding without an initializer is default-initialized per thread under the rules in [Default Initialization](#default-initialization). Access is `name` at file scope and `Self::name` / `Type::name` at class scope, the same as `static`. Seen from C++, a `thread` binding is a `thread_local` variable (`static thread_local` in a class or a function body). `static thread` is accepted as another spelling of `thread`. --- ## Shadowing Constants can shadow previous bindings of the same name. Each `const` declaration creates a new binding the previous one becomes inaccessible. ```kairo const raw = "42" const raw = std::parse(raw) // shadows string with i32 valid const raw = raw * 2 // shadows again valid ``` Mutable variables cannot shadow. Redeclaring a `var` with the same name in the same scope is a compile error. ```kairo var x = 42 var x = 100 // compile error: var cannot shadow ``` > [!NOTE] > Shadowing is restricted to `const` because shadowing a mutable variable is almost always a bug you likely meant to reassign (`x = 100`) rather than redeclare. --- ## Destructuring [Tuples](/docs/language/collections/#tuples-t1-t2-) and [structs](/docs/language/structures/) can be destructured into individual bindings. Use parentheses for tuples and curly braces for structs. ### Tuples ```kairo var point = (10, 20, 30) var (x, y, z) = point // x = 10, y = 20, z = 30 ``` ### Structs ```kairo struct Color { var r: u8 var g: u8 var b: u8 } var color = Color { r: 255, g: 128, b: 0 } var {r, g, b} = color // r = 255, g = 128, b = 0 ``` Destructured names must match the field names in the struct definition. The binding order follows the definition order. ### Discards Use `_` to ignore values you don't need. `_` is not a variable it cannot be referenced after destructuring. ```kairo var (x, _, z) = (1, 2, 3) // discard the second element var {r, _, _} = color // keep only r for _ in 0..10 { // loop body doesn't need the index } ``` The compiler will error if you attempt to use `_` as a value. --- Nullable types are covered in [Nullables](/docs/language/nullables/). --- ## The `const` Binding Rule Every `const` in Kairo answers one yes-or-no question about one thing: *can this be changed?* A plain value is one thing, so it has one question. A pointer is two things, the pointer and the value it points at, so it has two: 1. **Can I change the pointer?** That is, can it be made to point somewhere else. 2. **Can I change the pointee?** That is, can the value it points at be written through it. The two answers are independent, and each one is written in its own place: | Question | Where it is written | Yes | No | |---|---|---|---| | Can I change the pointer? | The declaration keyword | `var ptr` | `const ptr` | | Can I change the pointee? | Directly after the `*` | `*T` | `*const T` | Those are the only places a `const` can go, and a `const` always applies to the thing immediately to its right. You read a declaration left to right and each `const` you meet answers one question. There is never a puzzle about which part of the type a `const` belongs to, the way there is with `const int*` and `int* const` in C and C++. ### On simple variables A plain value has only the first question: ```kairo const x: i32 = 42 x = 10 // compile error: x is const ``` ### On pointers Two questions with two answers each gives four combinations: | Declaration | Change the pointer? | Change the pointee? | |---|---|---| | `var ptr: *i32` | Yes | Yes | | `const ptr: *i32` | No | Yes | | `var ptr: *const i32` | Yes | No | | `const ptr: *const i32` | No | No | ```kairo var a: *i32 = &x a = &y // ok *a = 10 // ok const b: *i32 = &x b = &y // compile error: b is const, it cannot point anywhere else *b = 10 // ok: the pointee is still writable var c: *const i32 = &x c = &y // ok: c can point somewhere else *c = 10 // compile error: cannot write through a *const pointer const d: *const i32 = &x d = &y // compile error *d = 10 // compile error ``` > [!TIP] > `var ptr: *const T` is the one you will reach for most: a read-only view of something that you can still re-point. Add `const` on the binding only when the pointer itself must never move. The rule scales to any depth. Every `*` adds one more thing that can be pointed at, and so one more place a `const` can go: ```kairo const ptr: *const *i32 = &ptr2 ptr = &ptr3 // compile error: ptr is const *ptr = &x // compile error: the inner pointer is const **ptr = 10 // ok: the i32 at the end is not const ``` `*const T` answers "can I write through *this* pointer?". It does not answer "can anyone change this value?". Another pointer to the same value may still be writable. See [Ownership](/docs/language/ownership/#pointer-aliasing). ### A practical example Consider a configuration object that should be readable through a pointer but never modified: ```kairo class Config { pub var host: string pub var port: i32 fn Config(self, host: string, port: i32) { self.host = host self.port = port } fn address(const self) -> string { return f"{self.host}:{self.port}" } fn set_port(self, port: i32) { self.port = port } } var config = Config("localhost", 8080) var ptr: *const Config = &config ptr->address() // ok: address() is a const method ptr->set_port(9090) // compile error: set_port() mutates, ptr points to const Config ``` ### On objects and methods `const self` is the pointee question asked about the receiver: can this method change the object it is called on? A `const` object, or one reached through a `*const T`, only allows methods that answer no. ```kairo const server = Config("localhost", 8080) server.address() // ok: const method server.set_port(9090) // compile error: set_port() is not const ``` > [!WARNING] > `var x: const i32 = 42` is a compile error. A plain value has one question, and the declaration keyword already answers it, so write `const x: i32 = 42`. For the same reason `var ptr: const *const i32` is rejected: the pointer question belongs to the keyword, so write `const ptr: *const i32`. This avoids the `const int* x` vs `int* const x` confusion that C++ is notorious for. --- ## Scope and Lifetime Variables are block-scoped and [destroyed at the end of their enclosing block](/docs/language/ownership/#destruction-order). ```kairo { var x = 42 // x is live here } // x is no longer accessible ``` [Tether](/docs/language/tether/) performs full-program analysis to track lifetimes automatically no lifetime annotations are required. If Tether determines that a pointer outlives its referent and cannot automatically [promote the pointer](/docs/language/tether-promotion/) (to a shared, weak, or unique smart pointer), it emits a compile error. ```kairo var x = 10 var *y = &x { *y = 15 // ok: x is still alive, y is valid } std::io::println(*y) // Tether error: y's safety cannot be guaranteed at this point ``` See [Tether](/docs/language/tether/) and [Ownership](/docs/language/ownership/) for the full lifetime and borrowing model. --- All five declaration keywords `var`, `const`, `static`, `eval`, `thread` work in both local and class/struct scope. ## See also - [Nullables](/docs/language/nullables/) - [Primitives](/docs/language/primitives/) - [Eval](/docs/language/eval/) - [Pointers](/docs/language/pointers/) - [Ownership](/docs/language/ownership/) - [Tether](/docs/language/tether/) - [Collections](/docs/language/collections/) - [Structures](/docs/language/structures/) --- ## Operators URL: https://www.kairolang.org/docs/language/operators/ # Operators Kairo's operators follow C-style precedence and semantics with a few additions: exponentiation (`^^`), null-aware equality (`===`), null-safe access (`?.`, `?->`), and ranges (`..`, `..=`). Most operators can be overloaded for user-defined types; the [overload table](/docs/language/operator-overloading/#all-overload-able-operators-for-user-defined-types) lists which. ## In this section - [Operator Overloading](/docs/language/operator-overloading/) --- ## Arithmetic | Operator | Description | Example | |---|---|---| | `+` | Addition / unary plus | `a + b`, `+a` | | `-` | Subtraction / unary negation | `a - b`, `-a` | | `*` | Multiplication | `a * b` | | `/` | Division | `a / b` | | `%` | Modulo (remainder) | `a % b` | | `^^` | Exponentiation | `2 ^^ 8` -> 256 | Integer division truncates toward zero, matching C++. The base of `^^` takes the expected type, the exponent may be any integer type, and the result has the base's type (`u64 ^^ u8` is `u64`, `f64 ^^ i32` is `f64`). A float exponent is an error. - `x ^^ 0` is `1`. - A negative exponent is `(1 / x) ^^ n` using the base type's own division. For an integer base that is `0`, `1` or `-1`; for a float base it is the reciprocal. - Overflow behaves exactly as repeated `*` does; see below. ```kairo var a = 2 ^^ 10 // 1024 var b = 2.0 ^^ -2 // 0.25 var c = 2 ^^ -1 // 0: 1 / 2 is 0 for an integer var d = 2 ^^ 0.5 // error: the exponent must be an integer ``` ### Integer overflow Integer arithmetic wraps around, signed and unsigned, in every build: `+`, `-`, `*`, unary `-`, `~`, `++`, `--`, the shifts and their compound assignments compute modulo 2N of the operand's type. Overflow is never undefined behavior and never a crash. Division and remainder by zero crash the program. See [Primitives](/docs/language/primitives/#overflow-behavior) for full details on numeric type behavior. ### Floating-point overflow Overflow produces `inf`, underflow produces `0.0`. Operations that produce `NaN` (e.g., `0.0 / 0.0`, `sqrt(-1.0)`) propagate `NaN` per IEEE 754 no crash, no trap. Test for `NaN` with `x != x`; `x == f64::NAN` is always `false`. See [Primitives](/docs/language/primitives/#limits). --- ## Comparison | Operator | Description | Example | |---|---|---| | `==` | Equality | `a == b` | | `!=` | Inequality | `a != b` | | `<` | Less than | `a < b` | | `>` | Greater than | `a > b` | | `<=` | Less than or equal | `a <= b` | | `>=` | Greater than or equal | `a >= b` | | `<=>` | Three-way comparison (spaceship) | `a <=> b` | | `===` | Null-aware equality | `a === b` | `<=>` returns an `Ordering`, matching the C++20 spaceship operator. > [!NOTE] > `<=>` on two floating-point values does not yet produce a usable `Ordering` (a NaN has no ordering). On integers, characters and booleans, and on types that define `op <=>`, it does. Compare floats with `<`, `==` and `>` for now. ### `==` vs `===` `===` is valid when at least one operand is [nullable](/docs/language/nullables/) (`T?`). `a === b` is true when both are non-null and equal: it reads as `(a? && b?) && a == b`, with `==` applied to the unwrapped values. A non-nullable operand needs no test, so `a === 5` is `a? && a == 5`. On nullable pointers (`*T?`) it compares the values they point to, where `==` compares **addresses**. This goes one level only: on `(**T)?` it compares the `*T` values, which are addresses. Using `===` where neither operand is nullable is an error, including two `*T`. To compare the pointees of two non-null pointers, dereference them and use `==`. When a nullable pointer is involved, both sides must be pointers (`p === 42` is an error), and a nullable raw pointer (`unsafe *T?`) needs an `unsafe` block, since `===` dereferences it. `x === null` is never true, so it is an error, with a fix-it that writes the null test `!x?`. ```kairo var a = 42 var b = 42 var p: *i32? = &a var q: *i32? = &b p == q // false: different addresses p === q // true: both point to 42 ``` ```kairo var *x = &a var *y = &b x === y // error: '===' needs a nullable operand; '*i32' and '*i32' are not nullable *x == *y // true ``` `===` is not overloadable. --- ## Logical | Operator | Description | Example | |---|---|---| | `&&` | Logical AND | `a && b` | | `\|\|` | Logical OR | `a \|\| b` | | `!` | Logical NOT | `!a` | Short-circuit evaluation applies: `&&` does not evaluate the right operand if the left is `false`, and `||` does not evaluate the right operand if the left is `true`. This is identical to C++. --- ## Bitwise | Operator | Description | Example | |---|---|---| | `&` | Bitwise AND | `a & b` | | `\|` | Bitwise OR | `a \| b` | | `^` | Bitwise XOR | `a ^ b` | | `~` | Bitwise NOT (complement) | `~a` | | `<<` | Left shift | `a << 2` | | `>>` | Right shift | `a >> 2` | A shift's result has its left operand's type `T`, of width `W`. The count `n` may be any integer type; it is taken modulo the **register width** `R`, which is 32 for types up to 32 bits, 64 for 64-bit types and 128 for 128-bit types. A negative count counts as a large unsigned one, so `x << -1` is `x << (R - 1)`. | Operator | Result | |---|---| | `x << n` | `x` shifted left by `n mod R`, computed in `R` bits, truncated to `T` | | `x >> n`, unsigned `T` | logical (zero-filling) shift right by `n mod R` | | `x >> n`, signed `T` | arithmetic (sign-filling) shift right by `n mod R` | | `x <<= n`, `x >>= n` | the same, with `x` evaluated once | A type narrower than 32 bits shifts in 32 bits and then truncates, so a count from `W` up to 31 moves every bit out: ```kairo var b: u8 = 1 var n: i32 = 9 var x = b << n // 0: the bit left the byte var s: i8 = -127 var y = s >> n // -1: sign fill var m: i32 = 33 var z = 1i32 << m // 2: 33 mod 32 is 1 var w = b << m // 2 ``` Every type, value and count has exactly one result, on every target, at every optimization level and in `eval`. A shift count that is a constant must be below the width: `x << 8` on a `u8`, `y >> 32` on an `i32` and `y << -1` are compile errors. **Cost.** x86, AArch64 and RISC-V take a shift count modulo the register width in hardware, so the rule costs nothing there. 32-bit ARM shifts by the count's low byte instead and pays one instruction per shift whose count is not known to be in range (two on ARMv6-M / ARMv8-M Baseline, which must load the 31 first); in a loop the mask is hoisted and paid once per loop entry. A shift costs nothing on any target when its count is a constant, is masked by the program itself (`n & 31`, or `n % 32` on an unsigned `n`), or is the variable of a range loop that stays below the width (`for i in 0..32 { m |= x << i }`). `-Wshift-count-unproven` names every shift that pays for its mask on an ARM32 target. --- ## Assignment | Operator | Description | |---|---| | `=` | Assignment | | `+=`, `-=`, `*=`, `/=`, `%=` | Arithmetic compound assignment | | `&=`, `\|=`, `^=` | Bitwise compound assignment | | `<<=`, `>>=` | Shift compound assignment | On primitives, `x op= y` behaves like `x = x op y` with `x` evaluated once. For user-defined types, a compound assignment and its binary operator form one pair (`+=` with `+`, `<<=` with `<<`, and so on): a type declares `op +` **or** `op +=`, never both, and the other is derived from it. See [Compound assignment](/docs/language/operator-overloading/#compound-assignment). --- ## Increment and Decrement | Syntax | Name | Behavior | |---|---|---| | `++x` | Prefix increment | Increments `x`, returns the new value | | `x++` | Postfix increment | Returns the current value, then increments `x` | | `--x` | Prefix decrement | Decrements `x`, returns the new value | | `x--` | Postfix decrement | Returns the current value, then decrements `x` | Every operand is evaluated left to right (see [Evaluation Order](#evaluation-order)), so an expression that changes a variable more than once, such as `i = i++ + ++i`, has one defined result. It is still hard to read; prefer one change per statement. --- ## Ranges | Operator | Description | Example | |---|---|---| | `..` | Exclusive range (end excluded) | `0..10` -> 0 through 9 | | `..=` | Inclusive range (end included) | `0..=10` -> 0 through 10 | Range operators produce a `Range` object that implements iteration. Any type that satisfies the `Steppable` interface can be used with range operators: ```kairo interface Steppable { fn op l++ (self) -> Self // step forward (prefix increment) fn op == (self, other: T) -> bool } ``` > [!NOTE] > Types do not need to explicitly `impl Steppable`. If a type satisfies the required method signatures, it is automatically compatible with range operators. See [Interfaces](/docs/language/interfaces/) for details on structural conformance. Ranges also work with slicing on strings and collections: ```kairo "hello"[1..4] // "ell" [1, 2, 3, 4][0..2] // [1, 2] ``` --- ## Null-Safe Access Kairo provides null-safe operators for working with [nullable types](/docs/language/nullables/) (`T?`). | Operator | Description | Example | |---|---|---| | `?.` | Null-safe member access | `obj?.field` | | `?->` | Null-safe pointer deref + member access | `ptr?->field` | If the left-hand side is null, nothing on the right is evaluated and the entire expression is null. `x?.m` reads as `if x? => x.m else null`, and `x?.f(args)` the same: the call and its arguments run only when `x` is non-null. Nothing is constructed on the null path. The result type is the member's (or the call result's) type made nullable, `M?`, and stays `M?` when `M` is already nullable rather than becoming `(M?)?`. `?->` is the same over a nullable pointer, and a chain `a?.b?.c` applies each step to the previous step's result. ```kairo var user: User? = find_user("alice") var name? = user?.get_name() // string?: null if user is null; get_name() not called var city? = user?.address?.city // string?: null if user or address is null ``` `??` supplies the fallback for the null case. The result is `T`, or `T?` when the right side is itself nullable; it chains to the right: ```kairo var shown = user?.get_name() ?? "guest" // string ``` The non-null equivalents follow the same pattern without the safety check: | Operator | Description | |---|---| | `.` | Member access | | `->` | Pointer dereference + member access | --- ## Type Inspection | Keyword | Return type | Description | |---|---|---| | `sizeof T` | `usize` | Size of type `T` in bytes | | `alignof T` | `usize` | Alignment requirement of type `T` in bytes | | `typeof expr` | Context-dependent | Type identity see below | `typeof` has dual behavior depending on context: ```kairo var x = 42 var y: typeof x = 100 // type position compiler substitutes i32 var info = typeof x // expression position returns a TypeInfo struct info.get_pretty_name() // "i32" info.get_size() // 4 ``` See [Type System](/docs/language/type-system/) for full `TypeInfo` details. --- ## Type Casting `as` `as` performs explicit type conversion. No implicit narrowing conversions exist in Kairo all narrowing casts must use `as`. [Implicit widening](/docs/language/casting-implicit/#widening) (e.g., `i32` to `i64`) is permitted without `as`. ```kairo var x: i64 = 1000 var y: i8 = x as i8 // explicit narrowing may truncate var f: f64 = 3.14 var i: i32 = f as i32 // 3 truncates toward zero ``` `as` is overloadable for user-defined types: ```kairo class Vector2D { var x: f32 var y: f32 fn op as (self) -> string { return f"Vector2D({self.x}, {self.y})" } } var v = Vector2D { x: 1.0, y: 2.0 } var s = v as string // "Vector2D(1.0, 2.0)" ``` See [Casting](/docs/language/casting/) for the full conversion rules. --- ## Operator Overloading Operator overloading is covered in [Operator Overloading](/docs/language/operator-overloading/). --- ## Statement Expressions A statement expression runs a block of statements and yields the value of its last expression: ```kairo fn main() -> i32 { var x = 1 var y = ({ var t = x * 10 t + 2 }) return x + y // 13 } ``` The form is `({ statements... expression })`. Its value and type are those of the last expression. - The last statement must be an expression. A block that ends in `var`, an `if` statement or `return`, or an empty block, is an error. - Locals declared inside are scoped to the block and destroyed at its closing brace. - `return`, `break` and `continue` inside the block jump out of it as they would anywhere else; `return` returns from the enclosing function. - The expected type reaches the last expression: in `var b: u8 = ({ 5 })` the literal is a `u8`. - The value is a copy. A statement expression cannot yield a fixed-size array, since arrays are not copied implicitly. - Inside the block, a newline ends a statement as it does in any block. `({` always opens a statement expression. A set or map literal, or an anonymous initializer, is written without surrounding parentheses. This is the only place a block yields a value. The arms of an `if`, `match`, or `try` expression are single `=> expr` values, and no other block returns its last expression implicitly. A statement expression is how an arm holds several statements: `if ready => ({ var t = load(); (t.value); }) else => 0`. --- ## Precedence Operators are listed from highest precedence (tightest binding) to lowest. Operators on the same row have equal precedence and associate in the direction shown. | Precedence | Operators | Associativity | Description | |---|---|---|---| | 1 | Literals, names, `( )` grouping, `({ ... })`, `match` | | Primary expressions | | 2 | `::` | Left | Scope resolution | | 3 | `()` `[]` `.` `->` `?.` `?->` `?` (null test) | Left | Postfix / member access | | 4 | `++` `--` (postfix) | Left | Postfix increment/decrement | | 5 | `++` `--` (prefix) `!` `~` `+` `-` (unary) `*` `&` `sizeof` `alignof` `typeof` | Right | Prefix / unary | | 6 | `as` | Left | Type cast | | 7 | `^^` | Right | Exponentiation | | 8 | `*` `/` `%` | Left | Multiplicative | | 9 | `+` `-` | Left | Additive | | 10 | `<<` `>>` | Left | Bitwise shift | | 11 | `<` `<=` `>` `>=` `<=>` `in` | Left | Relational / three-way / containment | | 12 | `==` `!=` `===` | Left | Equality | | 13 | `&` | Left | Bitwise AND | | 14 | `^` | Left | Bitwise XOR | | 15 | `\|` | Left | Bitwise OR | | 16 | `&&` | Left | Logical AND | | 17 | `\|\|` | Left | Logical OR | | 18 | `..` `..=` | None | Range | | 19 | `??` | Right | Null coalescing | | 20 | `=` `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | Right | Assignment | | 21 | `if` / `try` expressions | | Value-form `if` and `try` | `if` and `try` expressions bind looser than every operator. Their last arm extends as far right as it can, so `x + if c => 1 else => 2 + 5` is `x + (if c => 1 else => (2 + 5))`. An `if` or `try` used as an operand produces a warning ([S078W](/docs/language/diagnostics/#s078w-if-or-try-expression-as-an-operators-operand)); parenthesize it: `x + (if c => 1 else => 2) + 5`. A [`match` expression](/docs/language/pattern-matching/#match-as-an-expression) closes with `}` and binds as a primary expression: `match k { ... } + 1` needs no parentheses. `=>` is punctuation, not an operator: it has no precedence and cannot be overloaded. It introduces the value of an arm in the value forms of `if`, `match`, and `try`. See [Control Flow](/docs/language/control-flow/#if-as-an-expression-ternary-equivalent). `as` binds looser than every prefix operator and tighter than every binary one: `-1 as u8` casts `-1`, `&x as *const T` casts the address, and `x as i64 + 1` is `(x as i64) + 1`. > [!NOTE] > `==` binds tighter than `&&` and `||` compound conditions like `a == b && c == d` do not require explicit parentheses. This matches C/C++ precedence. When in doubt, use parentheses. Apart from an `if` or `try` expression used as an operand, the compiler does not warn about precedence ambiguity, but explicit grouping improves readability. --- ## Evaluation Order Call arguments are evaluated **left to right**, and the receiver of a method call comes first. Given `f(a(), b())`, `a()` runs before `b()`; given `x.m(a())`, `x` is evaluated before `a()`. ```kairo fn g(@inout n: i32) -> i32 { n += 1; return n * 10 } var n = 0 f(g(&n), g(&n)) // always f(10, 20) ``` Named arguments follow the same rule: they run in the order written, not parameter order. Defaults for omitted arguments run after all explicit arguments, in parameter order. See [Functions](/docs/language/functions-parameters/#evaluation-order). `&&` and `||` are also left to right, with short-circuiting. See [Control Flow](/docs/language/control-flow/#short-circuit-evaluation). The same holds for every operator and every place: a binary operator's left operand runs before its right (`a() + b()` calls `a` first), a subscript's base before its index, and an initializer's fields in the order written. An assignment evaluates its target first, then the value, then stores: in `arr[i()] = v()`, `i()` runs before `v()`. A compound assignment evaluates its target once. This order is guaranteed, not an implementation detail. Code inside an imported C or C++ header (an inline function or a macro) keeps C++'s own rules. Keeping one side effect per statement is still easier to read. --- ## Operators Not in Kairo For C++ developers the following C++ operators have no equivalent in Kairo: | C++ Operator | Kairo Alternative | |---|---| | `? :` (ternary) | `if`/`else` expressions | | `,` (comma operator) | Not supported use separate statements | | `new` / `delete` | `@create T()` / `@destroy p` (through the allocator in effect), or `fn op finally` for a custom destructor; `@cxx::new` / `@cxx::delete` for memory shared with C++. C++'s `operator new` / `operator delete` cannot be overloaded: Kairo defines them for every class ([Allocators & Ownership](/docs/language/c-cpp-memory/#class-specific-operator-new-and-operator-delete)) | | `typeid` | `typeof expr` returns `TypeInfo` | | `const_cast` / `reinterpret_cast` / `static_cast` / `dynamic_cast` | `as` for safe casts; see [Casting](/docs/language/casting/) | --- ## See also - [Operator Overloading](/docs/language/operator-overloading/) - [Control Flow](/docs/language/control-flow/) - [Casting](/docs/language/casting/) - [Nullables](/docs/language/nullables/) - [Type System](/docs/language/type-system/) - [Primitives](/docs/language/primitives/) - [Pattern Matching](/docs/language/pattern-matching/) - [Interfaces](/docs/language/interfaces/) --- ## Control Flow URL: https://www.kairolang.org/docs/language/control-flow/ # Control Flow Kairo's control flow is block-scoped and brace-delimited. Every statement-form branch, loop, and error-handling construct uses `{ ... }` there are no single-statement bodies. The value forms of `if`, `match`, and `try` write each arm as `=> expr` instead. Conditions are bare expressions (no parentheses required, though permitted for clarity). `=>` introduces exactly one value; `{ }` after a control keyword is always a statement block. ## In this section - [Pattern Matching](/docs/language/pattern-matching/): `match`, guards, destructuring, ranges, and exhaustiveness. --- ## Conditionals ### `if` / `else if` / `else` ```kairo if x > 0 { std::io::println("positive") } else if x == 0 { std::io::println("zero") } else { std::io::println("negative") } ``` Braces are mandatory on all branches. The condition must evaluate to [`bool`](/docs/language/primitives/#bool) no implicit conversion from integers or pointers. ### `if` as an expression (ternary equivalent) Kairo has no ternary `? :` operator. Use `if` as an expression instead: ```kairo var x = if condition => 10 else => 20 var z = if a == b => 2 else if b > 2 => 1 else => 0 ``` The form is `if cond => value else if cond => value else => value`. Every arm is one expression, and the final `else` is mandatory. All arms must produce the same type. #### Arms are expressions, not blocks A braced arm is an error ([S073E](/docs/language/diagnostics/#s073e-braced-value-arm-in-an-if-try-or-match-expression)), and the compiler offers a fix-it. An arm needs a value: `=>` with nothing after it is an error. For several statements, use a [statement expression](/docs/language/operators/#statement-expressions): ```kairo var v = if ready => ({ var t = load(); t.normalize(); (t.value); }) else => 0 ``` #### How far an arm extends The last arm takes everything to its right that is part of the same expression: ```kairo var z = if c => 1 else => 0 + 5 // else => (0 + 5) ``` An arm stops at `,`, `)`, `]`, `}`, and the end of the line, so call arguments work without parentheses: ```kairo draw(if wide => 80 else => 40, height) ``` Using an `if` as the operand of an operator is legal, but it produces a warning ([S078W](/docs/language/diagnostics/#s078w-if-or-try-expression-as-an-operators-operand)). Parenthesize it: ```kairo var w = base + (if wide => 80 else => 40) ``` #### Line breaks You may break before or after `=>`, and before `else`: ```kairo var z = if a == b => 2 else if b > 2 => 1 else => 0 ``` Inside an arm the ordinary rule applies: break after an operator, not before it. #### Nesting A nested `if` in any arm except the last must be in parentheses, and so must an `if` used as a condition. Otherwise it is a compile error ([S077E](/docs/language/diagnostics/#s077e-nested-if-or-try-expression-must-be-parenthesized)), and the compiler offers a fix-it. A nested `if` in the final `else` arm is allowed, but write it as `else if`: `else => if` produces a warning ([S079W](/docs/language/diagnostics/#s079w--between-else-and-if-is-redundant)). ```kairo var r = if a => (if b => 1 else => 2) else => 3 // ok var r = if a => if b => 1 else => 2 else => 3 // error: parenthesize the inner if ``` #### In statement position A value-form `if` in statement position is an ordinary expression statement. Its value is discarded: ```kairo if verbose => log_full(e) else => log_short(e) ``` > [!TIP] > The compiler warns if `else if` nesting exceeds 3 levels. Consider restructuring deeply nested conditionals into a `match` or separate function. ### Empty branches Empty branches are legal in statement form. The compiler will not warn this is intentional for cases where only one side of a conditional has work to do: ```kairo if condition { // intentionally empty } else { handle_false_case() } ``` --- ## `match` `match` is covered in [Pattern Matching](/docs/language/pattern-matching/). --- ## Loops ### `for` range and iterator Range-based and iterator-based `for` loops use the `in` keyword: ```kairo for i in 0..10 { // i = 0, 1, 2, ..., 9 } for i in 0..=10 { // i = 0, 1, 2, ..., 10 } for item in collection { // iterates using the collection's fn op in (self) -> yield T } ``` The range operators `..` and `..=` produce a `Range` object that implements the iterator protocol. Any type that defines `fn op in (self) -> yield T` is iterable. Defining `begin()` and `end()` on a Kairo class does not make it iterable. See [Operators](/docs/language/operators/#ranges) for the `Steppable` interface and [Operators](/docs/language/operator-overloading/#special-operators) for the `op in` overload. A `const` iterable uses `op in (const self)`; a type whose `op in` takes `self` cannot be iterated through a const value (SC063E). A plain binder is a copy of each element. Binding an element type that cannot be copied is SC182E; bind `*x` for the element's address. An [imported C++ class](/docs/language/c-cpp-calling/) iterates the way a C++ range-based `for` does: through its member `begin()` and `end()`, or else through free `begin()` and `end()` functions found by argument-dependent lookup. ### Multi-variable iteration If the collection yields [tuples](/docs/language/collections/#tuples-t1-t2-), [destructure](/docs/language/variables/#destructuring) directly in the loop header: ```kairo for (key, value) in some_map { std::io::println(f"{key} = {value}") } for (a, b) in pairs { // a and b are the first and second elements of each yielded tuple } ``` The tuple arity in the loop header must match the arity yielded by the collection. ### `for` C-style Traditional three-part `for` loops are also supported: ```kairo for var i = 0; i < 10; i++ { // classic index loop } ``` The init clause declares a new variable scoped to the loop body. The condition and step are bare expressions. The init clause may be empty, to loop over a variable declared before the loop: ```kairo var i = 0 for ; i < 10; i += 1 { if i == 3 { continue } // the step still runs // ... } ``` Unlike the equivalent `while` loop, `continue` in a C-style `for` still runs the step. ### `while` ```kairo while condition { // loop body } ``` The condition is evaluated before each iteration. No implicit conversion from integers must be `bool`. ### `loop` `loop` is an unconditional infinite loop. It runs until an explicit `break` or `return`: ```kairo loop { var input = read_line() if input == "quit" { break } process(input) } ``` ### Labeled loops Labels allow `break` and `continue` to target a specific enclosing loop. The syntax is `label: for`/`while`/`loop`: ```kairo outer: for i in 0..10 { inner: for j in 0..10 { if some_condition { break outer // exits the outer loop entirely } if other_condition { continue inner // skips to next iteration of the inner loop } } } ``` Labels follow the same [naming conventions](/docs/language/variables/#naming-conventions) as variables (`snake_case`). `break` and `continue` without a label target the innermost enclosing loop. --- ## `break` and `continue` | Statement | Behavior | |---|---| | `break` | Exits the innermost loop | | `break label` | Exits the loop identified by `label` | | `continue` | Skips to the next iteration of the innermost loop | | `continue label` | Skips to the next iteration of the loop identified by `label` | `break` and `continue` are statements, not expressions they do not produce values. Inside a `match` nested within a loop, `break` exits the **loop**, not the match (match cases are already isolated blocks with no fall-through by default). --- ## Error Handling ### `try` / `catch` `try`/`catch` handles panics from functions annotated with the `panic` specifier. The compiler statically verifies that `catch` blocks cover all panic types that can propagate from the `try` body uncovered types are a compile error. See [Panic](/docs/language/panic/) for the full panic model. ```kairo try { risky_operation() } catch { // catch-all any panic type std::io::println("something went wrong") } ``` Catch blocks can filter by specific error types. An error type is any movable type; it may define [`op panic`](/docs/language/operator-overloading/#op-panic) to give itself a message. The compiler checks exhaustiveness against the panic sets of the called functions: ```kairo struct IOError { var path: string fn op panic (const self) -> string { return f"cannot read {self.path}" } } struct ParseError { var line: i32 fn op panic (const self) -> string { return f"parse error on line {self.line}" } } fn load_data(path: string) panic(IOError, ParseError) -> Data { /* ... */ } try { load_data("data.txt") } catch e: IOError { std::io::println(f"IO error: cannot read {e.path}") } catch e: ParseError { std::io::println(f"parse error on line {e.line}") } ``` A bare `catch` (no type) acts as a catch-all and satisfies exhaustiveness for any remaining types. Each typed arm catches exactly its type, with no subtyping between error types; an arm for a type the body cannot panic with is a warning. See [Panic](/docs/language/panic/#arms-match-exact-types). ### `try`/`catch` as an expression ```kairo var n = try parse(s) catch e: ParseError => -1 catch => 0 ``` The form is `try operand catch ... => value`. There is no arrow after `try` itself; the operand runs until the first `catch`. Every catch arm takes one of these forms: ```kairo var a = try f() catch => v // catch-all var b = try f() catch e => v // catch-all, binds e var c = try f() catch var e => v // binds e as var var d = try f() catch const e => v // binds e as const var g = try f() catch e: ParseError => v // only ParseError ``` A bare name after `catch` is a binding, not a type: `catch ParseError => v` binds a variable named `ParseError`. Filter by type with `catch e: T`. At least one arm is required, and a default arm must be last. All arms must produce the same type. `finally` is not permitted in expression form. Each `catch` may start a new line: ```kairo var n = try parse(s) catch e: ParseError => -1 catch => 0 ``` A bare `try {` always begins a statement-form `try`. To `try` several statements as a value, use a statement expression: `try ({ ...; (value); }) catch => ...`. A `try` inside another `try`'s operand or arms must be parenthesized. Without the parentheses, the inner `try` would take every following `catch`: ```kairo var n = try (try f() catch => 1) catch => 2 ``` The last arm of a `try` extends as far right as it can, like the last arm of an `if`. See [How far an arm extends](#how-far-an-arm-extends). ### `finally` `finally` is a scope-exit block, described below. It is not a clause of `try`: a `finally` written after a `try`/`catch` is the same standalone `finally`, so it runs when the enclosing block is left, not when the `try` finishes, and a `return`, `break` or uncaught panic leaving the `try` never reaches it. ```kairo fn work() { try { do_work() } catch e: IOError { handle_error(e) } finally { // warning: runs when work() returns release_resource() } log("done") // runs before release_resource() } ``` A `finally` directly after a `try`/`catch` is a [warning](/docs/language/diagnostics/#sc001w-finally-runs-when-the-enclosing-block-exits-like-any-finally-not-when-the-try-before-it-finishes) for that reason. To clean up as soon as the `try` is done, on every way out of it, register the `finally` first, in a block of its own: `{ finally { release_resource() } try { ... } catch { ... } }`. ### Standalone `finally` (scope exit) `finally` can also appear without a preceding `try`. In this form it is a scope-exit block: its body runs when control leaves the enclosing scope, however it leaves: ```kairo fn process_file(path: string) panic -> void { var fd = open(path) finally { close(fd) // runs on normal return, panic, or early return } // ... work with fd ... if bad_data { return // finally still runs } // ... more work ... } ``` A standalone `finally` behaves like the [destructor](/docs/language/classes-lifecycle/#destructors---op-finally) (`fn op finally(self)`) of a local declared at the same point (the compiler lowers it to exactly that): - **It is tied to the enclosing block, not the function.** A `finally` inside an `if` body or a loop body runs when that block ends. In a loop it runs at the end of every iteration that reached it. - **It only runs if execution reached it.** A `return` or panic before the `finally` statement skips it, just as a local that was never declared is never destroyed. - **It runs on every exit from the scope.** That includes falling off the end, `return`, `break`, `continue`, and a panic leaving the scope. - **It runs in reverse order with everything else in the scope.** Multiple `finally` blocks and local destructors run in reverse declaration order (LIFO), so a `finally` written after a local runs before that local is destroyed. ```kairo fn copy_all(paths: [string]) { for path in paths { var fd = open(path) finally { close(fd) // runs at the end of each iteration, not when copy_all returns } copy(fd) } } ``` This differs from Go's `defer`, which always waits for the function to return. --- ## `assert` `assert` checks a condition. It takes an expression and an optional diagnostic message: ```kairo assert index < len, "index out of bounds" assert count > 0 ``` What an assert does depends on the build: | Build | Behavior | |---|---| | Debug | The condition is evaluated. If it is false, the program aborts with the message or a generated diagnostic | | Release | Asserts are removed. The condition is not evaluated | Because a release build drops the condition entirely, don't put side effects the program depends on inside an `assert`. The `-fassert-mode` compiler flag replaces the default failure behavior: | Mode | Behavior | |---|---| | `crash` | Crashes with the provided message or a generated diagnostic: prints it with the source location and terminates, like [`crash!()`](/docs/language/panic/#main-and-crash). A failed assert is never a [panic](/docs/language/panic/): it joins no panic set and cannot be caught | | `return` | Returns a default-constructed value of the function's return type | | `log` | Logs the assertion failure and continues execution | > [!WARNING] > `return` mode silently swallows assertion failures and produces a default-constructed value. This can mask bugs and produce incorrect results downstream. Asserts cannot appear at file scope they are only valid inside function bodies. --- ## `panic` `panic` is a statement that raises an error from the current function: the function returns the error to its caller instead of a value. Functions that can panic must be annotated with the `panic` specifier in their signature, and the compiler enforces that callers handle the panic via `try`/`catch` or propagate it. The value panicked can be of any movable type (see [Error Types](/docs/language/panic/#error-types)). ```kairo struct DivideByZero { fn op panic (const self) -> string { return "division by zero" } } fn divide(a: i32, b: i32) panic -> i32 { if b == 0 { panic DivideByZero {} } return a / b } ``` A panic never stops the program: an error can't reach `main` unhandled. To stop the program, use `crash!()`. See [Panic](/docs/language/panic/) for the full panic model, including panic sets, `main` and `crash!`, and the zero-cost codegen strategy. --- ## `return` `return` exits the current function with a value. If the function returns `void`, `return` takes no operand. ```kairo fn max(a: i32, b: i32) -> i32 { return if a > b => a else => b } ``` A statement written after a `return` in the same block (or after a `break`, `continue`, `panic` or `jump!`) can never run, and the compiler warns about it ([SC003W](/docs/language/diagnostics/#sc003w-unreachable-code)). A `return` inside a closure ends only the closure. ## Blocks and Scope A block is a brace-delimited sequence of statements. Every block introduces a new lexical scope variables declared inside are not visible outside, and [destructors run at the closing brace](/docs/language/ownership/#destruction-order) in reverse declaration order. ```kairo { var x = 42 var y = compute(x) // x and y are live here } // x and y are destroyed and no longer accessible ``` A plain block does not produce a value. To compute a value with statements, use a [statement expression](/docs/language/operators/#statement-expressions), whose value is its last expression: ```kairo var result = ({ var tmp = expensive_computation() tmp * 2 // result = tmp * 2 }) ``` A branch of an `if` or `match` expression that needs statements can use one too. Anonymous blocks are useful for limiting the lifetime of temporary resources without introducing a function: ```kairo fn process() { var config = load_config() { var lock = acquire_mutex() // critical section write_shared_state(config) } // lock is destroyed here mutex released do_unrelated_work() } ``` All control flow constructs (`if`, `match`, `for`, `while`, `loop`, `try`) create implicit blocks their bodies follow the same scoping and destruction rules. See [Variables](/docs/language/variables/#scope-and-lifetime) and [Tether](/docs/language/tether/) for full lifetime semantics. --- ## Jumps For low-level control flow (state machines, interpreters, hot loops), Kairo provides labeled jumps via [compiler intrinsics](/docs/language/macros-builtin/#compiler-intrinsic-macros): ```kairo label!(entry) // ... code ... jump!(entry) // unconditional jump to 'entry' ``` `jump!` can only target labels within the same function cross-function jumps are a compile error. Labels declared with `label!` are not the same as loop labels; they are raw branch targets with no structured control flow guarantees. > [!CAUTION] > `jump!` bypasses destructors and `finally` blocks. Jumping over a variable's declaration and then referencing it is undefined behavior. Use structured control flow (`loop`, `break`, `return`) unless you have a concrete reason not to. Kairo does not have a `goto` keyword. `label!` and `jump!` are compiler intrinsics surfaced with macro syntax to make jump usage explicit and greppable in a codebase. They are not user-defined macros see [Macros](/docs/language/macros/) for the macro system. --- ## Compile-Time Branching `eval if` selects a branch at compile time. The condition must be a compile-time constant expression if it is not, the compiler emits an error. Only the selected branch is included in the final program; the other branches are discarded entirely (no codegen, no type-checking). ```kairo eval if defined!(__linux__) { fn init() { /* linux-specific init */ } } else if defined!(_WIN32) { fn init() { /* windows-specific init */ } } else { fn init() { /* fallback */ } } ``` This is equivalent to `#if` / `#elif` / `#else` in C/C++, but operates on Kairo's compile-time evaluation system rather than a preprocessor. See [Eval](/docs/language/eval/) for details on what qualifies as a compile-time constant. --- ## Branch Hints Kairo provides [attributes](/docs/language/attributes/#branch-hints) to communicate branch likelihood to the compiler's optimizer. These map directly to LLVM's branch weight metadata and `__builtin_expect` semantics in the generated code. ```kairo @likely if hot_path { fast_operation() } else { slow_fallback() } @unlikely if rare_error { handle_error() } ``` | Attribute | Meaning | |---|---| | `@likely` | The condition is expected to be true in the common case | | `@unlikely` | The condition is expected to be false in the common case | | `@unreachable` | The branch should never execute if it does, behavior is undefined | ### Hints on `else` and `else if` The hint on the first `if` goes in front of it. A hint for a later branch goes in front of the `else` that opens it: each one is for the branch it precedes. ```kairo @likely if a { ... } @unlikely else if b { ... } @unlikely else { ... } ``` `@unlikely else if b` is the hint for the `else if` branch; `@unlikely else` is the hint for the final block. A newline may separate the `}` from the attribute, so this is the same chain: ```kairo @likely if a { ... } @unlikely else if b { ... } @unlikely else { ... } ``` Only `@likely` and `@unlikely` may precede `else`; any other attribute there is an error. An attribute that is not followed by `else` is not taken: it belongs to the next statement. ### `@assume` `@assume(cond)` tells the optimizer that `cond` is true at that point, so it can drop checks and pick better code for everything after. It is a statement of its own, alone on its line (a trailing `;` is fine), and attaches to nothing. ```kairo fn sum(xs: *i32, n: usize) -> i32 { @assume(n > 0) // the loop below runs at least once var total = 0 for var i: usize = 0; i < n; ++i { total += xs[i] } return total } ``` `@assume(x > y) foo()` on one line is an error, with a fix-it that puts `foo()` on its own line: the attribute form would suggest the assumption applies to `foo()`, and it does not. The condition must be a `bool`, and `@assume` takes exactly one. A false assumption is undefined behavior. The compiler does not check it and may build code that is wrong for every input that breaks it; use [`assert`](/docs/language/control-flow/) when you want a check that is verified at run time. `@unreachable` is a hard assertion to the optimizer that the marked branch is dead code. If execution reaches an `@unreachable` branch at runtime, the behavior is undefined the compiler is free to eliminate the branch entirely and may miscompile surrounding code under that assumption. ```kairo match direction { case .North { /* ... */ } case .South { /* ... */ } case .East { /* ... */ } case .West { /* ... */ } @unreachable default { // optimizer assumes this is dead code } } ``` Branch hints cannot be applied to `eval if` branches compile-time branches are resolved before codegen and have no runtime cost to optimize. --- ## The Never Type Functions that never return (they crash, loop forever, or call a noreturn function) use `!` as their return type. A `-> !` function cannot be [`panic`](/docs/language/panic/#panic-and-no-return-): ```kairo fn fatal(msg: string) -> ! { std::io::println(msg) crash!() } fn event_loop() -> ! { loop { process_events() } } ``` `!` is the **never type**. It is a subtype of every type, meaning it can appear anywhere a value is expected. This makes it valid in expression contexts: ```kairo var x: i32 = if valid => compute() else => fatal("invalid state") // fatal() returns ! which coerces to i32 ``` Because a call to a `-> !` function never comes back, a statement after it in the same block is unreachable, and the compiler warns ([SC003W](/docs/language/diagnostics/#sc003w-unreachable-code)). The same holds after an `if` whose every branch leaves, an exhaustive `match` whose every arm leaves, and a `loop` or `while true` that no `break` exits. See [Functions](/docs/language/functions/) for return type syntax and [Type System](/docs/language/type-system/) for how `!` interacts with type inference. --- ## `return` `return` exits the current function with a value. See [Functions](/docs/language/functions/) for full details on return types, `void` returns, and expression-bodied functions. --- ## Short-Circuit Evaluation `&&` and `||` are guaranteed left-to-right with short-circuit evaluation. The right operand is not evaluated if the left operand determines the result: ```kairo if ptr != null && *ptr == 42 { // safe: *ptr is only evaluated if ptr (a *i32?) is non-null, so ptr is narrowed there } ``` This is identical to C/C++ behavior and is guaranteed by the language specification, not an optimizer artifact. --- ## Control Flow Not in Kairo For C++ developers the following C++ constructs have no equivalent in Kairo: | C++ Construct | Kairo Alternative | |---|---| | `? :` (ternary) | `if`/`else` expressions | | `goto` | `label!` / `jump!` intrinsics | | `do { ... } while` | `loop` with a conditional `break` at the end | | `switch` fall-through | `match` but [no fall-through](/docs/language/pattern-matching/#no-fall-through) | | `throw` / C++ exceptions | `panic` / `try`/`catch` (see [Panic](/docs/language/panic/)) | | `#if` / `#ifdef` | `eval if` (see [Eval](/docs/language/eval/)) | | `constexpr` / `consteval` | `eval` functions / vars (see [Eval](/docs/language/eval/)) | ## See also - [Pattern Matching](/docs/language/pattern-matching/) - [Operators](/docs/language/operators/) - [Panic](/docs/language/panic/) - [Eval](/docs/language/eval/) - [Functions](/docs/language/functions/) - [Variables](/docs/language/variables/#scope-and-lifetime) - [Attributes](/docs/language/attributes/#branch-hints) `for *x` over a generator binds a pointer to const unless the generator yields a mutable place, so a write through `x` that would land in a copy is an error (SC071E). --- ## Functions URL: https://www.kairolang.org/docs/language/functions/ # Functions Functions in Kairo follow a consistent declaration syntax for both free functions and class methods. The full grammar covers visibility, ABI linkage, generics, modifiers, bounds, and return types all optional except the `fn` keyword, the name, and the parameter list. ## In this section - [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Function Overloading](/docs/language/functions-overloading/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/): modifiers, visibility, ABI and linkage, forward declarations --- ## Declaration Syntax ```kairo fn name(param1: Type1, param2: Type2) -> ReturnType { // body } ``` The full grammar: ```bnf function_declaration ::= visibility? abi_mod? leading_mods? "fn" generics? identifier "(" parameter_list? ")" function_mods? ("->" return_type)? constraint? body visibility ::= "pub" | "priv" | "prot" abi_mod ::= ("ffi" string_literal) | "static" | "virtual" | "override" leading_mods ::= ("inline" | "eval")* ; same meaning as in function_mods generics ::= "<" generic_param_list ">" function_mods ::= ("const" | "volatile" | "unsafe" | "eval" | "async" | "final" | "panic" | "inline")* constraint ::= "requires" expression return_type ::= type | "!" body ::= block | "=" expression | ε ; ε = forward declaration ``` All parts except `fn`, the name, and the parenthesized parameter list are optional. When the return type is omitted, it defaults to `void`. --- ## Parameters Parameters are declared as `name: Type`. Each parameter requires an explicit type annotation there is no parameter type inference. ```kairo fn greet(name: string, loud: bool) { if loud { std::io::println(f"HELLO, {name}!") } else { std::io::println(f"Hello, {name}.") } } ``` Default parameters, named arguments, and variadic functions are covered in [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/). Parameter passing modes are covered in [Parameter Passing Modes](/docs/language/functions-parameter-modes/#parameter-passing-modes). --- ## Return Types ### Explicit return ```kairo fn add(a: i32, b: i32) -> i32 { return a + b } ``` ### Implicit `void` When no return type is specified, the function returns `void`: ```kairo fn log(msg: string) { std::io::println(msg) } fn log_explicit(msg: string) -> void { // equivalent std::io::println(msg) } ``` ### Arrays are not returned A function cannot return a fixed array `[T; N]` by value. Return a vector `[T]`, or fill an [`@inout` parameter](/docs/language/functions-parameter-modes/): ```kairo fn make() -> [i32; 3] { ... } // compile error: 'make' returns an array fn make() -> [i32] { return [1, 2, 3] } // ok: the caller owns a vector fn make(@inout out: [i32; 3]) { // ok: the caller owns the array out[0] = 1; out[1] = 2; out[2] = 3 } ``` Returning a slice literal is also an error, because the literal's storage ends with the function. See [Primitives](/docs/language/collections/#how-long-a-slice-literals-storage-lives). ### No-return `!` Functions that never return (they crash, loop forever, or call a no-return function) use `!` as their return type: ```kairo fn fatal(msg: string) -> ! { std::io::println(f"Fatal: {msg}") crash!() } fn event_loop() -> ! { loop { process_events() } } ``` `!` is the **[no-return type](/docs/language/type-system/#the-never-type-)**. It is a subtype of every type, meaning it can appear anywhere a value is expected: ```kairo var x: i32 = if valid => compute() else => fatal("bad state") // fatal() returns ! which coerces to i32 ``` > [!WARNING] > No-return functions cannot have a [`panic` specifier](/docs/language/panic/#the-panic-specifier). Since `panic` acts as an alternative return path, it contradicts the guarantee that the function never returns. The compiler rejects `fn f() panic -> !`. Special return types and generators are covered in [Generators](/docs/language/functions-generators/). --- ## Expression-Bodied Functions Single-expression functions can use the `=` shorthand, omitting braces and `return`: ```kairo fn add(a: i32, b: i32) -> i32 = a + b fn square(x: f64) -> f64 = x * x fn greeting(name: string) -> string = f"Hello, {name}!" ``` The return type annotation is optional for expression-bodied functions it is inferred from the expression when omitted. This is the only form of [return type inference](/docs/language/type-system/#return-type-inference) in Kairo; block-bodied functions always require an explicit return type (or default to `void`). ```kairo fn add(a: i32, b: i32) = a + b // inferred as i32 fn greeting(name: string) = f"Hi, {name}!" // inferred as string ``` Explicit annotations are still useful when you want to constrain or widen the inferred type: ```kairo fn promote(x: i32) -> i64 = x as i64 // would otherwise infer i32 ``` --- ## Function Return `return` exits the current function with a value. For `void` functions, `return` takes no operand. ```kairo fn max(a: i32, b: i32) -> i32 { if a > b { return a } return b } fn log(msg: string) { std::io::println(msg) return // explicit return from void function valid but optional } ``` Early returns are permitted anywhere in a function body. The compiler verifies that all code paths return a value of the declared return type. --- Function overloading is covered in [Function Overloading](/docs/language/functions-overloading/). --- ## Generic Functions Generic functions declare [type parameters](/docs/language/generics/) in angle brackets before the function name: ```kairo fn identity(x: T) -> T { return x } ``` Constrain type parameters with `impl` (interface conformance) or `derives` (class inheritance): ```kairo fn max(a: T, b: T) -> T { return if a > b => a else => b } fn serialize(value: T) -> [byte] { return value.to_bytes() } ``` > [!NOTE] > `impl` checks structural conformance the type satisfies the interface's required method signatures without needing an explicit `impl` declaration. `derives` checks polymorphic inheritance the type is a subclass of the specified class. See [Interfaces](/docs/language/interfaces/) and [Requires Clauses](/docs/language/requires/) for details. ### Requires Clauses For constraints beyond type parameter bounds, attach a `requires` clause after the return type: ```kairo fn print_value(value: T) requires sizeof T <= 64 { std::io::println(value as string) } ``` `requires` is a compile-time gate: the condition must hold at compile time or the program does not compile. There is no runtime fallback and no dispatch. See [Requires Clauses](/docs/language/requires/) for the full constraint system and [Where Clauses](/docs/language/where/) for runtime-conditional overload dispatch. --- Function modifiers, visibility, ABI and linkage, and forward declarations are covered in [Function Declarations](/docs/language/functions-declarations/). --- ## Function Pointers Functions are first-class values. The type of a [function pointer](/docs/language/pointers/#function-pointers) is `fn(ParamTypes) -> ReturnType`: ```kairo fn add(a: i32, b: i32) -> i32 = a + b fn sub(a: i32, b: i32) -> i32 = a - b var f: fn(i32, i32) -> i32 = add f(3, 4) // 7 f = sub f(10, 3) // 7 ``` A `fn(...)` value holds a function or a [closure](/docs/language/closures/), including one that captures variables. Where only a plain function pointer will do (a C callback, a table of functions called often), write the raw type `unsafe fn(ParamTypes) -> ReturnType`. It is one machine word and is called directly, and a named function or a closure that captures nothing converts to it. A raw pointer converts to a `fn(...)` value, but a `fn(...)` value does not convert back. See [Function Types](/docs/language/type-system/#function-types). ```kairo struct Handlers { var on_alloc: unsafe fn(usize, usize) -> unsafe *u8 } ``` A function type for a function that may [panic](/docs/language/panic/) must declare its panic set: `fn(string) panic(IOError) -> i32`, not a bare `panic`, since a type has no body to infer the set from. A function converts to such a type when its own set is a subset of the declared one; a function that doesn't panic converts to any panicking function type. See [Declared Panic Sets](/docs/language/panic/#declared-panic-sets). Functions can be nested [inner functions](/docs/language/closures/#closures-vs-inner-functions) are scoped to the enclosing function: ```kairo fn outer(x: i32) -> i32 { fn inner(y: i32) -> i32 = y * 2 return inner(x) + 1 } ``` --- ## Closures Anonymous functions (lambdas) capture variables from the enclosing scope. Default capture is by copy; use `|*|` to capture by pointer or specify per-variable: ```kairo var multiplier = 3 var scale = fn (x: i32) -> i32 { return x * multiplier } // captures multiplier by copy scale(10) // 30 ``` See [Closures](/docs/language/closures/) for capture modes (`|*|`, `|a, *b|`), lifetime rules, and how closures interact with [Tether](/docs/language/tether/). --- ## Operator Functions Operators are overloaded with the `fn op` syntax: ```kairo class Vec2 { var x: f64 var y: f64 fn op +(self, other: Vec2) -> Vec2 { return Vec2 { x: self.x + other.x, y: self.y + other.y } } } ``` See [Operators](/docs/language/operator-overloading/) for the full list of overloadable operators, special operator syntax (`l++`/`r++`, `op as`, `op in`, `op finally`), and restrictions. --- --- ## Summary ```kairo // Basic function fn add(a: i32, b: i32) -> i32 = a + b // Default parameters + named arguments fn connect(host: string = "localhost", port: i32 = 8080) { /* ... */ } connect(port: 9090) // Parameter modes fn append(@inout s: string, t: string) { s += t } append(&name, "!") fn sink(@move s: string) { /* ... */ } // Generic with bounds fn show(value: T) { std::io::println(value as string) } // Variadic fn <...T> log(...args: T) { /* ... */ } // Overloaded fn process(x: i32) -> i32 { /* ... */ } fn process(x: string) -> string { /* ... */ } // Unsafe overload fn process(x: i32) unsafe -> i32 { /* ... */ } // Method with modifiers class Server { pub fn start(self) async panic { /* ... */ } // `async` with `panic`: not supported yet (SC116E) pub fn status(const self) -> string { /* ... */ } pub static fn default_port() -> i32 = 8080 } // Function pointer var handler: fn(Request) -> Response = handle_request // No-return fn abort() -> ! { crash!() } ``` ## See also - [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Function Overloading](/docs/language/functions-overloading/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/) - [Closures](/docs/language/closures/) - [Generics](/docs/language/generics/) - [Operator Overloading](/docs/language/operator-overloading/) --- ## Closures URL: https://www.kairolang.org/docs/language/closures/ # Closures A closure is an anonymous function that captures variables from its enclosing scope. In Kairo, lambdas and closures use the same syntax, the only distinction is whether the function captures anything. If it does, it's a closure. If it doesn't, it's a plain lambda. --- ## Basic Syntax Anonymous functions are declared with `fn` followed by a parameter list, an optional return type, and a body. The body can be a block `{ ... }` or a single expression after `=`. The return type is inferred when omitted. ```kairo var add = fn (a: i32, b: i32) -> i32 { return a + b } var twice = fn (x: i32) -> i32 = x * 2 add(3, 4) // 7 twice(10) // 20 ``` Closures have the same type as [function pointers](/docs/language/functions/#function-pointers) `fn(ParamTypes) -> ReturnType`. There is no separate closure type. The one exception is the raw function pointer `unsafe fn(ParamTypes) -> ReturnType` (a plain C function pointer): a closure that captures nothing converts to it, and a closure that captures does not, since it has no function pointer to give. See [Function Types](/docs/language/type-system/#function-types). ```kairo var opr: fn(i32, i32) -> i32 = fn (a: i32, b: i32) -> i32 { return a + b } ``` --- ## Capture Modes By default, closures [capture variables](/docs/language/ownership/#closure-captures) **by copy**. The closure receives its own copy of each captured variable, mutations inside the closure do not affect the original. In a script, a closure written in the top-level code captures the script's top-level variables by copy too; a function of the script reads the variable itself. A closure nested in such a closure sees the outer closure's copy: an inner `|*|` points at the copy, not the script's variable. ```kairo var x = 10 var add_x = fn (y: i32) -> i32 { return y + x // x is captured by copy } x = 999 add_x(5) // 15, uses the copied value of x (10), not 999 ``` ### Capture by Pointer `|*|` To capture all variables by pointer, append `|*|` after the parameter list. The closure can read and modify the original variables through explicit dereference: ```kairo var count = 0 var increment = fn ()|*| { *count += 1 // modifies the original count } increment() increment() count // 2 ``` ### Const Pointer Capture To capture variables by const pointer, use `|const *name, ...|` in the capture list. The closure can read but not modify the originals: ```kairo var x = 10 var y = 20 var z = 30 var closure = fn (a: i32)|const *x, const *y, const *z| -> i32 { return a + *x + *y + *z // can read but not modify } ``` ### Mixed Capture `|a, *b|` Specify capture mode per variable. Unqualified names are captured by copy, `*`-prefixed names by pointer: ```kairo var a = 10 var b = 20 var closure = fn (x: i32)|a, *b| -> i32 { *b += 1 // modifies the original b return x + a + *b // a is a copy, b is a pointer } closure(5) // 5 + 10 + 21 = 36 a // still 10 b // 21 ``` ### Empty Capture List `||` An explicit empty capture list prevents the default capture-by-copy behavior. The closure captures nothing, any reference to an outer variable is a compile error: ```kairo var x = 10 var no_capture = fn ()|| -> i32 { return 42 // ok, no outer variables referenced } // var bad = fn ()|| -> i32 { // return x // compile error: x is not captured // } ``` ### Capture Summary | Syntax | Behavior | |---|---| | *(none)* | All captures by copy (default) | | `\|\|` | No captures allowed | | `\|*\|` | All captures by pointer | | `\|a, b\|` | Named variables captured by copy | | `\|*a, *b\|` | Named variables captured by pointer | | `\|const *a, const *b\|` | Named variables captured by const pointer | | `\|a, *b\|` | Mixed, `a` by copy, `b` by pointer | --- ## Default Parameters Closures support [default parameter values](/docs/language/functions-parameters/#default-parameters), matching the behavior of regular functions: ```kairo var greet = fn (name: string = "world") { std::io::println(f"Hello, {name}!") } greet() // "Hello, world!" greet("Alice") // "Hello, Alice!" ``` --- ## Generic Closures Closures can be [generic](/docs/language/generics/), declaring type parameters before the parameter list: ```kairo var identity = fn (x: T) -> T { return x } identity(42) // i32 identity("hello") // string ``` --- ## Modifiers Closures support the `panic`, `volatile`, and `async` [modifiers](/docs/language/functions-declarations/#function-modifiers). Modifiers appear after the capture list (if present) and before the return type. Order between modifiers does not matter. A closure can also use `-> !` to indicate it [never returns](/docs/language/functions/#no-return-). A panicking closure must **declare its panic set**, `panic(E1, E2)`: a bare `panic` on a closure is an error whose fix-it writes the set inferred from the body. The set is then visible where the closure is written, and it matches the [function type](/docs/language/functions/#function-pointers) the closure is stored in, which needs a declared set too. ```kairo struct Failed { fn op panic (const self) -> string { return "failed" } } var risky = fn () panic(Failed) -> i32 { if bad_condition { panic Failed {} } return 42 } var side_effect = fn () volatile {} var background = fn () async {} var all_three = fn () volatile async panic(Failed) -> i32 { return 100 } var divergent = fn () -> ! { crash!() // never returns; `panic` and `-> !` cannot be combined } ``` > [!NOTE] > Closures cannot be `eval`, `const`, `unsafe`, `virtual`, `override`, `inline`, or `final`. > [!NOTE] > An `async` closure that is also `panic`, like `all_three`, is not supported yet ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)). See [Status](/docs/status/#not-compiled-yet). See [Panic](/docs/language/panic/) for the full panic model. --- ## Nested Closures Closures can return or contain other closures, in both expression body and block body forms: ```kairo // Expression body: outer closure returns inner closure var nested = fn () = fn (x: i32) -> i32 = x * 2 // Block body: outer closure builds and returns inner closure var nested_block = fn () -> fn(i32) -> i32 { return fn (x: i32) -> i32 { return x + 1 } } // Mixed: block outer, expression inner var nested_mixed = fn () -> fn(i32) -> i32 { var offset = 10 return fn (x: i32) -> i32 = x + offset } ``` --- ## Tether and Lifetime Safety [Tether](/docs/language/tether/) tracks closure captures the same way it tracks any other borrow. If a closure captures a variable by pointer and the closure outlives the variable, Tether will attempt to [auto-promote](/docs/language/tether-promotion/) the capture to a smart pointer (shared, weak, or unique). If promotion is not possible, the compiler emits a hard error. ```kairo fn make_closure() -> fn() -> i32 { var x = 42 return fn ()|*x| -> i32 { return *x } // Tether error: x is a stack local, closure would outlive it, // and there is no safe promotion path for a stack variable } ``` Capture by copy avoids this entirely, the closure owns its own copy and has no lifetime dependency on the original: ```kairo fn make_closure() -> fn() -> i32 { var x = 42 return fn () -> i32 { return x } // ok, x is copied into the closure } ``` > [!WARNING] > Capturing stack-local variables by pointer in a closure that escapes the current scope is always a Tether error. There is no way to promote a pointer to a stack variable into a safe smart pointer. Use capture by copy for closures that outlive their enclosing scope. --- ## Closures vs Inner Functions Inner functions (named functions declared inside another function) do **not** capture from the enclosing scope, they are self-contained. Referencing an outer variable from an inner function is a compile error: ```kairo fn outer() -> i32 { var x = 10 fn inner(y: i32) -> i32 = y + 1 // ok, does not reference x // fn inner(y: i32) -> i32 = y + x // compile error: x is not in scope return inner(x) // pass x explicitly } ``` If you need to reference enclosing variables by pointer, use a closure. If you don't, prefer an inner function, it has no capture overhead and makes the data flow explicit. --- ## Passing Closures to Functions Since closures share the `fn` pointer type, they can be passed to any function expecting a function pointer. A parameter of the raw type `unsafe fn(...)`, such as a C callback, takes only a closure that captures nothing: ```kairo fn apply(f: fn(i32) -> i32, x: i32) -> i32 { return f(x) } apply(fn (x: i32) -> i32 { return x * 2 }, 21) // 42 var triple = fn (x: i32) -> i32 { return x * 3 } apply(triple, 10) // 30 ``` Higher-order patterns work naturally: ```kairo fn map(data: [i32], transform: fn(i32) -> i32) -> [i32] { var result: [i32] for item in data { result.push(transform(item)) } return result } var doubled = map([1, 2, 3], fn (x: i32) -> i32 { return x * 2 }) // doubled == [2, 4, 6] ``` --- ## Summary ```kairo // Lambda, no capture var add = fn (a: i32, b: i32) -> i32 { return a + b } // Expression body var twice = fn (x: i32) -> i32 = x * 2 // Closure, capture by copy (default) var x = 10 var add_x = fn (y: i32) -> i32 { return y + x } // Closure, capture all by pointer var count = 0 var inc = fn ()|*| { *count += 1 } // Closure, empty capture list (no captures) var none = fn ()|| { return 42 } // Closure, mixed capture var a = 1 var b = 2 var mix = fn ()|a, *b| { *b += a } // Generic closure var id = fn (x: T) -> T { return x } // Nested closures var nested = fn () = fn (x: i32) -> i32 = x * 2 // Modifiers var risky = fn () panic(Failed) -> i32 { return 42 } var divergent = fn () -> ! { crash!() } // Passing closures fn apply(f: fn(i32) -> i32, x: i32) -> i32 = f(x) apply(fn (x: i32) -> i32 { return x * 2 }, 5) // 10 ``` --- ## See also - [Functions](/docs/language/functions/#function-pointers) - [Ownership](/docs/language/ownership/#closure-captures) - [Tether](/docs/language/tether/) - [Ownership and Promotion](/docs/language/tether-promotion/) - [Threading](/docs/language/tether-threading/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/#function-modifiers) - [Panic](/docs/language/panic/) --- ## Classes URL: https://www.kairolang.org/docs/language/classes/ # Classes Classes are Kairo's primary mechanism for encapsulating state and behavior. The object model layout, vtables, ABI follows the platform's C++ convention. The surface syntax is cleaner, `self` is always explicit, and the copy/move model is expressed through [attributes](/docs/language/attributes/) rather than reference qualifiers. ## In this section - [Class Lifecycle](/docs/language/classes-lifecycle/): destructors and lifecycle categories - [Inheritance and Virtual Dispatch](/docs/language/classes-inheritance/): `derives`, `virtual`, abstract classes and `final` - [Forward Declarations and Out-of-Line Definitions](/docs/language/classes-out-of-line/) - [Generics](/docs/language/generics/): type parameter constraints --- ## Declaration ```kairo class Foo { var x: i32 var y: f64 fn Foo(self, x: i32, y: f64) { self.x = x self.y = y } fn sum(self) -> f64 { return self.x as f64 + self.y } } var obj = Foo(10, 3.14) obj.sum() // 13.14 ``` Members are declared with `var`, `const`, `static`, `eval`, or `thread` inside the class body. Methods are declared with `fn` and take `self` as the first parameter for instance methods. Omitting `self` requires the `static` modifier. If `self` is present, it is an instance method; if not, it must be `static`. --- ## `self` and `Self` `self` is the instance parameter. It behaves like a reference to the current object use `self.member` to access fields and `self` to pass the object to other functions. `self` is not a pointer; you cannot perform pointer arithmetic on it or reassign it. ### Members always need a qualifier Unlike C++, Kairo has no implicit `this->`. Inside a function body a member of the enclosing type is not in unqualified scope: an instance member is reached through `self`, a static member through `Self::` (or the type's own name). A bare name is a local, a parameter, or something from an enclosing scope, and never a member: ```kairo class Counter { var hits: i32 static total: i32 = 0 fn Counter(self) { self.hits = 0 } fn bump(self) { self.hits += 1 // ok Self::total += 1 // ok (`Counter::total` works too) // hits += 1 // error: use of member 'hits' requires an explicit qualifier // total += 1 // error: use of static member 'total' requires an explicit qualifier } } ``` The one exception is a name that denotes a **scope** rather than a value nested types, type aliases, and nested modules. Naming a type is not an access through an object, so a qualifier is not required. Prefer `Self::Node` anyway: a bare nested type, type alias or associated type of the enclosing type compiles, but the compiler warns and offers a fix-it that inserts `Self::`, because nothing at the use says the name is a member rather than something from the module: ```kairo class Tree { struct Node { var value: i32 } type Depth = i32 fn root(self) -> Self::Depth { var n = Self::Node { value: 0 } // preferred var m = Node { value: 1 } // ok, but warns: write `Self::Node` var d: Depth = 0 // ok, but warns: alias, same rule return d } } ``` The warning applies anywhere in the body, a field type or method signature included. It names the innermost type only: inside `Node`, a bare `Depth` (a member of `Tree`, not of `Node`) and `Node` itself are not warned, since `Self::` there would mean `Node::`. The rule does not depend on where a method is written. It is identical in a `class`, `struct`, `union` or `interface` body, in an [`extend`](/docs/language/extends/) block, in an out-of-line `fn Type::method` definition, and inside a [closure](/docs/language/closures/) in any of those. `Self` (capitalized) is a type alias for the enclosing class. In a generic class `class Foo`, `Self` resolves to `Foo`. Use `Self` in parameter types, return types, and anywhere you need the class's own type without spelling out generic arguments: ```kairo class Container { var items: [T] fn Container(self) { self.items = [] } fn merge(self, other: Self) -> Self { var result = Container() for item in self.items { result.items.push(item) } for item in other.items { result.items.push(item) } return result } } ``` `Self` always refers to a reference to the class type. For a pointer, use `*Self` or `*ClassName`. The bare class name works anywhere `Self` does `Self` is syntactic sugar, not a distinct type. --- ## Visibility Visibility modifiers control access to members from outside the class: | Keyword | Scope | |---|---| | `pub` | Accessible from any module | | `priv` | Accessible within the defining class, and anywhere in the file that declares it, free functions included | | `prot` | What `priv` allows, plus every file of the declaring file's [module](/docs/language/modules/#visibility-scopes) (the tree under the nearest `module.k`), plus every class that derives from the defining class, anywhere | Modifiers are applied per-declaration. There are no visibility blocks (`public:` sections). Kairo checks visibility itself: using a `priv` member from another file, or a `prot` one outside its module and outside a subclass, is an error that offers to make the member `pub`. A `prot` member of a class whose file is in no module is refused in another file with a warning naming the missing `module.k`. An [`extend`](/docs/language/extends/) of the class in another file of its module reads its `prot` members, so a large class can be split across the files of one module. Operators are members like any other: a `priv fn op +` is usable only where a `priv` method would be. A base's members reached through a `derives priv` (or `derives prot`) edge are private (protected) to the deriving class and its file. A subclass outside the module uses a `prot` member the way C++ allows a protected one: - an instance field or method only through an object of the subclass's own type, or of a type deriving from it (`self.hits`, `other_counter.hits`), not through a `*Base` or a sibling subclass; - a `prot` constructor only as the base initializer `Base::Base(self, ...)` at the start of its own constructor, not to build a separate `Base`. `prot` statics and nested types have no such restriction. The C++ that Kairo generates keeps these levels: a `priv` member is `private:` and a `prot` one `protected:`, and the class names its file's functions and types as friends. C++ has no "module" access, so in a file under a `module.k` a `prot` member is `public:` in C++, and Kairo alone keeps it to the module. A C++ program that includes the module sees the members as Kairo has them (see [What crosses an include](/docs/language/c-cpp-exposing/#what-crosses-an-include)). ### Default visibility A member with no visibility written is `priv`, or `prot` when the class's file is under a `module.k`, whatever its kind: variables, methods, constructors, operators, static methods, nested types. A class meant to be used from other files marks its interface `pub`, its constructors included. (Compiler-made members, such as an implicit copy constructor or destructor, are available wherever the class is.) ```kairo pub class Account { var balance: f64 // priv by default (prot under a module.k) pub var owner: string // explicitly public pub fn Account(self, owner: string) { // a constructor other files may call self.owner = owner self.balance = 0.0 } pub fn deposit(self, amount: f64) { self.balance += amount } priv fn audit_log(self) { // internal only } } ``` Visibility also applies at the top level a `priv class` is only accessible within its file, a `prot class` within its module and subclasses. See [Modules](/docs/language/modules/) for how top-level visibility interacts with [imports](/docs/language/imports/). > [!NOTE] > Kairo has no `friend` keyword. If external code needs access to internals, expose it through a public method or adjust module-level visibility. `priv` at the top level restricts access to the current file, which covers most factory and serialization patterns. --- ## Constructors Constructors use the class name as the function name and take `self` as the first parameter: ```kairo class Point { var x: f64 var y: f64 fn Point(self, x: f64, y: f64) { self.x = x self.y = y } } var p = Point(1.0, 2.0) ``` Constructors support all the features of regular functions default parameters, named arguments, overloading by parameter types, generic type parameters. See [Functions](/docs/language/functions/). ### Const members in constructors Class-level `const` members can be initialized in the constructor body. They get exactly one assignment; after construction, they are frozen: ```kairo class Config { const MAX_RETRIES: i32 var timeout: f64 fn Config(self, retries: i32, timeout: f64) { self.MAX_RETRIES = retries // one-shot assignment, legal self.timeout = timeout } } var cfg = Config(3, 30.0) // cfg.MAX_RETRIES = 5 // compile error: MAX_RETRIES is const ``` If a `const` member has an initializer at the declaration site, it cannot be reassigned in the constructor. ### Fields without a default A field with no initializer whose type has no default value (`bool`, an [enum with payloads](/docs/language/enums-adt/), a class with no default constructor, or an array of any of these; see [Variables](/docs/language/variables/#default-initialization)) must be initialized by every constructor, like a `const` member. The constructor's first write of the whole field is its initialization; later writes are ordinary assignments: ```kairo enum Frame { Burst { base: i32, count: i32 }, Idle, } class Batch { var frames: [Frame; 3] var ready: bool fn Batch(self, base: i32) { self.frames = [.Burst { base: base, count: 3 }, .Idle, .Idle] // initialization self.ready = false self.log() // the object exists from here self.frames[2] = .Burst { base: 1, count: 1 } // ordinary assignment } fn log(self) { } } ``` Until every such field is initialized, the object does not exist yet, so the constructor can use `self` only to initialize fields and to read the ones already initialized: no method call, no `return`. A field the constructor leaves uninitialized on some path is an error at the constructor. An array field can also be built element by element: writing every element once, `self.frames[k] = ...` for each `k` from `0` to `N - 1` with a constant index, initializes it. The writes may come in any order and be spread over branches, as long as every path writes every element exactly once, outside any loop, before the array (or `self`) is read. Each element is built where its write is, so the right-hand sides run in source order with the statements around them. From the last element on, the array exists and further element writes are ordinary assignments: ```kairo class Pair { var frames: [Frame; 2] fn Pair(self, base: i32) { self.frames[1] = .Idle // builds element 1 self.frames[0] = .Burst { base: base, count: 2 } // builds element 0: frames exists from here self.frames[1] = .Burst { base: 1, count: 1 } // ordinary assignment } } ``` Leaving an element out on some path, writing one twice, an index that is not a constant, a write inside a loop, or reading the array before its last element is an error naming the elements still missing or the offending write. Only whole elements count: a write into an element (`self.toks[0].n = 1`) needs the element to exist already, and an array of arrays cannot be built element by element; assign those whole. Giving the field an initializer at its declaration (`var frames: [Frame; 3] = [.Idle, .Idle, .Idle]`) lifts the requirement. An array is not assignable, so an array field's one whole write in a constructor is its initialization: it must happen on every path through the constructor or on none, and never in a loop. A second whole write is an error; write the elements instead. ### Default and deleted constructors ```kairo class Defaults { var x: i32 fn Defaults(self) = default // compiler-generated default constructor } class NoDefault { var x: i32 fn NoDefault(self) = delete // no default construction allowed } var a = Defaults() // ok: x is zero-initialized var b = NoDefault() // compile error: default constructor is deleted ``` See [Variables](/docs/language/variables/#default-initialization) for default initialization rules. --- Destructors are covered in [Destructors - op finally](/docs/language/classes-lifecycle/#destructors---op-finally). Lifecycle categories are covered in [Lifecycle Categories](/docs/language/classes-lifecycle/#lifecycle-categories). Inheritance and virtual dispatch are covered in [Inheritance and Virtual Dispatch](/docs/language/classes-inheritance/). --- ## Interfaces A class can declare interface conformance with `impl`. The compiler verifies at declaration time that the class satisfies all interface requirements: ```kairo interface Hashable { fn hash(const self) -> u64 } class UserId impl Hashable { var id: u64 fn UserId(self, id: u64) { self.id = id } fn hash(const self) -> u64 { return self.id } } ``` Interface conformance is structural a class that has the required methods satisfies the interface whether or not `impl` is declared. The `impl` keyword triggers the check at the declaration site rather than at the point of use. ```kairo class Point { var x: f64 var y: f64 fn hash(const self) -> u64 { ... } } fn insert(set: {T}, item: T) { ... } insert(my_set, Point(1.0, 2.0)) // compiles: Point has hash() ``` See [Interfaces](/docs/language/interfaces/) and [Requires Clauses](/docs/language/requires/). --- ## Generic Classes [Type parameters](/docs/language/generics/) are declared in angle brackets before the class name: ```kairo struct StackUnderflow { fn op panic (const self) -> string { return "stack underflow" } } class Stack { var items: [T] fn Stack(self) { self.items = [] } fn push(self, item: T) { self.items.push(item) } fn pop(self) panic -> T { if self.items.length() == 0 { panic StackUnderflow {} } return self.items.pop() } } var s = Stack() s.push(42) ``` > [!NOTE] > A `panic` method of a generic class, like `pop` here, works: the set is computed at the definition. See [Generic functions](/docs/language/panic/#generic-functions) in Panic. Generic classes can inherit from other generic classes: ```kairo class Base { var data: T } class Derived derives Base { var extra: i32 } ``` Type parameter constraints are covered in [Generics](/docs/language/generics/#type-parameter-constraints). --- ## Static Members Static members belong to the class, not to any instance. They are declared with `static` and accessed via `ClassName::member`: ```kairo class Counter { static count: i32 = 0 fn Counter(self) { Counter::count += 1 } static fn get_count() -> i32 { return Counter::count } } var a = Counter() var b = Counter() Counter::get_count() // 2 ``` Static variables are declared `static name: Type`, with no `var`, and require an explicit type annotation. They can be initialized at the declaration site or at program startup. Static methods do not take `self` and cannot access instance members. --- ## Const Methods A method that takes `const self` promises not to modify the object (except `mutable` members). It is the ["can I change the pointee?"](/docs/language/variables/#the-const-binding-rule) question asked about the receiver. Only `const` methods can be called through a `*const T` pointer or on a `const` binding: ```kairo class Sensor { var reading: f64 mutable var read_count: i32 fn value(const self) -> f64 { self.read_count += 1 // ok: mutable member return self.reading } fn calibrate(self, offset: f64) { self.reading += offset } } const sensor: *const Sensor = &some_sensor sensor->value() // ok: const method // sensor->calibrate(1.0) // compile error: not const ``` `const` and non-`const` methods with the same name and parameter types cannot coexist use distinct names like `get()` and `get_mut()`. See [Variables](/docs/language/variables/#the-const-binding-rule). Inside a `const self` method, assigning to a field of `self` is a compile error (SC071E) unless the field is declared `mutable var`. ### Mutable members The `mutable` qualifier allows a member to be modified even through a `const` reference or in a `const` method: ```kairo class Cache { var data: [i32] mutable var hit_count: i32 fn Cache(self) { self.data = [] self.hit_count = 0 } fn lookup(const self, index: usize) -> i32 { self.hit_count += 1 // ok: mutable return self.data[index] } } ``` `mutable` is only valid on instance variables inside class and struct bodies. It cannot appear on top-level variables, local variables, or `const`/`eval`/`static` declarations. > [!WARNING] > `mutable` breaks the semantic guarantee that `const` methods do not modify the object. Use it sparingly caching, reference counting, and lazy initialization are the canonical use cases. If you find yourself marking many members `mutable`, reconsider the `const` boundary. --- A method may be named `test`, and a C++ method named `test` can be called; `test` is a keyword only to open a top-level test block. ## `inline` Methods `inline` puts the body in the interface: importers compile it themselves. Use it for small functions on hot paths, and for functions the C++ compiler calls on your behalf (coroutine promises and awaiters). ```kairo pub class Gate { pub var open: bool pub inline fn is_open(self) -> bool { return self.open } } ``` Every module that uses `Gate` compiles `is_open` itself, so a call to it can be inlined there. Every `inline` method of a class goes with the class, whether or not Kairo code calls it, because the C++ compiler may call methods Kairo never sees (`await_ready`, `initial_suspend`, ...). The class definition itself is unchanged: the bodies are emitted after it, outside it. See [Functions](/docs/language/functions-declarations/#inline) for the rules. `inline` is allowed on `virtual` and `override` methods. If every virtual method of a class is `inline`, the class has no key function, so its vtable is emitted in every object that uses the class. That is correct; it costs only size. --- ## Nested Classes Classes can be declared inside other classes. Nested classes can access private members of the enclosing class: ```kairo class Tree { priv class Node { var value: i32 var left: unsafe *Node var right: unsafe *Node } var root: unsafe *Node fn Tree(self) { self.root = &null } } ``` A type nested in a generic class belongs to each instance: `L::P` and `L::P` are different types, and a member of `L::P` typed with `L`'s parameter reads with `i32`. Name it through the instance from outside the class (`var q: L::P = l.make(7)`, `L::P { k: 1 }`, `L::Color::Red`); inside the class, `Self::P` is the current instance's. A generic function can take one and deduce the instance's arguments from it (`fn first(r: L::P) -> T`). --- Forward declarations and out-of-line definitions are covered in [Forward Declarations and Out-of-Line Definitions](/docs/language/classes-out-of-line/). --- ## Operator Overloading Operators are overloaded with `fn op` syntax inside the class body: ```kairo class Vec2 { var x: f64 var y: f64 fn Vec2(self, x: f64, y: f64) { self.x = x self.y = y } fn op +(self, other: Vec2) -> Vec2 { return Vec2(self.x + other.x, self.y + other.y) } fn op ==(const self, other: Vec2) -> bool { return self.x == other.x && self.y == other.y } } var a = Vec2(1.0, 2.0) var b = Vec2(3.0, 4.0) var c = a + b // Vec2(4.0, 6.0) ``` Special operators beyond arithmetic: | Syntax | Purpose | |---|---| | `fn op finally(self)` | Destructor | | `fn op as(self) -> TargetType` | Custom type conversion via `as` | | `fn op await(self, obj: std::forward) -> T` | Custom awaitable | `op =` is **not** user-definable it is auto-derived from the transfer constructor. See [Lifecycle Categories](/docs/language/classes-lifecycle/#lifecycle-categories). See [Operators](/docs/language/operator-overloading/) for the full list of overloadable operators and restrictions. --- ## Memory Layout and Allocation Class layout follows the platform's C++ ABI: - **Non-polymorphic classes**: members laid out in declaration order with standard padding and alignment. - **Polymorphic classes** (at least one `virtual` method): vtable pointer at offset 0 (8 bytes on 64-bit), followed by members. - **Inheritance**: base class subobject precedes derived members. Layout can be controlled with [attributes](/docs/language/attributes/): ```kairo @packed class Compact { var a: u8 // offset 0 var b: u32 // offset 1 (no padding) } @align(16) class Aligned { var data: [u8; 12] } ``` A plain `var` declaration allocates on the stack: ```kairo var obj = Foo(42) // stack-allocated ``` Heap allocation uses `@create T()`, which returns a pointer. [Tether](/docs/language/tether/) determines whether the returned pointer is raw or promoted to a smart pointer based on usage analysis: ```kairo var *ptr = @create Foo(42) ``` See [Pointers](/docs/language/pointers/) and [Tether](/docs/language/tether/). --- ## Structs vs Classes Structs and classes are distinct types: | | Class | Struct | |---|---|---| | Member default visibility | `priv` (`prot` under a `module.k`) | `pub` for all members | | Methods in body | Yes | No (use [extends](/docs/language/extends/)) | | Aggregate initialization | Only if the class declares no constructor | Yes (`Foo { field: value }`) | | Inheritance | `derives` | Not supported | | Virtual dispatch | Yes | No | | Lifecycle categories | Yes | N/A (no transfer constructors; copyable whenever every field is) | See [Structures](/docs/language/structures/). --- ## Summary ```kairo // Basic class class Point { var x: f64 var y: f64 fn Point(self, x: f64, y: f64) { self.x = x self.y = y } fn distance(const self, other: Self) -> f64 { var dx = self.x - other.x var dy = self.y - other.y return std::sqrt(dx * dx + dy * dy) } } // Move-only class class UniqueFile { var handle: unsafe *void fn UniqueFile(self, path: string) { self.handle = open_file(path) } @move fn UniqueFile(self, other: Self) { self.handle = other.handle other.handle = &null } fn op finally(self) { close_file(self.handle) } } // Inheritance with virtual dispatch class Shape { virtual fn area(const self) -> f64 } class Circle derives Shape { var radius: f64 fn Circle(self, r: f64) { self.radius = r } override fn area(const self) -> f64 { return 3.14159 * self.radius * self.radius } } // Generic class with interface conformance class PriorityQueue impl Iterable { priv var heap: [T] fn PriorityQueue(self) { self.heap = [] } fn push(self, item: T) { ... } fn pop(self) panic -> T { ... } } // Final class final class Immutable { const value: i32 fn Immutable(self, v: i32) { self.value = v } } ``` --- A class or struct whose only constructor is `@copy` or `@move` cannot be built with braces (SC088E). ## See also - [Structures](/docs/language/structures/) - [Interfaces](/docs/language/interfaces/) - [Operator Overloading](/docs/language/operator-overloading/) - [Extends](/docs/language/extends/) - [Generics](/docs/language/generics/) - [Pointers](/docs/language/pointers/) - [Tether](/docs/language/tether/) --- ## Structures URL: https://www.kairolang.org/docs/language/structures/ # Structures Structs are plain data types no constructors, no methods in the body, trivially copyable via `memcpy`. They exist for cases where you want a named bag of fields with aggregate initialization and no lifecycle management. If you need constructors, destructors, inheritance, or virtual dispatch, use a [class](/docs/language/classes/). --- ## Declaration ```kairo struct Point { var x: f64 var y: f64 } var p = Point { x: 1.0, y: 2.0 } p.x // 1.0 ``` The body contains only field declarations (`var`, `const`, `eval`, `static`) and nested type definitions. Methods and constructors are not permitted inside the struct body use [extends](/docs/language/extends/) to add behavior. --- ## Aggregate Initialization Structs are constructed with brace-delimited field assignment. All fields must be provided unless they have a default value at the declaration site: ```kairo struct Color { var r: u8 var g: u8 var b: u8 var a: u8 = 255 } var red = Color { r: 255, g: 0, b: 0 } // a defaults to 255 var blue = Color { r: 0, g: 0, b: 255, a: 128 } // explicit alpha ``` A field's default may read fields declared before it, and no others. Defaults run in declaration order, so a later field, or the field itself, is not built yet. Field names are required in the initializer positional initialization is not supported. The order of fields in the initializer does not need to match the declaration order. There are no user-defined constructors. If you need construction logic, extend a factory function onto the struct: ```kairo extend Color { static fn from_hex(hex: u32) -> Color { return Color { r: (hex >> 16 & 0xFF) as u8, g: (hex >> 8 & 0xFF) as u8, b: (hex & 0xFF) as u8, } } } var teal = Color::from_hex(0x008080) ``` --- ## Visibility All struct members default to `pub`. You can explicitly mark a member `priv` or `prot`, but the compiler emits a warning if you need access control on fields, a [class](/docs/language/classes/) is the better fit. Kairo enforces a `priv` field, but in the generated C++ a struct's fields stay public: a struct is a plain aggregate with the C layout, and a private field would change how C and MSVC pass it. ```kairo struct Packet { var header: u32 // pub by default priv var checksum: u32 // legal but warned: consider using a class } ``` Extended functions can be `pub`, `prot`, or `priv` without warning. --- ## Const and `mutable` Members `const` members must be initialized at the declaration site or in the aggregate initializer. Unlike class `const` members, there is no constructor body to provide a one-shot assignment: ```kairo struct Config { const VERSION: i32 = 1 var name: string } var cfg = Config { name: "app" } // cfg.VERSION = 2 // compile error: VERSION is const ``` `mutable` works the same as in classes the member can be modified even through a `const` reference: ```kairo struct Metrics { var total: i32 mutable var cache_hits: i32 } fn report(const self: Metrics) { self.cache_hits += 1 // ok: mutable // self.total += 1 // compile error: total is not mutable, self is const } ``` See [Classes](/docs/language/classes/#mutable-members) for the `mutable` rationale and usage guidance. --- ## Copy Semantics Structs are always trivially copyable. Assignment and parameter passing use `memcpy` there are no copy constructors, move constructors, or assignment operator overloads: ```kairo var a = Point { x: 1.0, y: 2.0 } var b = a // memcpy, a and b are independent copies b.x = 9.0 a.x // still 1.0 ``` This is a hard guarantee. Extending a destructor (`fn op finally`), copy assignment (`fn op =`), or move assignment onto a struct is a compile error. If you need custom lifecycle management, use a [class](/docs/language/classes-lifecycle/#the-rule-of-three). --- ## Extends Since structs cannot contain methods in their body, behavior is added via `extend` blocks. An `extend` block can add methods, operators, and static functions: ```kairo struct Vec2 { var x: f64 var y: f64 } extend Vec2 { fn length(const self) -> f64 { return std::sqrt(self.x * self.x + self.y * self.y) } fn op +(self, other: Vec2) -> Vec2 { return Vec2 { x: self.x + other.x, y: self.y + other.y } } fn op ==(const self, other: Vec2) -> bool { return self.x == other.x && self.y == other.y } } var v = Vec2 { x: 3.0, y: 4.0 } v.length() // 5.0 ``` ### What extends can add | Allowed | Not allowed | |---|---| | Methods | Constructors | | Static functions | Destructors (`fn op finally`) | | Arithmetic / comparison operators | Copy / move assignment (`fn op =`) | | `fn op as` (type conversion) | | | `fn op in` (iteration) | | ### Interface conformance Structs implement interfaces through `extend ... impl`: ```kairo interface Drawable { fn draw(self) -> string } extend Vec2 impl Drawable { fn draw(self) -> string { return f"({self.x}, {self.y})" } } ``` The `extend` block and the struct definition must be in the same file the same restriction as Rust's `impl` blocks. See [Extends](/docs/language/extends/) for the full `extend` system and [Interfaces](/docs/language/interfaces/) for interface declarations. --- ## Generic Structs [Type parameters](/docs/language/generics/) are declared in angle brackets before the struct name: ```kairo struct Pair { var first: T var second: T } var p = Pair { first: 10, second: 20 } ``` Generic extends must redeclare the type parameters: ```kairo extend Pair { fn swap(self) -> Pair { return Pair { first: self.second, second: self.first } } } ``` Constrain type parameters with `impl` or `derives` bounds: ```kairo struct Range { var start: T var end: T } ``` See [Requires Clauses](/docs/language/requires/) for the full constraint system. --- ## Nested Types Structs can contain nested type definitions classes, enums, unions, other structs: ```kairo struct Packet { var header: Header var payload: [byte] struct Header { var version: u8 var length: u16 } } var pkt = Packet { header: Packet::Header { version: 1, length: 64 }, payload: [], } ``` Nested types are accessed via `StructName::NestedType`. Interfaces cannot be nested they must be declared at the top level. --- ## No Inheritance Structs do not support `derives`. If you need field inheritance, embed the struct: ```kairo struct Base { var x: i32 } struct Composed { var base: Base var y: i32 } var c = Composed { base: Base { x: 10 }, y: 20 } c.base.x // 10 ``` This keeps aggregate initialization unambiguous and avoids layout questions that inheritance introduces. If you need polymorphism or a type hierarchy, use [classes](/docs/language/classes-inheritance/#inheritance). --- ## Destructuring Struct fields can be destructured into individual bindings: ```kairo struct Color { var r: u8 var g: u8 var b: u8 } var color = Color { r: 255, g: 128, b: 0 } var { r, g, b } = color // r = 255, g = 128, b = 0 ``` Use `_` to discard fields you do not need. See [Variables](/docs/language/variables/#destructuring) for the full destructuring syntax. --- ## Memory Layout Struct layout follows the platform's C++ ABI members in declaration order with standard padding and alignment rules. Control layout with [attributes](/docs/language/attributes/#layout-attributes): ```kairo @packed struct Tight { var a: u8 // offset 0 var b: u32 // offset 1 (no padding) } @align(16) struct Aligned { var data: [u8; 12] } ``` Structs are always value types. A plain `var` declaration allocates on the stack. Heap allocation uses `@create T()`: ```kairo var local = Point { x: 1.0, y: 2.0 } // stack var *heap = @create Point{ x: 1.0, y: 2.0 } // heap ``` See [Pointers](/docs/language/pointers/) and [Tether](/docs/language/tether/) for allocation and pointer semantics. --- ## Forward Declarations Structs can be forward-declared for use in [pointer types](/docs/language/pointers/) before the full definition is available: ```kairo struct Node // forward declaration struct Tree { var root: unsafe *Node } struct Node { var value: i32 var left: unsafe *Node var right: unsafe *Node } ``` A forward declaration and its definition are one type, wherever each sits in the scope (the definition may even come first), and they must use the same keyword: `struct Node` followed by `class Node { ... }` is an error, with a fix-it to the definition's keyword. A type that is only forward-declared and never defined can be used through a pointer only: a field, base or variable holding it by value is an error, since its size is unknown. Forward declarations also work inside a class body, with or without a trailing `;`: ```kairo class Queue { struct Cell; var head: unsafe *Self::Cell struct Cell { var seq: u64 } } ``` --- ## Structs vs Classes | | Struct | Class | |---|---|---| | Member default visibility | `pub` | `priv` for variables | | Methods in body | No (use [extends](/docs/language/extends/)) | Yes | | Constructors | No (aggregate init only) | Yes | | Destructors | No | Yes | | Copy semantics | `memcpy` (trivial) | Rule of Three | | Inheritance | No | `derives` | | Virtual dispatch | No | Yes | | Aggregate initialization | Yes | No | Use structs for plain data configuration records, protocol headers, math vectors, tuple-like types. Use classes when you need lifecycle control, inheritance, or encapsulation. --- ## Summary ```kairo // Basic struct struct Point { var x: f64 var y: f64 } var p = Point { x: 1.0, y: 2.0 } // Generic struct struct Pair { var first: T var second: T } // Extend with methods and operators extend Point { fn length(const self) -> f64 { return std::sqrt(self.x * self.x + self.y * self.y) } fn op +(self, other: Point) -> Point { return Point { x: self.x + other.x, y: self.y + other.y } } } // Extend with interface conformance extend Point impl Drawable { fn draw(self) -> string { return f"({self.x}, {self.y})" } } // Layout control @packed struct Header { var magic: u16 var version: u8 var flags: u8 } // Composition over inheritance struct Rect { var origin: Point var size: Point } var r = Rect { origin: Point { x: 0.0, y: 0.0 }, size: Point { x: 100.0, y: 50.0 }, } ``` --- ## See also - [Classes](/docs/language/classes/) - [Extends](/docs/language/extends/#structs) - [Pattern Matching](/docs/language/pattern-matching/#struct-matching) - [Class Lifecycle](/docs/language/classes-lifecycle/) - [Variables](/docs/language/variables/#default-initialization) - [Unions](/docs/language/unions/) - [Enums](/docs/language/enums/) - [Generics](/docs/language/generics/) --- ## Enums URL: https://www.kairolang.org/docs/language/enums/ # Enums Enums define a closed set of named variants. In their simplest form, each variant is an integer discriminant, equivalent to a C++ `enum class`. Variants can also carry structured data ([ADT enums](/docs/language/enums-adt/)), making them Kairo's mechanism for type-safe tagged unions. Dispatch on variants with `match`. See [Control Flow](/docs/language/pattern-matching/) for the complete `match` syntax. ## In this section - [Plain Enums](/docs/language/enums-plain/): named integer constants, discriminant values, underlying types, casting, and forward declarations. - [ADT Enums](/docs/language/enums-adt/): variants with payloads, construction, destructuring with `match`, memory layout, lifecycle, generic enums, and casting. --- ## Shorthand Syntax When the compiler can infer the enum type from context, the `.Variant` shorthand is available in construction, `match` cases, comparison, and assignment: ```kairo enum Direction { North, East, South, West } fn go_up() { } fn go_down() { } fn go_right() { } fn go_left() { } fn main() -> i32 { var dir: Direction = .North match dir { case .North { go_up() } case .South { go_down() } case .East { go_right() } case .West { go_left() } } if dir == .North { go_up() } dir = .South return 0 } ``` The fully qualified form (`Direction::North`) always works and is required when the type cannot be inferred. `.V` takes its enum from the type expected where it is written: - an initializer with a declared type: `var d: Dir = .North` - a `return` in a function with a declared return type - a call argument, which takes the parameter's type - the other operand of `==` or `!=`, on either side: `.North == d` is `d == .North`. Two shorthands compared with each other (`.A == .B`) have no enum to take and are an error (SC123E) ```kairo enum Dir { North, East, South, West } enum Light { Red, Green } fn turn(d: Dir) { } fn set(l: Light) { } fn set(d: Dir) { } fn log(x: T) { } fn opposite(d: Dir) -> Dir { return .South // return with a declared return type } fn main() -> i32 { var d: Dir = .North // initializer with a declared type turn(.West) // call argument set(.Green) // only Light has Green: picks set(l: Light) set(.East) // only Dir has East: picks set(d: Dir) log(Dir::North) // generic parameter: write the enum in full return 0 } ``` As an argument, `.V` matches a parameter only if that parameter's enum has a variant `V`; this is how an [overload](/docs/language/functions-overloading/) is chosen. If more than one overload's enum has `V`, the call is ambiguous ([SC064E](/docs/language/diagnostics/#call-to-f-is-ambiguous-more-than-one-candidate-matches-at-the-same-rank)). A generic parameter `T` gives `.V` no enum to take, so no overload matches (SC063E); write the variant in full, `Dir::North`: ```kairo enum Dir { North, South } enum Pole { North, Equator } fn go(d: Dir) { } fn go(p: Pole) { } fn log(x: T) { } fn main() -> i32 { go(.North) // error SC064E: both Dir and Pole have North log(.North) // error SC063E: T gives .North no enum type return 0 } ``` A `.V` with nothing to give it an enum type, against a type that is not an enum, or naming a variant the enum does not have is [SC123E](/docs/language/diagnostics/#sc123e-a-variant-name-does-not-fit-the-expected-type). --- ## Comparison and Assignment Enum values support equality comparison and assignment. Ordering operators (`<`, `>`, `<=`, `>=`) are not available by default [extend](/docs/language/extends/#enums) them if needed: ```kairo enum Direction { North, East, South, West } fn main() -> i32 { var a = Direction::North var b = Direction::South var same = a == b // ok: false var differ = a != b // ok: true // var before = a < b // compile error: no ordering defined return 0 } ``` `==` and `!=` on enums are built in and compare which variant is active, ignoring payloads. They satisfy `Equatable` the same way integer comparison does; no operator declaration is involved. --- ## Extends Enums cannot contain methods in their body. Use `extend` blocks to add behavior, matching the same pattern as [structs](/docs/language/structures/#extends): ```kairo enum LogLevel { Debug, Info, Warning, Error, Fatal, } extend LogLevel { fn is_severe(const self) -> bool { return self == .Error || self == .Fatal } fn prefix(const self) -> string { match self { case .Debug { return "[DEBUG]" } case .Info { return "[INFO]" } case .Warning { return "[WARN]" } case .Error { return "[ERROR]" } case .Fatal { return "[FATAL]" } } } static fn from_string(s: string) -> LogLevel { match s { case "debug" { return .Debug } case "info" { return .Info } case "warning" { return .Warning } case "error" { return .Error } case "fatal" { return .Fatal } default { return .Info } } } } ``` ### What extends can add | Allowed | Not allowed | |---|---| | Methods | Constructors | | Static functions | Destructors | | Comparison / arithmetic operators | Copy / move assignment | | `fn op as` (type conversion) | | ### Interface conformance Enums can implement interfaces through `extend ... impl`: ```kairo enum LogLevel { Debug, Info, Warning, Error, Fatal } interface Loggable { fn to_log_string(const self) -> string } extend LogLevel impl Loggable { fn to_log_string(const self) -> string { if self == .Error || self == .Fatal { return "severe" } return "normal" } } ``` The `extend` block and the enum definition must be in the same file. See [Extends](/docs/language/extends/) for the full `extend` system and [Interfaces](/docs/language/interfaces/) for interface declarations. --- ## No Inheritance Enums do not support inheriting from other enums. The `derives` keyword on an enum is reserved exclusively for specifying the [underlying type](/docs/language/enums-plain/#underlying-type). --- ## Summary ```kairo // Plain enum enum Direction { North, East, South, West, } // Explicit discriminants + underlying type enum Opcode derives u8 { Nop = 0x00, Load = 0x01, Store = 0x02, Halt = 0xFF, } // Bit flags enum FileMode derives u8 { Read = 1 << 0, Write = 1 << 1, Execute = 1 << 2, All = (Read | Write | Execute), } // ADT enum with payloads enum LookupResult { Found { key: K, value: V }, NotFound { key: K }, Error { message: string }, } // Extended with methods extend Direction { fn opposite(self) -> Direction { match self { case .North { return .South } case .South { return .North } case .East { return .West } case .West { return .East } } } } fn main() -> i32 { // Construction var r = LookupResult::Found { key: "count", value: 42 } // Match with destructuring match r { case .Found(var key, var value) { var line = f"{key} = {value}" } case .NotFound(var key) { var line = f"{key} not found" } case .Error(var message) { var line = f"error: {message}" } } var back = Direction::North.opposite() return 0 } ``` ## See also - [Plain Enums](/docs/language/enums-plain/) - [ADT Enums](/docs/language/enums-adt/) - [Extends](/docs/language/extends/) - [Interfaces](/docs/language/interfaces/) - [Control Flow](/docs/language/pattern-matching/) - [Unions](/docs/language/unions/) - [Casting](/docs/language/casting/#enum-casts) --- ## Unions URL: https://www.kairolang.org/docs/language/unions/ # Unions Unions overlay multiple fields at the same memory address, sized to the largest member. They are a low-level memory layout tool for hardware registers, binary protocol parsing, and type punning. The user is responsible for tracking which field is active there is no compiler-managed tag. For type-safe tagged unions with compiler-enforced variant tracking, use [ADT enums](/docs/language/enums-adt/#adt-enums). --- ## Declaration ```kairo union Register { var as_u32: u32 var as_bytes: [u8; 4] var as_f32: f32 } ``` All fields share the same starting address. The union's size is the size of its largest member, plus any alignment padding. --- ## Usage Read and write fields with plain assignment. No special syntax or [`unsafe` block](/docs/language/unsafe/#unsafe-blocks) is required: ```kairo var r: Register r.as_u32 = 0xDEADBEEF var byte0 = r.as_bytes[0] // reads overlapping memory as u8 r.as_f32 = 3.14f32 // r.as_u32 now contains the bit representation of 3.14 as f32 ``` Reading a field other than the one last written is type punning the value you get is the raw bit reinterpretation. This is legal but the result depends entirely on the underlying representation. > [!CAUTION] > The compiler does not track which field was last written. Reading the wrong field is not a compile error it produces whatever bits happen to be in memory. This is the intended use case for unions, but it means correctness is entirely on the caller. --- ## Trivial Types Only Union fields must be trivially copyable. The following types are permitted: - Integers (`i8`-`i512`, `u8`-`u512`, `isize`, `usize`) - Floats (`f16`-`f512`) - Booleans (`bool`) - Characters (`char`) - Bytes (`byte`) - [Pointers](/docs/language/pointers/) (`*T`, `unsafe *T`) - Fixed-size arrays of trivial types (`[T; N]`) - [Structs](/docs/language/structures/) where all fields are trivially copyable - Other unions - [Enums](/docs/language/enums-plain/) (plain, without ADT payloads) Non-trivially copyable types are a compile error: ```kairo union Bad { var text: string // compile error: string has a destructor var data: [i32] // compile error: vector owns heap memory } ``` If you need a union of non-trivial types, use an [ADT enum](/docs/language/enums-adt/#adt-enums) the compiler manages construction, destruction, and active-variant tracking for you. --- ## Unions Must Be Named Unions cannot exist as standalone anonymous types. They must always be declared with a name: ```kairo union Pixel { // ok: named union var rgba: u32 var channels: [u8; 4] } ``` --- ## Nesting in Structs and Classes Unions are commonly embedded in [structs](/docs/language/structures/) or [classes](/docs/language/classes/) for structured access to overlapping data: ```kairo struct Packet { var opcode: u8 var payload: PacketData } union PacketData { var as_int: i64 var as_float: f64 var as_bytes: [u8; 8] } var pkt: Packet pkt.opcode = 0x01 pkt.payload.as_int = 42 ``` For a type-safe version of this pattern (where the opcode determines which payload field is valid), use an [ADT enum](/docs/language/enums-adt/#adt-enums) instead. --- ## Generic Unions Unions can be [generic](/docs/language/generics/): ```kairo union Either { var left: T var right: U } var e: Either e.left = 42 ``` Type parameters must resolve to trivially copyable types. The compiler errors at instantiation time if a type argument is not trivially copyable. --- ## Memory Layout Union layout follows the platform's C++ ABI: - Size equals the largest member's size, rounded up for alignment - All fields start at offset 0 - Alignment is the strictest alignment of any member [Layout attributes](/docs/language/attributes/#layout-attributes) work the same as on [structs](/docs/language/structures/#memory-layout) and classes: ```kairo @packed union Compact { var a: u8 var b: u32 // no padding between a and b at the union level } @align(16) union Aligned { var data: [u8; 12] var value: i32 } ``` --- ## Forward Declarations Unions can be forward-declared for use in [pointer types](/docs/language/pointers/): ```kairo union Payload // forward declaration struct Message { var kind: u8 var data: unsafe *Payload } union Payload { var as_int: i64 var as_bytes: [u8; 8] } ``` A forward declaration and its definition are one type, wherever each sits in the scope (the definition may even come first), and they must use the same keyword: `union Payload` followed by `struct Payload { ... }` is an error, with a fix-it to the definition's keyword. A type that is only forward-declared and never defined can be used through a pointer only: a field, base or variable holding it by value is an error, since its size is unknown. Forward declarations also work inside a class body, with or without a trailing `;`: ```kairo class Queue { struct Cell; var head: unsafe *Self::Cell struct Cell { var seq: u64 } } ``` --- ## No Extends Unions do not support [`extend` blocks](/docs/language/extends/). They are raw memory overlays with no behavior adding methods would blur the line between unions and [classes](/docs/language/classes/). If you need methods on overlapping data, wrap the union in a struct or class and add behavior there. --- ## No Inheritance Unions do not support `derives`. They cannot inherit from or be inherited by other types. --- ## Summary ```kairo // Basic union union Color { var rgba: u32 var channels: [u8; 4] } var c: Color c.rgba = 0xFF0000FF c.channels[0] // 0xFF (on little-endian) // Generic union union Reinterpret { var a: A var b: B } var bits: Reinterpret bits.a = 3.14f32 std::io::println(f"bits of 3.14: 0x{bits.b:X}") // Nested in a struct struct HardwareRegister { var address: usize var value: RegValue } union RegValue { var raw: u32 var fields: RegFields } struct RegFields { var low: u16 var high: u16 } var reg: HardwareRegister reg.address = 0x4000_0000 reg.value.raw = 0xDEAD_BEEF reg.value.fields.low // 0xBEEF (little-endian) reg.value.fields.high // 0xDEAD (little-endian) ``` --- ## See also - [ADT Enums](/docs/language/enums-adt/) - [Structures](/docs/language/structures/#memory-layout) - [Attributes](/docs/language/attributes/#layout-attributes) - [Unsafe](/docs/language/unsafe/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Classes](/docs/language/classes/) - [Generics](/docs/language/generics/) --- ## Interfaces URL: https://www.kairolang.org/docs/language/interfaces/ # Interfaces Interfaces define a set of method signatures that a type must satisfy. An interface used as a bound is zero-cost: it is checked at compile time and leaves nothing in the binary. Using an interface for runtime dispatch, via a witness table, is described in [Virtual Interfaces](#virtual-interfaces). A type conforms to an interface if it has all the required methods with matching signatures, whether or not it explicitly declares conformance. For runtime polymorphism over a class hierarchy, use a base [class](/docs/language/classes/) with `virtual` methods and dispatch through a base pointer. Interfaces and virtual dispatch solve different problems and can be used together on the same type. ## In this section - [Interface Requirements](/docs/language/interfaces-requirements/): operators, constructors, static methods, and `Self` return types in interfaces. --- ## Declaration ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } ``` An interface body contains method signatures (including generic methods), static function signatures, operator signatures, constructor requirements, and [associated types](#associated-types). It has no method bodies, variables, constants, or nested classes, structs, enums or interfaces. Every member is implicitly `pub` the `priv` and `prot` modifiers are compile errors on interface members. Explicit `pub` is permitted but has no effect. An interface must have at least one requirement, declared or derived. An empty interface is a compile error: conformance is structural, so every type would satisfy it, and it would constrain nothing. --- ## Conformance A type declares interface conformance with `impl` on a [class](/docs/language/classes/) or through `extend ... impl` on a [struct](/docs/language/structures/), [enum](/docs/language/enums/), or class. The compiler verifies at declaration time that all required methods are present with matching signatures: ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } class Document impl Serializable { var content: string var size: i32 fn Document(self, content: string, size: i32) { self.content = content self.size = size } fn serialize(const self) -> string { return self.content } fn byte_size(const self) -> i32 { return self.size } } ``` > [!NOTE] > Conformance is structural, not nominal. A type that has all the required methods with matching signatures satisfies the interface implicitly. The check happens at the point of use. See [Structural conformance](#structural-conformance) section below for details. For structs and enums, conformance goes through `extend`: ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } struct Point { var x: f64 var y: f64 } extend Point impl Serializable { fn serialize(const self) -> string { return f"{self.x},{self.y}" } fn byte_size(const self) -> i32 { return 16 // two f64s } } ``` See [Extends](/docs/language/extends/) for the full `extend` system. ### Structural conformance Explicit `impl` is not required. A type that has all the required methods with matching signatures satisfies the interface implicitly. The check happens at the point of use: ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } class Logger { fn serialize(const self) -> string { return "log" } fn byte_size(const self) -> i32 { return 3 } } // Logger never mentions Serializable, but satisfies it structurally fn write_to_disk(data: T) -> i32 { return data.byte_size() } fn main() -> i32 { write_to_disk(Logger()) // compiles: Logger has serialize() and byte_size() return 0 } ``` The difference between explicit and implicit conformance is when the check happens at declaration time (`class Foo impl Bar`) or at first use (`fn `). The runtime behavior is identical. ### Signature matching A generic method requirement is matched by a method with the same number of generic parameters and the same bounds, whose signature is identical once its parameters are renamed: `fn liz(self)` satisfies `fn liz(self)`. ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } interface Sink { fn push(self, item: T) } class Buffer impl Sink { fn push(self, item: U) { } // ok: same shape, U renamed from T } ``` --- ## Generic Interfaces Interfaces can declare type parameters: ```kairo interface Container { fn add(self, item: T) fn get(const self, index: i32) -> T fn size(const self) -> i32 } class IntPair impl Container { var items: [i32; 2] var count: i32 fn IntPair(self) { self.count = 0 } fn add(self, item: i32) { self.items[self.count] = item self.count += 1 } fn get(const self, index: i32) -> i32 { return self.items[index] } fn size(const self) -> i32 { return self.count } } ``` Type parameters on interfaces can have [constraints](/docs/language/generics/#type-parameter-constraints): ```kairo interface Comparable { fn op <(const self, other: Self) -> bool } class Base { } interface Registry { fn lookup(const self, key: T) -> U fn store(self, key: T, value: U) } ``` Generic defaults are not permitted on interface type parameters. (An [associated type](#associated-types) may have a default; that is a different thing, chosen by the conforming type rather than by the user of the interface.) See [Requires Clauses](/docs/language/requires/) for the full constraint system. --- ## Associated Types An interface can require a type member. A conforming type supplies it with a type alias: ```kairo interface Graph { type Node type Edge fn edges(const self, n: Self::Node) -> [Self::Edge] } class RoadMap impl Graph { type Node = CityId type Edge = Road fn edges(const self, n: CityId) -> [Road] { ... } } ``` Inside the interface (and inside a conforming type's body), name it `Self::Node`; a bare `Node` resolves too, but warns, with a fix-it that inserts `Self::`. A generic body names it through its parameter: `T::Node`. Associated types can carry bounds, and can themselves be generic: ```kairo interface Store { type Map fn index(const self) -> Self::Map } ``` A generic body names a generic associated type with its arguments: `T::Map`. A conformer supplies it with a generic alias of the same arity (`type Map = HashMap`); an alias with a different number of parameters does not supply it. An argument must meet the bounds of the parameter it fills (`T::Map` needs `K impl Hashable`). A bound on an associated type is written with `impl`, and several are separated by commas. The type a conformer supplies must satisfy each of them: ```kairo interface Catalog { type Item impl Display type Key impl Hashable, Comparable fn lookup(const self, k: Self::Key) -> Self::Item } ``` A generic body uses a value of an associated type through the associated type's own bounds, exactly as it uses a value of a bounded parameter: with `type Item impl Display`, `x.show()` on `x: T::Item` is a call to `Display`'s `show`. The same holds for everything else named through it: a static requirement (`T::Item::make()`), an associated type one of its bounds declares (`T::Item::Inner`, at any depth), an operator (`a == b` needs an `op ==` requirement in one of its bounds) and a conversion or interpolation. A member none of its bounds declares is a compile error, and an associated type with no bound has no members. A bound may name `Self`, another associated type or the interface's own parameter (`type Item impl Has`); it is read for the type the body named it through (`Has` for `T::Item`). Associated types are declared only inside an interface. Outside one, a `type` declaration is an alias and needs `=`. ### Defaults An associated type may have a default: ```kairo interface Indexed { type Index = usize fn at(const self, i: Self::Index) -> i32 } ``` The default applies only when a type conforms explicitly, with `impl` on its declaration or through `extend ... impl`, and doesn't declare the type itself. Structural conformance never uses defaults: a type that satisfies an interface implicitly must declare every associated type. A default may refer to `Self` and to associated types declared before it in the same interface. Defaults resolve in declaration order; a forward reference, and therefore any cycle, is a compile error: ```kairo interface WeightedGraph { type Node type Edge = (Self::Node, Self::Node) // ok: Node is declared earlier // type Cost = Self::Weight // compile error: Weight is declared later type Weight } ``` A default must satisfy its own bounds. This is checked once, at the interface declaration, with `Self` abstract, not separately for each conforming type. ### Associated types and inheritance A derived interface may give an inherited associated type a default if it has none. It may not change a default that is already given; otherwise which default applies would depend on the inheritance path. For the same reason, a type that declares two interfaces giving one inherited associated type different defaults takes neither: it must declare the type itself, or its conformance is a compile error. The derived interface's line is the inherited associated type, not a new one: `Self::Node` inside it names the base's, and a type that conforms to the derived interface explicitly gets the default. Restating the inherited type without a default, giving it bounds of its own, or changing a default the base already gives is a compile error. An associated type inherited from a generic interface is the one at the arguments the derived interface names: in `interface IntSource derives Source`, `S::Item` for `S impl IntSource` is `Source`'s `Item`. ### Name collisions between bounds Associated types belong to their interface. If `Graph` and `Tree` both declare `Node`, then for the same `T`, `Graph`'s `Node` and `Tree`'s `Node` are different types. In a body bounded by both, `T::Node` is ambiguous and is a compile error; it must be written with a qualified form that names the interface. The qualified syntax is not fixed yet. It is needed only when the names collide. --- Operator, constructor, static method, and `Self` requirements are covered in [Interface Requirements](/docs/language/interfaces-requirements/). --- ## Interface Inheritance Interfaces can inherit from other interfaces with `derives`. A type that conforms to the derived interface must satisfy all inherited interfaces as well: ```kairo interface Readable { fn read(self, buffer: [byte], count: i32) -> i32 } interface Seekable { fn seek(self, position: i64) fn tell(const self) -> i64 } interface Stream derives Readable, Seekable { fn close(self) fn flush(self) } ``` A class that `impl Stream` must provide `read`, `seek`, `tell`, `close`, and `flush`: ```kairo interface Readable { fn read(self, buffer: [byte], count: i32) -> i32 } interface Seekable { fn seek(self, position: i64) fn tell(const self) -> i64 } interface Stream derives Readable, Seekable { fn close(self) fn flush(self) } class FileStream impl Stream { var fd: i32 var pos: i64 fn FileStream(self, fd: i32) { self.fd = fd self.pos = 0 } fn read(self, buffer: [byte], count: i32) -> i32 { return 0 } fn seek(self, position: i64) { self.pos = position } fn tell(const self) -> i64 { return self.pos } fn close(self) { self.fd = -1 } fn flush(self) { } } ``` Interface inheritance is purely additive the derived interface's requirements are the union of its own methods and all inherited methods. There is no diamond problem because interfaces carry no implementation or state. Associated type defaults follow a rule that keeps it that way; see [Associated types and inheritance](#associated-types-and-inheritance). Multiple inheritance is permitted: ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } interface Printable { fn print(const self) -> string } interface Loggable derives Serializable, Printable { fn log_level(const self) -> i32 } ``` ### Composing interfaces A `derives` clause is an expression over interfaces. It combines their requirements as sets: | Operator | The derived interface requires | |---|---| | `X + Y` | everything `X` or `Y` requires (union) | | `X - Y` | what `X` requires, minus anything `Y` also requires (difference) | | `X & Y` | only what both require (intersection) | `derives A, B` is the same as `derives A + B`. Parentheses group, and `+` and `-` bind tighter than `&`: `A + B & C` is `(A + B) & C`. Writing `&` next to `+` or `-` without parentheses is a warning. ```kairo interface Readable { fn read(self) -> i32 } interface Seekable { fn seek(self, at: i64) } interface Closable { fn close(self) } interface Cursor derives (Readable + Seekable + Closable) - Closable { } // read and seek interface Shared derives Readable & Stream { } // read: in both ``` More requirements make an interface harder to satisfy, so `X + Y` is the stricter interface and `X & Y` the looser one. There is no `|`, no `^`, and no complement: a requirement set has nothing to take a complement against. A single member can't be removed by name; declare an interface with that member and subtract it. Two requirements are the same requirement when they have the same name, the same receiver (none, `self` or `const self`), the same generic parameters with the same bounds, and the same parameter types. The return type is not part of that identity: - In a union, the same requirement from two sides is one requirement. Two with the same name and different parameters are both kept, as overloads. The same requirement with two different return types is a compile error. - `-` and `&` match requirements by that identity alone, whatever they return. - Generic bounds count: `fn process(self, v: T)` and `fn process(self, v: T)` are different requirements, so subtracting the second from an interface that has the first keeps it. [Associated types](#associated-types) are matched by name: - In a union, two `type Item`s are one associated type whose bounds are the bounds of both. If both give a default and the defaults differ, that's a compile error. - `-` removes the associated type by name. If the result keeps a method whose signature names it (`Self::Item`), that's a compile error: nothing would supply the type. - `&` keeps it when both sides declare it, with only the bounds both state. A composed interface is an ordinary interface: a type conforms to it structurally, by having every requirement in the result, and a requirement that was subtracted is not required. If the result has no requirements, the interface is a compile error. --- ## Using Interfaces as Bounds The primary use of interfaces is constraining [generic type parameters](/docs/language/generics/) with `impl`: ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } fn write_file(path: string, text: string) { } fn save(data: T, path: string) { var text = data.serialize() write_file(path, text) } ``` `impl` checks structural conformance the type satisfies the interface's required method signatures. This is distinct from `derives`, which checks class inheritance. See [Requires Clauses](/docs/language/requires/) for the full constraint system. ```kairo interface Serializable { fn serialize(const self) -> string fn byte_size(const self) -> i32 } class Base { } fn save(data: T) -> i32 { return data.byte_size() } // T has serialize() and byte_size() fn process(data: T) { } // T is a subclass of Base ``` --- ## Generic Bodies Inside `fn `, a value of type `T` supports exactly what `Foo` (and every interface it derives) declares, plus destruction and move, which every type parameter has unless it opts out (see [Implicit capabilities](/docs/language/generics/#type-parameter-constraints)). - `x.method()` resolves against `Foo`'s methods. - A generic method requirement is called with explicit arguments, `x.liz()`, or with deduced ones. - `T(args)` constructs a `T`; it requires a constructor requirement taking those arguments in some bound (see [Constructors in Interfaces](/docs/language/interfaces-requirements/#constructors-in-interfaces)). - `var x: T` with no initializer requires a constructor requirement `fn Foo(self)` in some bound. - An operator on `x` (`x == y`, `x + y`, `-x`, `x += y`, `x[i]`, and the `!=`, `<` or `+` derived from `op ==`, `op <=>` or `op +=`), `x as string` and `f"{x}"` resolve against the bounds' requirements (`fn op ==(const self, other: Self) -> bool`, `fn op as(const self) -> string`, `fn repr(const self) -> string`) and call them through the bound. An operator on a `T derives Base` resolves against `Base`'s operators too (its own, its bases' and its extensions'), and calls the base's operator directly. With no requirement that grants it, each is a compile error in the generic (R051E for an unbounded `T`, R025E when no bound declares it), even if every type it is used with has the operator. A base operator whose parameter is the base by value (`fn op ==(self, o: Base)`) does not take a `T`, as it does not take a derived class's value. - `T` is never nullable: `x?`, `x == null` and `unwrap!(x)` are errors (write the parameter as `T?`). `===` on a `T?` compares the values with the bounds' `op ==`. - `match x` can bind `x` (`case var v`), guard it (`case var v where ...`) or ignore it (`case _`, `default`). A variant, literal, range, tuple or struct pattern is an error: no bound gives `T` variants or values to compare. - `T::Name` names an [associated type](#associated-types). A value of it has nothing but what the associated type's own bounds declare. `T::Name()` / `T::Name{}` builds one only through a constructor requirement in one of those bounds (`type Node impl Default`); a field list (`T::Name{x: 1}`) never compiles, since no bound can promise fields. Nothing else is available, and the body is checked once against its bounds, never per instantiation. ```kairo interface Shape { fn area(const self) -> f64 } fn describe(s: T) -> f64 { var a = s.area() // ok: declared by Shape // s.perimeter() // compile error: Shape declares no perimeter() // var t: T // compile error: no bound requires a default constructor return a } ``` > [!NOTE] > The current compiler does not report `var x: T` without a constructor bound yet. See [Status](/docs/status/#not-diagnosed). See [Generic Classes](/docs/language/generics/#type-parameter-constraints) for the implicit destroy and move capabilities and how instantiation reports them. --- ## Virtual Interfaces An interface declared `virtual interface` can also be used for runtime dispatch. A pointer to it, `*Heap`, can point at a value of any conforming type; calls through the pointer go through a witness table built for each conforming type, so the caller doesn't need to know at compile time which type it holds: > [!NOTE] > Virtual interfaces are not compiled yet. See [Status](/docs/status/#not-compiled-yet). ```kairo virtual interface Heap { fn alloc(self, size: usize, align: usize) -> unsafe *u8 fn free(self, ptr: unsafe *u8, size: usize) } class LibcHeap impl Heap { fn alloc(self, size: usize, align: usize) -> unsafe *u8 { return &null } fn free(self, ptr: unsafe *u8, size: usize) { } } fn release(heap: *Heap, ptr: unsafe *u8, size: usize) { heap->free(ptr, size) // dispatched through LibcHeap's (or any conformer's) witness table } ``` A virtual interface is still an ordinary interface when used as a bound: `fn ` is checked at compile time and costs nothing. The witness table is paid for only where the interface is used for runtime dispatch. --- ## Declaration Scope Interfaces must be declared at module scope. They cannot be nested inside classes, structs, enums, or other interfaces: ```kairo interface Valid { fn check(const self) -> bool } class Outer { // interface Invalid { ... } // compile error: interfaces cannot be nested } ``` See [Modules](/docs/language/modules/) for module organization. --- ## No Default Implementations Interface methods have no bodies. Every method is a requirement that the conforming type must fulfill: ```kairo interface Hashable { fn hash(const self) -> u64 // fn hash(const self) -> u64 { return 0 } // compile error: no default implementations } ``` This keeps interfaces as zero-cost contracts. There is no method resolution order, no inheritance of behavior, and no hidden dispatch when an interface is used as a bound. If you need shared implementation, use a base [class](/docs/language/classes/) with `derives`. --- ## No Variables or Constants Interfaces cannot declare variables, constants, static variables, or eval bindings: ```kairo interface Invalid { // var x: i32 // compile error // const Y: i32 = 10 // compile error // static z: i32 = 0 // compile error fn valid_method(self) // ok } ``` --- ## Interfaces From a Class (Planned) Today an interface is always written by hand, even when it only restates the methods a class already has. Once the attribute system is complete, the standard library will provide a way to generate an interface from a given class, so a class's public surface can be turned into a bound without copying every signature. ## Summary ```kairo // Basic interface interface Drawable { fn draw(const self) -> string fn width(const self) -> f64 } interface Comparable { fn op <(const self, other: Self) -> bool } // Generic interface with constraints interface SortedContainer { fn insert(self, item: T) fn min(const self) -> T fn max(const self) -> T } // Interface with operators interface Arithmetic { fn op +(self, other: Self) -> Self fn op -(self, other: Self) -> Self fn op ==(const self, other: Self) -> bool } // Interface inheritance interface Flushable { fn flush(self) } interface BufferedWriter derives Flushable { fn write(self, data: [byte]) fn buffer_size(const self) -> i32 } // Class conformance class Renderer impl Drawable { fn draw(const self) -> string { return "rendering" } fn width(const self) -> f64 { return 100.0 } } struct Point { var x: f64 var y: f64 } // Struct conformance via extend extend Point impl Drawable { fn draw(const self) -> string { return f"({self.x}, {self.y})" } fn width(const self) -> f64 { return 0.0 } } // Generic bound fn total_width(items: [T;]) -> f64 { var total = 0.0 for item in items { total += item.width() } return total } ``` --- ## See also - [Interface Requirements](/docs/language/interfaces-requirements/) - [Generics](/docs/language/generics/) - [Requires Clauses](/docs/language/requires/) - [Requires on Interfaces](/docs/language/requires/#requires-on-interfaces) - [What where Cannot Do](/docs/language/where/#what-where-cannot-do) - [Extends](/docs/language/extends/) - [Classes](/docs/language/classes/) - [Classes: Inheritance](/docs/language/classes-inheritance/) A builtin type meets an operator requirement through its own operator when the shapes match (operands `Self`, the requirement's result with `Self` substituted): `i32` meets `fn op +(const self, o: Self) -> Self`, `fn op <(const self, o: Self) -> bool` and `fn op <=>(const self, o: Self) -> Ordering`, and `op +=` when it has `+`. A requirement the type does not have built in, such as `bool + bool`, is SC162E. --- ## Type System URL: https://www.kairolang.org/docs/language/type-system/ # Type System Kairo is statically typed with full type inference. Every value has a single concrete type known at compile time. The type system is nominal two types are the same if they have the same name and generic arguments, not if they happen to have the same structure. ## In this section - [Type Aliases](/docs/language/type-aliases/) --- ## Type Aliases Type aliases are covered in [Type Aliases](/docs/language/type-aliases/). --- ## Type Inference The compiler infers types from initializers, return expressions, and generic arguments. Explicit annotations are optional where inference succeeds. ### Variable inference ```kairo var x = 42 // i32 var y = 3.14 // f64 var z = "hello" // string var v = [1, 2, 3] // [i32] var p = (1.0, true) // (f64, bool) ``` See [Primitives](/docs/language/primitives/) for default literal types. ### Generic argument inference [Generic type arguments](/docs/language/generics/) are inferred from the arguments at the call site: ```kairo fn identity(x: T) -> T { return x } identity(42) // T inferred as i32 identity("hello") // T inferred as string ``` This extends to complex generic patterns: ```kairo fn first(items: [T]) -> T { return items[0] } var nums: [i32] = [1, 2, 3] first(nums) // T inferred as i32 from [T] matching [i32] ``` Explicit generic arguments are required only when inference is ambiguous or when no arguments provide type information: ```kairo var s = Stack() // no arguments to infer from, must specify ``` ### Return type inference Return types are never inferred for block-bodied functions or forward declarations. They must be declared explicitly, or they default to `void`: ```kairo fn add(a: i32, b: i32) -> i32 { return a + b } // explicit fn log(msg: string) { std::io::println(msg) } // defaults to void ``` Expression-bodied functions (`fn foo() = expr`) are the one exception: if the return type annotation is omitted, it is inferred from the expression. ```kairo fn square(x: i32) = x * x // inferred as i32 fn name() = "Kairo" // inferred as string fn typed(x: i32) -> i64 = x as i64 // explicit still allowed ``` See [Functions](/docs/language/functions/#expression-bodied-functions) --- ## Implicit Conversions Kairo minimizes implicit conversions. The following are the only implicit conversions in the language: ### Numeric widening Integer and float types can be implicitly widened to a larger type of the same signedness: ```kairo var a: i32 = 42 var b: i64 = a // ok: i32 to i64 var x: f32 = 1.0f32 var y: f64 = x // ok: f32 to f64 ``` Narrowing conversions require an explicit `as` cast. See [Casting](/docs/language/casting/). ### Integer widening into C/C++ parameters An argument to an [imported C/C++ function](/docs/language/c-cpp-calling/#argument-conversions) widens into a `size_t`/`ptrdiff_t` parameter when no 32- or 64-bit target could lose a value: ```kairo // buf.h: void buf_reserve(size_t n); ffi "c" import "buf.h" fn grow(n: u32) { buf_reserve(n) // ok: u32 to usize (size_t) } ``` `u64` to `usize` still needs `as`, because it narrows on 32-bit targets; on 16-bit targets `u32` to `usize` does too. The full rule is in the [Conversion Lattice section 4.1](/docs/language/conversion-lattice/#41-the-cc-boundary). ### `T` to `T?` - Non-nullable to Nullable A non-nullable value is implicitly convertible to its nullable counterpart: ```kairo fn maybe_log(msg: string?) { ... } var s = "hello" maybe_log(s) // string implicitly converts to string? ``` The reverse (`T?` to `T`) requires explicit unwrapping see [Variables](/docs/language/nullables/#nullable-types). ### Derived-to-base pointer A pointer to a [derived class](/docs/language/classes-inheritance/#inheritance) is implicitly convertible to a pointer to its base class: ```kairo class Animal { ... } class Dog derives Animal { ... } fn feed(animal: *Animal) { ... } var dog = Dog("Rex", "Labrador") feed(&dog) // *Dog implicitly converts to *Animal ``` This is always safe the base subobject is at a known offset. The reverse (base-to-derived) requires an explicit cast because it can fail at runtime. See [Casting](/docs/language/casting/). ### List literal to a container A [list literal](/docs/language/collections/#list-literals) takes the type its target asks for: an array `[T; N]` with a matching element count, a slice `[T;]`, or a vector `[T]`. With no target it is an array. ```kairo fn total(xs: [i32;]) -> i32 { ... } total([1, 2, 3]) // the literal becomes a slice for this call var v: [i32] = [1, 2, 3] // the literal becomes a vector ``` This applies to the literal only. Array and vector variables convert only to a slice, below. ### Array or vector to slice An array `[T; N]` converts to a slice `[T;]` implicitly. The slice is a view of the array; nothing is copied. A `const` array converts only to `[const T;]`. A vector `[T]` also converts to a slice implicitly. ```kairo fn total(xs: [i32;]) -> i32 { ... } var a = [1, 2, 3] total(a) // a viewed as [i32;] var v: [i32] = [4, 5] total(v) // v viewed as [i32;] ``` The other direction, `[T;]` to `[T]`, stays explicit because it allocates. ### `@implicit` conversion operators A type's `op as` marked `@implicit` applies without `as` where its exact result type is wanted. See [Implicit `op as`](/docs/language/operator-overloading/#implicit-op-as). ### No other implicit conversions The following conversions are all explicit (require `as`): - [Enum to integer or integer to enum](/docs/language/casting/#enum-casts) - `T?` to `T` (use `unwrap!()`, `??`, or null checking) - [Base-to-derived pointer (downcast)](/docs/language/casting/#downcasting-base-to-derived) - Any pointer to a different pointer type - Integer narrowing or float-to-integer - Slice to vector (`s as [T]`; it allocates) --- ## Subtyping Kairo has a limited subtyping hierarchy: - `!` (never type) is a subtype of every type - A derived class is a subtype of its base class(es) Interface-satisfying types are not subtypes of the interface. [Interfaces](/docs/language/interfaces/) are constraints checked at compile time via `impl` bounds, not runtime-dispatchable types. For runtime polymorphism, use base class pointers with [virtual dispatch](/docs/language/classes-inheritance/#virtual-dispatch) or `unsafe *void` for type-erased pointers. --- ## The Never Type (`!`) `!` is the return type of functions that never return: they crash, loop forever, or call a no-return function. A `-> !` function cannot [panic](/docs/language/panic/#panic-and-no-return-): ```kairo fn fatal(msg: string) -> ! { std::io::println(msg) crash!() } ``` `!` is a subtype of every type, making it valid in expression contexts: ```kairo var x: i32 = if valid => compute() else => fatal("bad state") ``` `!` can only appear as a function return type. It cannot be used as a variable type, type parameter, or in any other type position: ```kairo // var x: ! // compile error // var y: Foo // compile error ``` See [Functions](/docs/language/functions/#no-return-) for no-return function semantics. --- ## Void - The Absence of a Value - Unit Types `void` represents the absence of a value. It is the default return type for functions with no explicit return type. `void` can be used as a type parameter, but can not be used as a variable type: ```kairo var handle: unsafe *void = get_opaque_handle() var safe_handle: *void = get_tracked_handle() var y: Foo // valid - ok var x: void // compile error ``` See [Primitives](/docs/language/primitives/#void) for details. --- ## Nullable Types in the Type System `T?` is syntactic sugar for the built-in `Nullable`, which holds a `T` or `null` (the one value of the empty type `null_t`). It is constructed only from a `T` or from `null`, which is what the implicit conversions `T` to `T?` and `null` to `T?` do. `Nullable` is not directly usable as a type name use the `?` suffix: ```kairo var x: i32? = 42 var y: string? = null ``` ### Nested nullables `T??` is a parser error because `??` is the [null-coalescing operator](/docs/language/nullables/#null-coalescing-). Use parentheses for nested nullables: ```kairo // var x: i32?? // parse error: ?? is an operator var x: (i32?)? = null // ok: Nullable> ``` Nested nullables are rarely useful. If you find yourself writing `(T?)?`, reconsider the data model. See [Variables](/docs/language/nullables/#nullable-types) for null checking, safe access, and unwrapping. --- ## Tuple Types Tuples are fixed-size, heterogeneous, ordered groups of values: ```kairo var point: (f64, f64) = (1.0, 2.0) var record: (i32, string, bool) = (42, "answer", true) ``` Single-element tuples do not exist. `(T)` is just `T` the parentheses are grouping, not a tuple constructor: ```kairo var x: (i32) = 42 // same as var x: i32 = 42 ``` There is no unit type or empty tuple `()`. Functions that return nothing use `void`. See [Primitives](/docs/language/collections/#tuples-t1-t2-) for tuple syntax and [Variables](/docs/language/variables/#destructuring) for tuple destructuring. --- ## Function Types Function pointer types are written as `fn(ParamTypes) -> ReturnType`: ```kairo var add: fn(i32, i32) -> i32 = fn (a: i32, b: i32) -> i32 { return a + b } var log: fn(string) -> void = std::io::println ``` The [`panic` modifier](/docs/language/panic/#the-panic-specifier) can appear on function types to indicate the function may panic. On a function type it must name the panic set, `panic(E1, E2)`: a type has no body to infer the set from. Callers must handle the panic via `try`/`catch`: ```kairo struct ParseError { var input: string fn op panic (const self) -> string { return f"cannot parse {self.input}" } } var risky: fn(i32) panic(ParseError) -> i32 = some_panicking_function try { risky(42) } catch e { // handle } ``` A function converts to a panicking function type when its own set is a subset of the type's; a function that doesn't panic converts to any of them. See [Declared Panic Sets](/docs/language/panic/#declared-panic-sets). `unsafe` before `fn` makes the type a **raw function pointer**: `unsafe fn(ParamTypes) -> ReturnType` is a plain C function pointer, one machine word, called directly. A `fn(...)` value can also hold a closure that captures variables; a raw one cannot, so only a named function or a closure that captures nothing converts to it: ```kairo fn twice(x: i32) -> i32 { return x * 2 } var raw: unsafe fn(i32) -> i32 = twice // ok var lit: unsafe fn(i32) -> i32 = fn (x: i32) -> i32 { return x + 1 } // ok: captures nothing var k = 3 // var bad: unsafe fn(i32) -> i32 = fn (x: i32) -> i32 { return x * k } // compile error: this closure captures, so it has no function pointer var f: fn(i32) -> i32 = raw // ok: a raw pointer converts to a fn value var g = twice as fn(i32) -> i32 // ok: the same conversion, written out // var back: unsafe fn(i32) -> i32 = f // compile error: a fn value may hold a capturing closure ``` Function pointer types imported from C and C++ are raw, and so are the `fn` parameters and result of an [`ffi "c"` function](/docs/language/c-cpp-exposing/). No other modifiers (`const`, `async`, `eval`) are valid on function pointer types. `const` is a property of methods (it constrains `self`), not of the function signature. `async` and `eval` require named function declarations. See [Functions](/docs/language/functions/#function-pointers) and [Closures](/docs/language/closures/) for function pointer usage. --- ## Collection Types Collection literal syntax maps to built-in types: | Syntax | Type | Description | |---|---|---| | `[T]` | Vector | Growable contiguous array that owns a heap copy of its elements (ptr + len + cap) | | `[T;]` | Slice | Non-owning view over contiguous elements (ptr + len) | | `[T; N]` | Array | Fixed-size, stored inline, `N` must be compile-time; not copyable or assignable | | `{K: V}` | Map | Hash map | | `{T}` | Set | Hash set | These are primitives in the type system, not generic library types. The standard library provides [type aliases](/docs/language/type-aliases/) for the explicit names: ```kairo // In module std: type Vector = [T] type Array = [T; N] type HashMap = {K: V} type HashSet = {T} ``` The literal syntax and the aliased names are interchangeable. A list literal `[a, b, c]` is an array `[T; 3]` unless its target is a slice or a vector. Arrays are not value types: they cannot be copied, assigned, passed by value, or returned. See [Primitives](/docs/language/collections/) for the full rules on arrays, slices, vectors, and list literals. `N` in `[T; N]` must be a compile-time evaluable expression. Runtime-dependent array sizes are not supported use `[T]` (vector) for dynamically sized collections: ```kairo eval SIZE = 256 var buffer: [u8; SIZE] // ok: SIZE is compile-time // var dynamic: [u8; runtime_val] // compile error: N must be compile-time ``` See [Eval](/docs/language/eval/) for compile-time evaluation rules. --- ## Typeof Identity Semantics `typeof` has dual behavior depending on whether it appears in a type position or an expression position: ### Type position In a type position, `typeof` resolves to the compile-time type of the expression: ```kairo var x = 42 var y: typeof x = 100 // typeof x resolves to i32 at compile time ``` ### Expression position In an expression position, `typeof` returns a `TypeInfo` object: ```kairo var x = 42 var info = typeof x info.get_pretty_name() // "i32" info.get_size() // 4 info.get_align() // 4 ``` ### TypeInfo `TypeInfo` is a built-in class that describes a type at runtime: ```kairo class TypeInfo { fn get_name(const self) -> string // mangled ABI name fn get_pretty_name(const self) -> string // human-readable (e.g. "HashMap") fn get_size(const self) -> usize fn get_align(const self) -> usize fn get_abi_format(const self) -> string // ABI format string for interop fn get_kind(const self) -> TypeKind } enum TypeKind { Primitive, Struct, Class, Enum, Union, Function, Interface, } ``` `get_name()` returns the [mangled name](/docs/language/c-cpp-abi/#name-mangling) following the platform's C++ ABI (Itanium on Unix and MinGW, MSVC on `*-windows-msvc`). `get_pretty_name()` returns a human-readable string including generic arguments. > [!IMPORTANT] > The `TypeInfo` API is still being finalized. Additional methods for querying members, base classes, and interface conformance may be added in a future update. ### Compile-time `typeof` `typeof` in `eval if` conditions is resolved at compile time: ```kairo fn process(x: T) { eval if typeof T == i32 { // only compiled when T is i32 fast_int_path(x) } else { generic_path(x) } } ``` See [Eval](/docs/language/eval/) for compile-time evaluation and [Control Flow](/docs/language/control-flow/#compile-time-branching) for `eval if`. --- ## Self `Self` is a type alias that resolves to the enclosing type. It is available in: - [Class](/docs/language/classes/#self-and-self) bodies and methods - [Interface](/docs/language/interfaces-requirements/#operators-in-interfaces) signatures - [Extend](/docs/language/extends/) blocks `Self` always refers to a reference to the type. For a pointer, use `*Self`. In a generic class `class Foo`, `Self` resolves to `Foo`: ```kairo class Hold { var value: T fn Hold(self, v: T) { self.value = v } fn replace(self, other: Self) { // Self is Hold self.value = other.value } } ``` `Self` is not available in free functions or at the top level. --- ## Type Identity Two types are the same if they have the same fully qualified name and the same generic arguments. This is nominal identity, not structural: ```kairo struct Point { var x: f64; var y: f64 } struct Vec2 { var x: f64; var y: f64 } // Point and Vec2 are different types despite identical structure // var p: Point = Vec2 { x: 1.0, y: 2.0 } // compile error ``` [Generic types](/docs/language/generics/) are identified by their monomorphized form. `Foo` and `Foo` are different types. `Foo` in one translation unit is the same type as `Foo` in another identity follows the platform's C++ ABI mangling rules. Type alias identity is covered in [Type Aliases](/docs/language/type-aliases/). --- ## Summary ```kairo // Type alias type Meters = f64 type Pair = (T, T) // Type inference var x = 42 // i32 var y = [1.0, 2.0] // [f64] fn id(x: T) -> T = x id(42) // T inferred as i32 // Implicit conversions var n: i64 = 42i32 // numeric widening var s: string? = "hello" // T to T? var a: *Animal = &Dog("Rex", "Lab") // derived-to-base pointer // Nullable var x: i32? = null var y = x ?? 0 // null coalescing // typeof var info = typeof x info.get_pretty_name() // "Nullable" var z: typeof x = 10 // type position: resolves to i32? // Function types var f: fn(i32) -> i32 = fn (x: i32) -> i32 { return x * 2 } var g: fn(i32) panic(ParseError) -> i32 = risky_fn // Collections var vec: [i32] = [1, 2, 3] var view: [i32;] = [1, 2, 3] var arr: [u8; 4] = [0, 0, 0, 0] var map: {string: i32} = {"a": 1} var set: {i32} = {1, 2, 3} ``` ## See also - [Type Aliases](/docs/language/type-aliases/) - [Primitives](/docs/language/primitives/) - [Casting](/docs/language/casting/) - [Nullables](/docs/language/nullables/) - [Collections](/docs/language/collections/) - [Generics](/docs/language/generics/) - [Implicit Conversions](/docs/language/casting-implicit/) - [Classes](/docs/language/classes/) --- ## Casting URL: https://www.kairolang.org/docs/language/casting/ # Casting All explicit type conversions in Kairo use the `as` keyword. There are no separate cast operators like C++'s `static_cast`, `dynamic_cast`, `reinterpret_cast`, and `const_cast` `as` handles all conversion categories, with safety determined by the source and target types. For implicit conversions (numeric widening, `T` to `T?`, derived-to-base pointers), see [Type System](/docs/language/type-system/#implicit-conversions). ## In this section - [Implicit Conversions](/docs/language/casting-implicit/): numeric widening and derived-to-base upcasts that need no `as` - [Conversion Lattice](/docs/language/conversion-lattice/): the normative rules for primitive conversions --- ## Numeric Casts Implicit widening is covered in [Implicit Conversions](/docs/language/casting-implicit/#widening). ### Narrowing (truncation) Narrowing conversions require an explicit `as`. The cast truncates by keeping the low bits of the source value: ```kairo var x: i64 = 1000 var y: i8 = x as i8 // truncates to low 8 bits: -24 var big: u32 = 0xDEADBEEF var small: u8 = big as u8 // 0xEF ``` Truncation never panics. The `as` keyword is the programmer explicitly accepting potential data loss. ### Float to integer Float-to-integer casts truncate toward zero, matching C++ behavior. Out-of-range values saturate instead of producing undefined behavior: ```kairo var f: f64 = 3.9 var i: i32 = f as i32 // 3 (truncates toward zero) var neg: f64 = -2.7 var n: i32 = neg as i32 // -2 var huge: f64 = 1.0e18 var s: i32 = huge as i32 // i32 max (2147483647) saturates ``` ### Integer to float Integer-to-float casts may lose precision for large values but never fail: ```kairo var x: i64 = 9007199254740993 // 2^53 + 1 var f: f64 = x as f64 // rounded f64 cannot represent this exactly ``` ### Signed/unsigned conversion Casting between signed and unsigned integers of the same width reinterprets the bit pattern: ```kairo var s: i8 = -1 var u: u8 = s as u8 // 255 (same bits, different interpretation) ``` --- ## Pointer Casts Implicit upcasting is covered in [Implicit Conversions](/docs/language/casting-implicit/#upcasting-derived-to-base). ### Downcasting (base to derived) Base-to-derived casts come in two forms: **Asserting downcast** crashes the program if the runtime type does not match, like [`unwrap!`](/docs/language/nullables/) on null. A failed cast is a programmer error, not a [panic](/docs/language/panic/#what-is-not-a-panic): it is in no panic set and no `try` can catch it, so the function needs no `panic` specifier. The compiler warns on every asserting downcast and offers a fix-it rewriting it to the checked form below: ```kairo fn process(animal: *Animal) { var *dog = animal as *Dog // crashes if animal is not a Dog // warning: use 'animal as *Dog?' and test the result dog->fetch() } ``` On a miss the program writes one line to stderr naming the cast, the target type, the pointer's static type and where the cast is (the source file's full path, line and column), then aborts (`SIGABRT`). The line is built at compile time, so nothing is formatted while crashing: ```text animal as *Dog: the object is not a 'Dog' (static type '*Animal') at /home/me/app/app.k:2:16 ``` A null pointer is not a miss: it stays null. **Checked downcast** returns a [nullable pointer](/docs/language/nullables/#pointers-and-nullability) `*Derived?` (a nullable pointer, `(*Derived)?`), which is null if the runtime type does not match: ```kairo fn process(animal: *Animal) { var *dog? = animal as *Dog? // null if animal is not a Dog if dog? { dog->fetch() } } ``` Both forms perform a runtime type check using the [vtable](/docs/language/classes-inheritance/#virtual-dispatch) (the class must have at least one `virtual` method), compiled to C++'s `dynamic_cast`. Downcasting a non-polymorphic class is a compile error. Inside a generic body, a pointee that is a type parameter works only with the checked form (`a as (*T)?`); the asserting form is an error there for now. **The CRTP downcast** is the one exception that needs no vtable. Inside a generic base whose parameter is bounded by `derives` on the base itself, `&self as *X` (or `*const X`) is allowed without `unsafe`: the bound proves every `X` derives the base, so the target is known statically, and the cast compiles to C++'s `static_cast`, which also adjusts the pointer when the base is not the first one: ```kairo class impl Weighted> Counter { fn dyn(self) -> *X { return &self as *X } // static, no vtable fn bump(self) -> i32 { return self.dyn()->weight() } } class Node derives Base, Counter impl Weighted { fn weight(const self) -> i32 { return 5 } } ``` The bound may also reach the source through a chain of bases (`X derives Stmts`, `Stmts derives Rav` lets a `*Rav` cast down to `*X`). The cast cannot drop `const`; without such a bound (none, an `impl` bound, or a `derives` bound naming another class) a pointer cast between unrelated types is still an error. As in C++, the cast trusts that the object really is an `X`: a class that names `Counter` for some other `Other` that derives `Counter` makes it undefined. ### Raw pointer cast Casting to `unsafe *T` reinterprets the pointer with no type checking equivalent to C++'s `reinterpret_cast`. The compiler performs no validation. The one exception is a cast between a class and one of its bases, in either direction (`unsafe *Derived as unsafe *Base`, or back). There the cast moves the pointer to the base subobject, exactly as the implicit upcast does, and compiles to C++'s `static_cast`. A first base usually sits at offset 0, so a plain reinterpret would happen to work for it; for any other base it would point into the wrong fields. The downcast is still unchecked: the caller vouches that the object really is the derived class. Casting a safe pointer to a raw pointer `*T as unsafe *U` requires an [`unsafe` block](/docs/language/unsafe/#unsafe-blocks). This is the point where [Tether](/docs/language/tether-bounds/#provenance-and-epochs) loses provenance: after the cast the compiler can no longer relate the pointer to the allocation it came from, so the loss is made visible at the source: ```kairo var ptr: *i32 = &some_value unsafe { var unsafe *raw = ptr as unsafe *void // provenance loss: safe pointer to raw var unsafe *back = raw as unsafe *i32 // reinterpret caller must ensure correctness } ``` Casting between `unsafe *T` types needs no `unsafe` block there is no provenance left to lose. The result is the same pointer value with a different type no runtime check, and no adjustment unless the two pointees are a class and its base (above). > [!CAUTION] > Raw pointer casts bypass Tether's safety guarantees. Casting to `unsafe *void` erases type information permanently the compiler cannot verify the correctness of a subsequent cast back. Use only for [C/C++ interop](/docs/language/c-cpp/), custom allocators, and other low-level scenarios. ### Pointer to integer Casting a pointer to an integer extracts the numeric address. This is safe and requires no `unsafe` block reading an address cannot violate memory safety on its own, and the resulting integer carries no provenance: ```kairo var ptr: *i32 = &some_value var addr = ptr as usize // ok: numeric address ``` `usize` is the only permitted target it is the one integer type guaranteed to hold a full address. Casting a pointer directly to any other integer is a compile error, not a warning, `u64` and `isize` included even on a target where they are as wide ([SC026E](/docs/language/diagnostics/), with a fix-it inserting `usize as`): silently discarding the high bits of an address is never what the programmer meant, and a cast that compiles on one target must not truncate on another. ```kairo // var truncated = ptr as u8 // compile error: cannot cast pointer to u8 var low = ptr as usize as u8 // ok: address, then explicit truncation ``` If you genuinely want the low byte of an address (tag bits, alignment checks), spell it as two casts. The second cast is an ordinary [numeric narrowing](#narrowing-truncation) and reads as deliberate. ### Integer to pointer Casting an integer to a pointer fabricates a pointer from a numeric address. The result must be an `unsafe` pointer safe pointers require provenance tracking that an integer cannot provide and the cast requires an [`unsafe` block](/docs/language/unsafe/#unsafe-blocks). The integer carries no provenance, so the cast invents one that Tether has no way to verify: ```kairo var addr: usize = 0x7FFE_0000_1000 unsafe { var unsafe *ptr = addr as unsafe *i32 // ok: fabricating provenance } // var bad = addr as *i32 // compile error: cannot create safe pointer from integer ``` This is the inverse of `ptr as usize`, and the asymmetry is deliberate: discarding provenance is harmless, inventing it is not. ### Pointer cast rules Every pointer cast is classified by what it does to *provenance* the compiler's knowledge of which allocation a pointer belongs to. Casts that discard provenance are safe; casts that create or fabricate it are not: | Cast | Status | Provenance | Why | |---|---|---|---| | `ptr as usize` | Allowed, no `unsafe` | Discarded | Reading an address cannot cause UB on its own | | `ptr as u8` (any narrower int) | **Compile error** | | Narrowing an address is never intended write `ptr as usize as u8` | | `n as unsafe *T` | Allowed, requires `unsafe` block | Fabricated | Tether cannot verify an address that came from an integer | | `n as *T` | **Compile error** | | Safe pointers require provenance an integer cannot supply | | `*T as unsafe *U` | Allowed, requires `unsafe` block | Lost | The provenance-loss point keep it visible | | `unsafe *T as unsafe *U` | Allowed, no `unsafe` | Already absent | Nothing left to lose | | `unsafe *Derived as unsafe *Base` (or back) | Allowed, as above | As above | Adjusted to the base subobject (`static_cast`), not reinterpreted | | `*Derived as *Base` | Implicit | Preserved | Same allocation, adjusted offset | | `*Base as *Derived` | Allowed, runtime check | Preserved | Vtable check, crashes (`as *Derived`) or yields null (`as *Derived?`) | | `&self as *X` in `class > B` | Allowed, no runtime check | Preserved | The `derives` bound proves the relation; compiled to `static_cast` | The two error rows are deliberate refusals rather than warnings. `ptr as u8` has an honest spelling (`ptr as usize as u8`) that says the same thing in two steps, and `n as *T` has no honest spelling at all a safe pointer's guarantees cannot be reconstructed from a number. `unsafe` blocks appear on exactly the rows where Tether stops being able to reason about the pointer. See [Unsafe](/docs/language/unsafe/#the-safety-boundary) for the boundary model and [Tether](/docs/language/tether/) for what provenance tracking buys. --- ## Enum Casts ### Plain enums [Plain enums](/docs/language/enums-plain/) can be cast to their underlying integer type and back: ```kairo enum Direction derives u8 { North = 0, East = 1, South = 2, West = 3, } var raw = Direction::North as u8 // 0 var dir = 2u8 as Direction // Direction::South ``` A plain enum is [closed](/docs/language/enums-plain/#closed-and-open-enums) unless it is declared `@open`, and casting an integer that is no variant's value into a closed enum fails: with a constant operand it is a compile error ([SC001E](/docs/language/diagnostics/#sc001e-a-constant-cast-into-a-closed-enum-is-no-variants-value)), otherwise the program crashes when the cast runs (a message and an abort, like a failed bounds check; no `try` catches it). The check is a compare on the integer before the cast (`v >= N` when the values are `0` to `N-1`), which the compiler drops when it can see the value. An `@open` enum, and every enum imported from C or C++, takes any value of its underlying type unchecked. The cast target must match the underlying type. `Direction::North as i32` requires the enum to be backed by `i32`, or an intermediate cast: `Direction::North as u8 as i32`. ### ADT enums [ADT enums](/docs/language/enums-adt/) cannot be cast to integers. The discriminant tag is an internal implementation detail. If you need the tag value, expose it through an [`extend` method](/docs/language/extends/): ```kairo enum ParseResult { Success { value: T, consumed: i32 }, Error { message: string }, EndOfInput, } // ParseResult::Success { ... } as u32 // compile error: ADT enums cannot be cast to integers extend ParseResult { fn tag(const self) -> u32 { return match self { case .Success => 0 case .Error => 1 case .EndOfInput => 2 } } } ``` --- ## Nullable to Non-Nullable Casting a nullable value `T?` to its underlying type `T` is a compile error: ```kairo var x: i32? = null // var y = x as i32 // compile error: cannot cast i32? to i32 // // use `x ?? ` or `unwrap!(x)` ``` There is no collapsing cast in Kairo. A cast that quietly produced a default-constructed value on null would fabricate a value the program never computed which is precisely what the nullable system exists to prevent. The null case has to be answered, not erased, and the two honest answers already have syntax: | Intent | Write | On null | |---|---|---| | Supply a fallback | `x ?? 0` | Yields the fallback | | Assert non-null | `unwrap!(x)` | Aborts the program (not catchable) | Both read at the call site as a decision about null. `x as i32` reads as a type conversion and hides one. ```kairo var count: i32? = lookup_count() var n = count ?? 0 // explicit: absent means zero var m = unwrap!(count) // explicit: absent is a bug, abort ``` See [Nullables](/docs/language/nullables/#nullable-types) for the rest of the nullable operations (`?.`, `??`, `unwrap!()`, null checking). --- ## User-Defined Conversions (`op as`) Types can define custom conversions by overloading the `op as` operator: ```kairo class Temperature { var celsius: f64 fn Temperature(self, c: f64) { self.celsius = c } fn op as(self) -> f64 { return self.celsius } fn op as(self) -> string { return f"{self.celsius}C" } } var temp = Temperature(100.0) var f = temp as f64 // 100.0 var s = temp as string // "100.0C" ``` `op as` can be overloaded for multiple target types. The compiler selects the overload based on the target type in the `as` expression, which must be exactly one overload's result: no second conversion follows a user one, so `x as f64` with only `op as -> i32` declared is an error. Two `op as` with the same target are one member declared twice. `op as` must take only `self` as a parameter and return the target type. In a generic class, `fn op as(self) -> T` converts to whatever the instance binds `T` to (`Wrap as i64`), and an interface may require several `op as`, one per target. Marking an `op as` with `@implicit` lets it apply without `as` where its exact result type is wanted. See [Implicit `op as`](/docs/language/operator-overloading/#implicit-op-as). See [Operators](/docs/language/operator-overloading/#special-operators) for the full operator overloading reference. ## Conversion Through a Constructor `x as T` is also a conversion when `T` declares a constructor with one parameter that accepts `x`'s type. The cast calls that constructor: ```kairo class Celsius { var value: f64 fn Celsius(self, v: f64) { self.value = v } } var c = 21.5 as Celsius // calls Celsius(21.5) ``` The standing example is [slice to vector](/docs/language/collections/#conversions-between-the-three). A vector has a constructor that takes a slice, so the cast copies the elements into a new vector: ```kairo var s: [i32;] = [1, 2, 3] var v = s as [i32] // allocates and copies ``` If the source type declares `op as` for `T` and `T` also has a matching constructor, `op as` wins. --- ## Cast Summary | Cast | Syntax | Safety | Behavior on failure | |---|---|---|---| | Numeric widening | Implicit | Safe | N/A | | Numeric narrowing | `x as i8` | Truncates | Low bits kept | | Float to int | `x as i32` | Truncates/saturates | Saturates on overflow | | Int to float | `x as f64` | May lose precision | Rounded | | Derived-to-base ptr | Implicit | Safe | N/A | | Base-to-derived ptr (asserting) | `ptr as *Derived` | Runtime check, warns | Crashes | | Base-to-derived ptr (checked) | `ptr as *Derived?` | Runtime check | Returns null | | Safe to raw pointer | `ptr as unsafe *T` | Requires `unsafe` block | Provenance loss | | Raw to raw pointer | `raw as unsafe *T` | No check | Reinterpret | | Raw pointer between class and base | `raw as unsafe *Base` | No check | Offset adjusted, like the implicit upcast | | Pointer to `usize` | `ptr as usize` | Safe | Address value | | Pointer to narrower int | `ptr as u8` | Compile error | Use `ptr as usize as u8` | | Integer to pointer | `n as unsafe *T` | Requires `unsafe` block | Fabricated provenance | | Plain enum to int | `e as u8` | Safe | Discriminant value | | Int to closed plain enum | `n as Direction` | Error (constant) / crash (runtime) if no match | Checked; declare `@open` to skip | | Int to `@open` or imported enum | `n as Signal` | Safe | Any value of the underlying type | | ADT enum to int | N/A | Compile error | Use `extend` method | | User-defined | `x as TargetType` | Depends on `op as` | Calls user code | | Through a constructor | `x as T` | Depends on the constructor | Calls `T`'s one-parameter constructor | | Slice to vector | `s as [T]` | Safe | Allocates and copies | | `T` to `T?` | Implicit | Safe | N/A | | `T?` to `T` | Not a cast | Compile error | Use `??` or `unwrap!()` | --- ## Casts Not in Kairo | C++ Cast | Kairo Equivalent | |---|---| | `static_cast(x)` | `x as T` | | `dynamic_cast(p)` | `p as *T?` (checked) or `p as *T` (asserting) | | `reinterpret_cast(p)` | `p as unsafe *T` | | `const_cast(p)` | Not supported `const` cannot be stripped at runtime | --- ## See also - [Implicit Conversions](/docs/language/casting-implicit/) - [Conversion Lattice](/docs/language/conversion-lattice/) - [Type System](/docs/language/type-system/#implicit-conversions) - [Pointers](/docs/language/pointers/) - [Unsafe](/docs/language/unsafe/) - [Enums](/docs/language/enums/) - [Nullables](/docs/language/nullables/) - [Operator Overloading](/docs/language/operator-overloading/) --- ## Requires Clauses URL: https://www.kairolang.org/docs/language/requires/ # Requires Clauses `requires` attaches compile-time constraints to declarations. A `requires` clause specifies a condition that must hold at compile time if it doesn't, the program does not compile. There is no runtime fallback, no dispatch, no branching. `requires` is a static gate. For runtime-conditional dispatch, see [Where Clauses](/docs/language/where/). | Property | Guarantee | |---|---| | Evaluation time | Compile time, always | | Memory safe | Yes | | Runtime cost | Zero | | Valid on functions | Yes | | Valid on types | Yes | | Valid on interface methods | Yes | | Valid on interfaces | Yes (constrains conforming types) | --- ## Basic Syntax A `requires` clause appears after the parameter list and return type, before the function body: ```kairo fn divide(a: i32, b: i32) -> i32 requires b != 0 { return a / b } ``` If the condition cannot be evaluated at compile time, the compiler emits a hard error: ``` error: requires expression is not compile-time evaluable --> src/math.k:1:32 1 | fn divide(a: i32, b: i32) -> i32 2 | requires b != 0 { | ^^^^^^ depends on runtime value 'b' note: for runtime-conditional dispatch, use 'where' ``` Multiple conditions are combined with boolean operators in a single expression: ```kairo fn safe_index(arr: [i32], i: i32) -> i32 requires i >= 0 && i < arr.length() { return arr[i] } ``` --- ## Compile-Time Expressions Any expression the compiler can evaluate statically is valid in a `requires` clause: | Expression | Example | |---|---| | `sizeof T` | `requires sizeof T <= 64` | | `alignof T` | `requires alignof T >= 16` | | Arithmetic and comparisons | `requires N > 0 && N <= 1024` | | `eval` variables and functions | `requires is_power_of_two(N)` | | Type trait checks | `requires T impl Comparable` | | `typeof` queries | `requires typeof T == i32` | If the expression depends on a runtime value, it belongs in a `where` clause, not `requires`. --- ## Type Constraints `impl` and `derives` bounds can appear in `requires` clauses as an alternative to inline bounds on type parameters. The compiler desugars them identically: ```kairo // These are equivalent: fn save(data: T) { ... } fn save(data: T) requires T impl Serializable { ... } ``` Either way, the bounds are all a generic body can rely on. The body is checked once, where it is defined, against its bounds, never per instantiation. Calling a method no bound declares is a compile error in the generic itself, even if every type it is ever instantiated with happens to have that method. See [Type parameter constraints](/docs/language/generics/#type-parameter-constraints) and [Generic Bodies](/docs/language/interfaces/#generic-bodies). The `requires` form is preferred when constraints are long or involve relationships between multiple type parameters: ```kairo fn convert(input: T) -> U requires T impl Serializable && U impl Deserializable { var bytes = input.serialize() return U::from_bytes(bytes) } ``` --- ## Requires on Types `requires` on a [class](/docs/language/classes/), [struct](/docs/language/structures/), or [enum](/docs/language/enums/) is checked at instantiation time. A violation is a hard compile error at the point of use: ```kairo class SmallBuffer requires sizeof T <= 128 { var data: [T; 16] } SmallBuffer() // ok: sizeof i32 == 4 SmallBuffer<[u8; 256]>() // compile error: sizeof [u8; 256] == 256, exceeds 128 struct Aligned16 requires alignof T >= 16 { var value: T } enum Compact requires sizeof T <= 8 { Some { value: T }, None, } ``` Type-level constraints are always `requires`. There is no runtime dispatch on type instantiation either the type is valid or it isn't. A member's `requires P impl I` gives its body `I`'s members on `P`; the member exists only on instances that meet it, and calling it on another instance is an error (SC153E). ### Partial specializations selected by `requires` A partial specialization may carry a `requires` clause: it is chosen for an instantiation only when its pattern matches and its clause holds there. Its pattern can be the type's own parameters: ```kairo struct Store { var value: T } struct

Store

requires sizeof P <= 8 { var small: P } // Store is this one struct

Store<*P> requires sizeof P >= 8 { var wide: *P } // Store<*i64> is this one ``` A pattern argument can be qualified: `class

V` is chosen for `V` with `P = i32`, and is more specialized than `V

`; `V<*const P>` is more specialized than `V<*P>`. The more specialized pattern wins first (`Store<*P>` over `Store

`); between two equal patterns, one with a clause wins over one without, and two with clauses that both hold are ambiguous (an error). The clause is decided at compile time from literals, `sizeof` and `alignof` of builtin types, pointers and arrays of them, arithmetic and comparisons. A clause the compiler cannot decide for an instantiation (the `sizeof` of a struct, an `eval` function) is an error where that instantiation is used, and a conformance (`requires P impl I`) in a partial's clause is not supported yet. --- ## Requires on Interface Methods `requires` on an [interface](/docs/language/interfaces/) method constrains what conforming types must satisfy. The conforming type must implement the method with an identical `requires` clause: ```kairo interface Accumulator { fn add(self, value: i32) -> Self requires value > 0 } class Counter impl Accumulator { var total: i32 fn Counter(self) { self.total = 0 } fn add(self, value: i32) -> Self requires value > 0 { self.total += value return self } } ``` Because interfaces are zero-cost structural contracts, `requires` is the only valid constraint keyword on interface members. `where` is not permitted runtime dispatch inside an interface method would violate the zero-cost guarantee. --- ## Requires on Interfaces A `requires` clause on an interface declaration constrains which types can conform. A type that does not satisfy the `requires` cannot implement the interface, even if it has all the required methods: ```kairo interface SmallStorable requires sizeof T <= 64 { fn store(self) -> [byte] fn load(data: [byte]) -> T } ``` This is distinct from `requires` on an individual method it applies to the entire interface as a precondition on conformance. --- ## Requires and eval `requires` expressions are evaluated by the same compile-time engine as `eval`. Any `eval` function or variable is usable in a `requires` clause: ```kairo eval fn is_power_of_two(n: i32) -> bool { return n > 0 && (n & (n - 1)) == 0 } fn clear_aligned(@inout buf: [u8; N]) requires is_power_of_two(N) { for i in 0..N { buf[i] = 0 } } var a: [u8; 256] var b: [u8; 300] clear_aligned<256>(&a) // ok: 256 is a power of two clear_aligned<300>(&b) // compile error: 300 is not a power of two ``` See [Eval](/docs/language/eval/) for compile-time evaluation rules. --- ## Requires and panic `requires` and [`panic`](/docs/language/panic/) serve different purposes and can coexist. `requires` filters invalid inputs before the function body executes. `panic` handles valid inputs that produce errors during processing: ```kairo struct PortRange { var port: i32 fn op panic (const self) -> string { return f"port {self.port} out of range" } } fn parse_port(input: string) panic -> i32 requires input.length() > 0 { var port = std::parse(input) if port < 0 || port > 65535 { panic PortRange { port: port } } return port } ``` The `requires` clause rejects empty strings at compile time (when the argument is a constant) or documents the precondition for the caller. The `panic` handles the runtime error case of a non-empty string that isn't a valid port. --- ## Summary ```kairo // Compile-time size constraint on a generic fn stack_alloc() -> T requires sizeof T <= 4096 { // ... } // Type constraint in requires clause fn transform(input: T) -> U requires T impl Readable && U impl Writable { // ... } // Requires on a class class InlineBuffer requires sizeof T <= 64 { var data: [T; 8] } // Requires on an interface method interface Validator { fn validate(self, input: string) -> bool requires input.length() > 0 } // Requires with eval function eval fn fits_in_cache_line(n: i32) -> bool = n <= 64 struct CacheAligned requires fits_in_cache_line(sizeof T) { var value: T } ``` ## See also - [Where Clauses](/docs/language/where/) - [Generics](/docs/language/generics/#type-parameter-constraints) - [Interfaces](/docs/language/interfaces/#using-interfaces-as-bounds) - [Compile-Time Eval](/docs/language/eval/) - [Panic](/docs/language/panic/) - [Generic Functions](/docs/language/functions/#generic-functions) --- ## Where Clauses URL: https://www.kairolang.org/docs/language/where/ # Where Clauses `where` attaches runtime-conditional constraints to function declarations. A `where` clause specifies a condition that is checked when the function is called; if it fails, execution falls through to the next matching overload. The compiler folds multiple `where`-constrained overloads into a single function with branch dispatch. For compile-time constraints, see [Requires Clauses](/docs/language/requires/). | Property | Guarantee | |---|---| | Evaluation time | Runtime | | Memory safe | Yes | | Thread safe | Yes | | Undefined behavior | No | | Requires unsafe | No | | Valid on functions | Yes | | Valid on types | No use `requires` | | Valid on interfaces | No interfaces are zero-cost, use `requires` | --- ## Basic Syntax A `where` clause appears after the parameter list and return type, before the function body: ```kairo ffi "c" import "math.h" // the C library's sqrt fn root(x: f64) -> f64 where x >= 0.0 { return sqrt(x) } fn root(x: f64) -> f64 { return 0.0 // fallback for negative input } ``` The overloads compile to one function, `root`, which tests the condition. If the condition holds, the constrained overload runs. If not, execution falls to the next candidate. Every caller, including C++ code calling `root`, calls that one function; the overloads' bodies are private to the file. Multiple conditions are combined with boolean operators: ```kairo fn safe_divide(a: i32, b: i32) -> i32 where b != 0 && a >= 0 { return a / b } fn safe_divide(a: i32, b: i32) -> i32 { return 0 // fallback } ``` --- ## Fallback Requirement Every `where`-constrained overload must have a fallback: an overload with no `where` clause, or `where` clauses the compiler can prove cover every remaining case. If no fallback exists, the compiler emits an error: ``` error: no fallback overload for 'root' when where condition fails --> src/math.k:1:1 1 | fn root(x: f64) -> f64 2 | where x >= 0.0 { note: add an overload without a 'where' clause to handle all remaining cases ``` The fallback is the compiler's guarantee that every call site has a valid code path. Conditions that compare integer parameters with constants (`x >= 0`, `x < 0`, joined with `&&`), test a `bool` parameter, or are `true`, can cover every value without a fallback; the last one is then never tested: ```kairo fn sign(x: i32) -> i32 where x >= 0 { return 1 } fn sign(x: i32) -> i32 where x < 0 { return -1 } // ok: every i32 is covered ``` Overloads with the same parameter types are dispatched together, and must agree on the return type and on receiver `const`-ness. An overload with a different parameter list is an ordinary overload and is not a fallback. [Generic](/docs/language/generics/) overloads dispatch together when their signatures are the same up to the names of their generic parameters, type and value parameters alike, and they must also name those parameters alike and have the same bounds. A condition may read a type parameter (`where sizeof T > 8`) or a generic value parameter (`where n > N` under ``); it is tested at run time like any other, and it is the same answer every time for one instantiation: ```kairo fn pick(x: T, n: i32) -> i32 where n > 0 { return 1 } fn pick(x: T, n: i32) -> i32 { return 2 } ``` --- ## Declaration Order Determines Priority When multiple `where`-constrained overloads exist for the same function, the compiler checks them in declaration order. The first satisfied condition wins. The unconstrained overload is always the final fallback: ```kairo fn categorize(x: i32) -> string where x > 100 { return "high" } fn categorize(x: i32) -> string where x > 0 { return "positive" } fn categorize(x: i32) -> string { return "non-positive" } ``` Conceptual codegen: ```kairo fn categorize(x: i32) -> string { if x > 100 { return "high" } else if x > 0 { return "positive" } else { return "non-positive" } } ``` Declaration order is the programmer's explicit priority control. The compiler does not attempt to determine which condition is "more specific": it chains them sequentially in the order they appear in source. The fallback is always tested last, wherever it is declared. Each condition is evaluated at most once per call, in order, and only until one holds. > [!WARNING] > A `where` condition that is a strict subset of a preceding condition will never fire. The compiler emits a warning when it can statically determine that a `where` clause is unreachable (it decides conditions that compare integer parameters with constants, alone or joined with `&&`): > > ```kairo > fn process(x: i32) -> string where x > 50 { return "high" } > fn process(x: i32) -> string where x > 100 { return "very high" } // warning: unreachable > fn process(x: i32) -> string { return "low" } > ``` --- ## Overlapping Conditions If two `where` clauses have overlapping conditions that cannot be statically determined to be disjoint, the compiler emits a warning: ```kairo fn handle(x: i32) -> string where x > 0 && x < 100 { return "small positive" } fn handle(x: i32) -> string where x > 50 { return "over 50" } // warning: overlaps with above fn handle(x: i32) -> string { return "other" } ``` Declaration order still determines the result: `x == 75` hits the first overload, but the warning signals that the intent may not match the behavior. A narrower condition before a wider one, as in `categorize` above, is the priority pattern and is not warned about. Conditions the compiler cannot decide (floating-point comparisons, function calls) produce no warning. --- ## Where in Match The `where` keyword also appears in [`match`](/docs/language/pattern-matching/) arms as a guard condition. Match guards are always evaluated at runtime and are independent of the overload dispatch system they are simple boolean filters on a matched pattern, not function overloads: ```kairo match result { case .Found(var key, var value) where value > 0 { process(key, value) } case .Found(var key, var value) { skip(key) } default { } } ``` A match guard that fails causes the arm to be skipped and evaluation continues to the next arm. See [Control Flow](/docs/language/pattern-matching/#where-guards) for the full `match` syntax. --- ## Runtime Dispatch and Timing `where` dispatch introduces a branch at the call site. In most cases this is a single conditional jump that the branch predictor handles efficiently. However, if the constrained function processes sensitive data, the branch structure can leak information through execution time differences. > [!CAUTION] > Runtime `where` dispatch creates observable branching. If the function handles sensitive data (cryptographic keys, authentication tokens, private user data), the timing difference between the constrained and fallback paths may be measurable by an attacker. Use constant-time implementations in those cases and do not rely on `where` dispatch for security-critical branching. --- ## Where and panic `where` clauses and [`panic`](/docs/language/panic/) are orthogonal. `where` selects which overload runs based on a runtime condition. `panic` signals an error from within a function body. They can coexist: ```kairo struct ConnectError { var host: string fn op panic (const self) -> string { return f"cannot connect to {self.host}" } } fn connect(host: string, port: i32) panic -> Connection where port > 0 && port <= 65535 { var conn = tcp_connect(host, port) if !conn.is_valid() { panic ConnectError { host: host } } return conn } fn connect(host: string, port: i32) -> Connection { // fallback: invalid port, return a no-op connection return Connection::invalid() } ``` Overloads in one `where` group may differ in `panic`. A call through the group may reach any of them, so its panic set is the union of the candidates' sets: a call to `connect` must handle `ConnectError` even though the fallback never panics. --- ## Where and unsafe `where` constraints and `unsafe` overloads are in separate namespaces. Safe overloads dispatch among themselves based on `where` conditions. Unsafe overloads are selected explicitly by the caller with the `unsafe` keyword and do not participate in `where`-based dispatch: ```kairo // Safe dispatch: where selects between these fn access(data: [i32], index: i32) -> i32 where index >= 0 && index < data.length() { return data[index] } fn access(data: [i32], index: i32) -> i32 { return 0 // fallback } // Unsafe overload: separate namespace, caller selects explicitly fn access(data: [i32], index: i32) unsafe -> i32 { return data[index] // no bounds check } var a = access(data, 5) // safe dispatch var b = unsafe access(data, 5) // unsafe overload, no where dispatch ``` See [Unsafe](/docs/language/unsafe/) for the unsafe overload model. --- ## What where Cannot Do `where` is only valid on free functions and methods. The following are compile errors (so is a `where` clause on a closure): ```kairo // compile error: where on a type use requires instead class Buffer where sizeof T <= 128 { var data: [T; 16] } // compile error: where on an interface method interfaces are zero-cost, use requires interface Validator { fn validate(self, input: string) -> bool where input.length() > 0 } ``` Type instantiation is always compile-time. [Interface conformance](/docs/language/interfaces/#conformance) is a zero-cost structural contract. Neither admits runtime dispatch. Use `requires` for both. --- ## Summary ```kairo // Basic runtime dispatch with fallback fn root(x: f64) -> f64 where x >= 0.0 { return sqrt(x) } // C's sqrt, from math.h fn root(x: f64) -> f64 { return 0.0 } // Multiple constrained overloads declaration order is priority fn classify(temp: f64) -> string where temp > 100.0 { return "boiling" } fn classify(temp: f64) -> string where temp > 0.0 { return "liquid" } fn classify(temp: f64) -> string { return "frozen" } // Where with panic struct NotPositive { var value: i32 fn op panic (const self) -> string { return f"{self.value} is not positive" } } fn parse_positive(input: string) panic -> i32 where input.length() > 0 { var n = std::parse(input) if n <= 0 { panic NotPositive { value: n } } return n } fn parse_positive(input: string) -> i32 { return 0 } // Where coexisting with unsafe overload fn divide(a: i32, b: i32) -> i32 where b != 0 { return a / b } fn divide(a: i32, b: i32) -> i32 { return 0 } fn divide(a: i32, b: i32) unsafe -> i32 { return a / b } // no check var result = divide(10, 0) // 0 (fallback) var fast = unsafe divide(10, 2) // 5 (unsafe, no dispatch) ``` ## See also - [Requires Clauses](/docs/language/requires/) - [Pattern Matching](/docs/language/pattern-matching/#where-guards) - [Function Overloading](/docs/language/functions-overloading/) - [Unsafe](/docs/language/unsafe/) - [Panic](/docs/language/panic/) --- ## Pointers & Raw Pointers URL: https://www.kairolang.org/docs/language/pointers/ # Pointers & Raw Pointers Kairo has two pointer types: safe pointers (`*T`) with compiler-tracked lifetime and a non-null guarantee, and raw pointers (`unsafe *T`) with no tracking and no checks. Both are 8 bytes on 64-bit platforms and hold a memory address. --- ## Safe Pointers (`*T`) `*T` is the default pointer type. The compiler tracks its provenance via [Tether](/docs/language/tether/). It is never null, so a dereference needs no check: ```kairo var x = 42 var p: *i32 = &x // p points to x *p = 100 // dereference and assign, no null check std::io::println(*p) // 100 ``` ### Non-Null Guarantee `*T` cannot hold null. Attempting to assign `&null` to a `*T` is a compile error: ```kairo var p: *i32 = &null // compile error: *T is non-null var x = 42 var p: *i32 = &x // ok: p is guaranteed valid *p = 100 // no null check needed ``` If you need a pointer that might be absent, use `*T?`, a nullable pointer (see [Pointers and Nullable Types](#pointers-and-nullable-types)): ```kairo var p: *i32? = get_pointer() // might be null if p? { std::io::println(*p) // safe: compiler has verified p is non-null } ``` For a raw pointer with no compiler tracking, use `unsafe *T`. It is the only pointer that can hold the null address, written `&null`. A bare `null` is a nullable's null and never a pointer: `var raw: unsafe *i32 = null` is a compile error. A null check compares against `&null` by hand: ```kairo var raw: unsafe *i32 = &null // ok: raw pointers can be null if raw != &null { std::io::println(*raw) } ``` ### Member access Use `->` to access members through a pointer: ```kairo class Config { pub var port: i32 fn Config(self, port: i32) { self.port = port } } var cfg = Config(8080) var ptr: *Config = &cfg ptr->port // 8080 ``` --- ## Raw Pointers (`unsafe *T`) [`unsafe *T`](/docs/language/unsafe/#raw-pointers-unsafe-t) is an untracked pointer with no null checks, no bounds checks, and no [Tether provenance tracking](/docs/language/tether-bounds/). It is equivalent to a raw C/C++ pointer: ```kairo var x = 42 var p: unsafe *i32 = unsafe &x // create raw pointer from safe binding *p = 100 // no null check ``` Dereferencing a null `unsafe *T` is undefined behavior. The compiler will not insert a check. Raw pointers are required for [C/C++ interop](/docs/language/c-cpp/), custom allocators, hardware register access, and any scenario where Tether tracking is not possible or not desired. ### Creating raw pointers ```kairo // From a safe binding var x = 42 var raw: unsafe *i32 = unsafe &x // From heap allocation var raw: unsafe *i32 = unsafe std::alloc(sizeof i32) // From an integer address (requires an unsafe block: fabricates provenance) unsafe { var unsafe *raw = 0x7FFE_0000_1000 as unsafe *i32 } // Null var raw: unsafe *i32 = &null ``` --- ## Const Pointers A pointer declaration makes two independent properties visible: 1. **Can I change the pointer?** Answered by the declaration keyword: `var ptr` or `const ptr`. 2. **Can I change the pointee?** Answered directly after the `*`: `*T` or `*const T`. | Declaration | Change the pointer? | Change the pointee? | |---|---|---| | `var ptr: *i32` | Yes | Yes | | `const ptr: *i32` | No | Yes | | `var ptr: *const i32` | Yes | No | | `const ptr: *const i32` | No | No | ```kairo var a: *i32 = &x a = &y // ok *a = 10 // ok const b: *i32 = &x b = &y // compile error: the pointer is const *b = 10 // ok var c: *const i32 = &x c = &y // ok *c = 10 // compile error: the pointee is const const d: *const i32 = &x d = &y // compile error *d = 10 // compile error ``` Each question has exactly one place it can be answered. `var ptr: const *const i32` would mean the same thing as `const ptr: *const i32`, but it is rejected, because the pointer question belongs to the declaration keyword. See [Variables](/docs/language/variables/#the-const-binding-rule) for the full `const` model. --- ## Pointer Arithmetic ### On safe pointers (`*T`) Safe pointers support offset arithmetic with integers. The offset is in units of `sizeof T`: ```kairo var arr: [i32; 4] = [10, 20, 30, 40] var p: *i32 = &arr[0] var second = *(p + 1) // 20 var third = *(p + 2) // 30 p = p + 4 // ok: one past the end, may be compared but not dereferenced p = p - 1 // ok: back to the last element --p // ok: `p -= 1`; `++p`, `p++` and `p--` step the same way ``` `++` and `--` on a pointer move it by one element, as `p += 1` and `p -= 1` do, on both kinds of pointer. That is how a C++-style iterator loop is written: ```kairo var v: [i32] = [1, 2, 3] var sum = 0 for var *it = v.begin(); it != v.end(); ++it { sum += *it } // 6 ``` A pointer to `void` has no element size and cannot be stepped. A nullable pointer (`*T?`) must be checked first. A safe pointer must always stay within its allocation or exactly one past its end. Forming one outside that range (`&arr[0] - 1`, `&arr[0] + 5`) is a compile error when Tether can see it statically, and a runtime check at the arithmetic when the offset is runtime data. See [Forming versus dereferencing](/docs/language/tether-bounds/#forming-versus-dereferencing-and-one-past-the-end). Pointer-to-pointer arithmetic (`p1 - p2`) is not permitted on safe pointers use `unsafe *T` for that. > [!CAUTION] > Safe pointer arithmetic needs provenance [Tether](/docs/language/tether-bounds/#pointer-arithmetic) can track. A safe pointer whose allocation Tether cannot determine (for example, one that came from C++ untracked) cannot be offset or dereferenced in safe code; use an `unsafe` block. Prefer array/vector indexing over pointer arithmetic when possible. ### On raw pointers (`unsafe *T`) Raw pointers support all arithmetic operations with no checks: ```kairo var p: unsafe *i32 = get_buffer() var q: unsafe *i32 = p + 10 // offset by 10 i32s (40 bytes) var distance = q - p // 10 (pointer difference in units of sizeof i32) ``` Out-of-bounds access through raw pointer arithmetic is undefined behavior. --- ## Array-Style Indexing Pointers support bracket indexing, which desugars to offset + dereference: ```kairo var p: *i32 = &arr[0] p[0] // same as *(p + 0) p[2] // same as *(p + 2) ``` Bounds checking follows the same rules as pointer arithmetic Tether checks when provenance is trackable, no checks on `unsafe *T`. --- ## Void Pointers `*void` and `unsafe *void` are opaque pointers that hold an address without type information. They cannot be dereferenced cast to a typed pointer first: ```kairo var handle: unsafe *void = get_opaque_handle() // *handle // compile error: cannot dereference void pointer var unsafe *typed = handle as unsafe *i32 var value = *typed // ok: typed pointer ``` Void pointers are used for type-erased APIs, opaque handles, and [C interop](/docs/language/c-cpp-calling/#pointers-and-references) where the concrete type is not known at the Kairo call site. --- ## Double Pointers Pointers to pointers are legal and follow the same rules recursively: ```kairo var x = 42 var p: *i32 = &x var pp: **i32 = &p **pp = 100 // x is now 100 ``` `const` applies at each level independently, one question per level: ```kairo const pp: *const *i32 = &p // pp cannot be reassigned // *pp (the inner pointer) cannot be reassigned // **pp (the i32) can be modified ``` --- ## Smart Pointer Promotion [Tether](/docs/language/tether-promotion/) analyzes pointer usage and determines when a safe pointer needs smart pointer ownership semantics. In **debug** builds it performs the promotion and warns; in **release** builds the same situation is a hard error naming the type to annotate. The smart pointer types are compiler intrinsics exposed through the standard library: | Type | Description | |---|---| | `std::Unique` | Single-owner, exclusive access, freed on drop | | `std::Shared` | Reference-counted, multiple owners, freed when count reaches zero | | `std::Weak<*T>` | Non-owning reference to a `Shared` allocation, does not prevent deallocation | Tether picks the smart pointer type from how the pointer is used across the program: ```kairo fn make_config() -> *Config { var *cfg = @create Config(8080) return cfg // debug: promote cfg -> std::Unique // release: error, annotate the return type } ``` If Tether cannot determine a safe promotion path (e.g., the pointer escapes in a way that prevents tracking), it emits a compile error in both modes rather than allowing unsafe behavior. Release code spells the smart pointer type explicitly, which is also how you override Tether's choice in debug: ```kairo var ptr: std::Unique = @create Config(8080) var shared: std::Shared = @create Config(8080) ``` See [Tether](/docs/language/tether/) for the full lifetime and promotion model, and [Ownership](/docs/language/ownership/) for borrowing semantics. --- ## Heap Allocation Stack allocation is the default. Heap allocation uses `@create T()`: ```kairo var stack_val = Config(8080) // stack-allocated var *heap_ptr = @create Config(8080) // heap-allocated, Tether chooses pointer type ``` For raw heap allocation without Tether tracking: ```kairo var unsafe *raw = unsafe std::alloc(sizeof i32 * 10) // raw allocation, 10 i32s // must be manually freed unsafe std::free(raw) ``` A heap object is freed with `@destroy p`, which runs the object's destructor ([`fn op finally`](/docs/language/classes-lifecycle/#destructors---op-finally)) and returns the memory to the same allocator `@create` used. Kairo has no `delete` expression. ```kairo var *obj = @create Config(8080) // ... @destroy obj ``` For memory that comes from or goes to C++ code, `@cxx::new T(args)` is a plain C++ `new` (an `unsafe *T`) and `@cxx::delete p` a plain C++ `delete`; see [C++ memory](/docs/language/c-cpp-memory/#memory-that-belongs-to-c-cxxnew-and-cxxdelete). See [Tether](/docs/language/tether/) for how allocation interacts with lifetime tracking. --- ## Pointer Comparison | Operator | Behavior | |---|---| | `==` | Compares addresses do both pointers point to the same location? | | `!=` | Negation of `==` | | `<` `<=` `>` `>=` | Address order. On safe pointers, both operands must point into the same allocation (one-past included); otherwise it is a compile error | | `===` | Null-aware equality on nullable pointers (`*T?`): true when both are non-null and the values they point to are equal (one level: on `(**T)?` it compares the `*T` addresses) | ```kairo var a = 42 var b = 42 var p: *i32? = &a var q: *i32? = &b p == q // false: different addresses p === q // true: both point to 42 var r: *i32? = &a p == r // true: same address ``` `===` needs at least one nullable operand; on two `*T` it is an error. To compare what two `*T` point to, dereference them: `*x == *y`. For raw pointers (`unsafe *T`), use `==` for address comparison and dereference manually after a null check. See [Operators](/docs/language/operators/#comparison) for the full comparison model. --- ## Function Pointers Function pointers (`fn(T) -> R`) are a separate type from `*T`. They are opaque values that cannot be cast to data pointers or vice versa: ```kairo fn add(a: i32, b: i32) -> i32 = a + b var f: fn(i32, i32) -> i32 = add // var p = f as unsafe *void // compile error: function pointers are not data pointers ``` See [Functions](/docs/language/functions/#function-pointers) for function pointer syntax and [Closures](/docs/language/closures/) for closures as function pointers. --- ## Pointers and Nullable Types `*T` is non-null by construction. To represent a pointer that might not exist, use `*T?` which wraps the pointer in the standard [`Nullable` system](/docs/language/nullables/#pointers-and-nullability). `*T?` reads as `(*T)?`: the `?` applies to the whole pointer type, so the pointer itself may be null. A pointer to a nullable value is a different type, written with parentheses as `*(T?)`: the pointer is never null, and the value it points to may be. ```kairo var a: *i32? = find_ptr() // (*i32)?: maybe a pointer; check a? before *a var b: *(i32?) = &slot // slot: i32?; b is always valid, *b may be null ``` A nullable safe pointer is one pointer wide: null is stored as `0x0`, with no separate flag. | | `*T` | `*T?` | `unsafe *T` | |---|---|---|---| | Can be null | No | Yes | Yes | | Null check mechanism | N/A | `val?`, `== null`, `?.`, `?->`, `??`, `unwrap!()` | `ptr != &null` (manual) | | Dereference null | Cannot happen | Compile error (must check first) | Undefined behavior | | Tether tracked | Yes | Yes | No | `*T?` supports the same null-handling operators as any other nullable type. `unsafe *T` uses manual null comparison, it does not participate in the `Nullable` system. ```kairo var p: *i32 = &x // always valid, no null check needed var q: *i32? = find_ptr() // might be null must check before use var r: unsafe *i32 = &null // raw pointer, may hold &null, no tracking if q? { std::io::println(*q) // compiler knows q is non-null here } var *val = q ?? &fallback // *i32: use fallback pointer if q is null var *forced = unwrap!(q) // *i32: aborts if null ``` See [Nullables](/docs/language/nullables/#nullable-types) for the full nullable type system. --- ## Summary ```kairo // Safe pointer var x = 42 var p: *i32 = &x *p = 100 // Raw pointer var raw: unsafe *i32 = unsafe &x // Nullable pointer (*T itself is never null) var maybe: *i32? = null if maybe? { std::io::println(*maybe) } // Const pointer var ptr: *const i32 = &x // can change the pointer, cannot change the pointee const ptr: *i32 = &x // cannot change the pointer, can change the pointee // Pointer arithmetic var arr: [i32; 4] = [10, 20, 30, 40] var p: *i32 = &arr[0] *(p + 2) // 30 // Heap allocation var *heap = @create Config(8080) // Smart pointer (explicit) var unique: std::Unique = @create Config(8080) // Void pointer var opaque: unsafe *void = get_handle() var unsafe *typed = opaque as unsafe *i32 // Double pointer var pp: **i32 = &p **pp = 999 // Comparison p == q // address comparison *p == *q // value comparison maybe === other // pointee equality on nullable pointers (one level) ``` ## See also - [Ownership](/docs/language/ownership/) - [Unsafe](/docs/language/unsafe/) - [Tether](/docs/language/tether/) - [Bounds and Provenance](/docs/language/tether-bounds/) - [Ownership and Promotion](/docs/language/tether-promotion/) - [Nullables](/docs/language/nullables/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/#pointers-and-references) --- ## Ownership URL: https://www.kairolang.org/docs/language/ownership/ # Ownership > [!WARNING] > The ownership model is enforced by [Tether](/docs/language/tether/), which is not yet implemented. Tether development begins at **Stage 2** of the compiler roadmap. This page describes the intended design. See [Tether](/docs/language/tether/) for the implementation timeline. Kairo's ownership model governs how values are created, transferred, borrowed, and destroyed. It works in conjunction with [Tether](/docs/language/tether/) to provide memory safety without lifetime annotations and without a separate reference type. The model has two parts: **transfer semantics** (how values move between bindings) and **pointer aliasing** (how multiple pointers to the same value interact). Transfer semantics are determined by the type's lifecycle category. Pointer aliasing is tracked by Tether at compile time. > [!NOTE] > This page covers *who owns a value and when it dies*. It does not cover the safety of individual pointer *accesses* (bounds, use-after-free, null, data races) those are dereference obligations discharged by Tether's proof engine, described in [Tether The Dereference Obligation](/docs/language/tether-proof-model/#the-dereference-obligation). The distinction matters: ownership and escape violations are resolved by *transforming the program* (debug) or a *hard error* (release), never by a runtime check. Access violations may fall back to a runtime check. When this page says a violation is "a hard error," it means specifically that no ownership transformation can rescue it see [Tether The Residual Table](/docs/language/tether-proof-model/#the-residual-table) for the full classification. --- ## Transfer Semantics Every type in Kairo has a lifecycle category that determines what happens when a value is assigned to a new binding, passed to a function, or returned. The category is set by which transfer constructor the type defines. See [Classes Lifecycle Categories](/docs/language/classes-lifecycle/#lifecycle-categories) for the declaration syntax. ### COPY types A type with a `@copy` transfer constructor (explicit or implicit) is copyable. Assignment produces an independent copy both the source and destination are live after the assignment: ```kairo class Buffer { var data: [i32] fn Buffer(self) = default @copy fn Buffer(self, const other: Self) = default } var a = Buffer() var b = a // copy: a and b are independent b.data.push(42) a.data.size() // 0 a is unaffected ``` Tether may **elide a copy into a move** when it proves the source is not used after the transfer and the elision is unobservable. This is a pure optimization with no observable semantic difference. Tether does not elide when the destructor has timing-sensitive side effects see [Tether Copy Elision](/docs/language/tether/#copy-elision) for the exact rule. The programmer does not opt into or control copy elision. Tether applies it when safe. ### MOVE types A type with a `@move` transfer constructor can only be moved. MOVE types represent unique ownership of a resource. Moving transfers ownership without duplicating the underlying resource, preventing double destruction and expensive deep copies. Assignment transfers ownership the source is invalidated and cannot be used: ```kairo class UniqueFile { var handle: i32 fn UniqueFile(self) = default @move fn UniqueFile(self, other: Self) = default } var a = UniqueFile() var b = a // move: ownership transfers to b // a is invalidated any use after this line is a compile error a.handle // compile error: a has been moved b.handle // ok: b owns the value ``` A type cannot define both `@copy` and `@move` (unless both are `= delete`) pick one. A type with neither takes the weakest category its bases and fields allow: COPY if all of them are, MOVE if any is move-only, NON_TRANSFER if any cannot be transferred. Its members are compiler-generated to match. ### NON_TRANSFER types A type with a deleted transfer constructor (`@copy ... = delete`, `@move ... = delete`, or both) cannot be assigned, copied, or moved. The auto-derived `op =` is also `= delete`d as a consequence there is no transfer constructor for it to be generated from. These are scope-bound values: they live and die in the scope where they are created: ```kairo class ScopeLock { fn ScopeLock(self) = default @copy fn ScopeLock(self, const other: Self) = delete @move fn ScopeLock(self, other: Self) = delete } var lock = ScopeLock() // var copy = lock // compile error: copy deleted // var moved = lock // compile error: move deleted // lock = ScopeLock() // compile error: op = is deleted // lock lives until end of scope, then destructor runs ``` > [!NOTE] > `NON_TRANSFER` types have a specific restriction under threading: they cannot be transfer-captured into a spawned task (there is nothing to transfer), and may only be shared read-only by address. See [Tether Threading](/docs/language/tether-threading/#threading). ### Structs Structs have value semantics. Assignment copies their object representation byte-for-byte via `memcpy`. Because structs cannot define constructors, destructors, or transfer constructors, this copy is always valid. ```kairo struct Point { var x: f64; var y: f64 } var a = Point { x: 1.0, y: 2.0 } var b = a // memcpy always, unconditionally b.x = 9.0 a.x // 1.0 independent copy ``` See [Structures](/docs/language/structures/#copy-semantics). --- ## Function Parameters Function parameters follow the same transfer rules as assignment. Passing a COPY type copies it. Passing a MOVE type moves it the caller cannot use the value after the call: ```kairo fn consume(file: UniqueFile) { // file is owned by consume } var f = UniqueFile() consume(f) // f is invalidated moved into consume f.handle // compile error: f has been moved ``` ```kairo fn inspect(buf: Buffer) { // buf is an independent copy } var b = Buffer() inspect(b) b.data.size() // ok: b is still live, inspect got a copy ``` To let a callee write to the caller's object, or to take ownership of a generic argument, use the `@inout` and `@move` parameter modes. See [Parameter passing modes](/docs/language/functions-parameter-modes/#parameter-passing-modes). ### Last-use move optimization For MOVE types, Tether detects when a value is passed to a function and never used again. In this case, the value is moved rather than requiring explicit annotation: ```kairo var m = Moveable() foo(m) // m is moved Tether sees m is not referenced after this line // m is invalidated from here ``` This only applies when the value is genuinely unused after the call. If any subsequent code references the value, it is a compile error (MOVE types cannot be copied). ### Pass-by-pointer optimization When a function takes a parameter by value and the type is larger than a pointer (8 bytes on 64-bit), the compiler may silently pass a pointer instead of copying. This is a **codegen optimization only** the source-level semantics are always by-value. The optimization applies only when Tether can prove the by-value semantics are preserved for the duration of the call: - The parameter is not aliased *and mutated* through any other live pointer while the call is in progress i.e. Tether proves no write reaches the same allocation during the call. - The parameter is not modified inside the callee (or the function takes it as `const`). - The parameter is not stored, returned, or captured. - The function is not [`async`](/docs/language/concurrency/#asyncawait). The first condition is stronger than "no other pointer exists." Kairo permits arbitrary mutable aliasing in single-threaded code (see [Pointer Aliasing](#pointer-aliasing)), so Tether cannot rely on the absence of aliases it must prove that no *write* through an alias is observable during the call. If it cannot prove this, the parameter is copied as written. The programmer does not control this optimization and cannot observe it. --- ## Pointer Aliasing Kairo allows multiple pointers to the same value. There is no Rust-style exclusivity rule (one mutable xor many immutable) **in single-threaded code**. Multiple `*T` to the same location is legal, and writing through one pointer is visible through all others: ```kairo var x = 42 var p: *i32 = &x var q: *i32 = &x *p = 100 std::io::println(*q) // 100 defined behavior ``` > [!IMPORTANT] > This freedom is single-threaded only. The moment an allocation is shared across a thread boundary (captured into a [`spawn`](/docs/language/concurrency/#spawn)ed task), Tether switches to a stricter rule: one writer, or many readers, never both. Arbitrary mutable aliasing is permitted within one thread because a single-threaded race is impossible; across threads it is undefined behavior that no runtime check can rule out, so the rule tightens exactly at the boundary. See [Tether Threading](/docs/language/tether-threading/#threading). This applies uniformly regardless of `const`: ```kairo var x = 42 var p: *i32 = &x var q: *const i32 = &x *p = 100 std::io::println(*q) // 100 *const prevents mutation through q, not through p ``` `const` is a **semantic check on the binding**, not an aliasing constraint. Of the [two questions a pointer declaration answers](/docs/language/variables/#the-const-binding-rule), "can I change the pointee?" is asked about one pointer only. `*const T` prevents the holder from mutating through that pointer. It does not prevent other pointers from mutating the same value. Tether does not change behavior based on `const` qualifiers it tracks provenance and lifetime independently of mutability. ### What Tether enforces Tether does not restrict aliasing patterns in single-threaded code. What it does enforce: **Provenance validity.** A pointer must refer to memory that is still live. Using a pointer after its target has been destroyed is a hard error. This is clause C1 of the [dereference obligation](/docs/language/tether-proof-model/#the-dereference-obligation), discharged by epoch tracking Tether proves the allocation has not been freed or relocated since the pointer was derived: ```kairo var p: *i32 { var x = 42 p = &x } *p = 10 // hard error: x is destroyed (epoch incremented), p is dangling ``` When provenance is intact but the epoch cannot be proven equal statically, this access falls back to a runtime epoch check rather than a hard error see [Tether Provenance and Epochs](/docs/language/tether-bounds/#provenance-and-epochs). It is a hard error only when provenance is lost entirely. **Iterator invalidation.** A pointer into a container's buffer is invalidated by operations that may reallocate the buffer: ```kairo var v: [i32] = [1, 2, 3] var p: *i32 = &v[0] v.push(4) // may reallocate v's internal buffer std::io::println(*p) // hard error: p's provenance is invalidated by push ``` Tether detects this through [`.amt` summaries](/docs/language/tether-internals/#amt-summaries): `push`'s summary records that it may reallocate the backing buffer, so any live pointer into that buffer is flagged at the call site. **Invalidation is a hard error even when Tether can trace the reallocation** it is not a runtime-check fallback. The realloc is provable statically, re-validating every live pointer across every potentially-reallocating call would be expensive, and a use-after-realloc is almost always a real bug, so Tether errors rather than checks. Where the buffer is mutated through a path Tether cannot trace (an opaque container, a raw FFI call), Tether also errors rather than allowing an unprovable access. See [Tether Analysis scope](/docs/language/tether-proof-model/#the-dereference-obligation). **Stack escape.** A pointer to a stack-allocated value cannot outlive the value. What happens when it tries depends on whether the value is **heap-promotable**: ```kairo fn make() -> *i32 { var x = 42 return &x // debug: Tether rewrites `var x = 42` to a heap allocation and promotes the // escaping pointer (Unique) // release: hard error a heap allocation in a release binary must be visible // in the source, so Tether shows the fix instead of inserting it silently } ``` A stack escape of a heap-promotable value is **debug-transformable / release-error** Tether can lift `x` to the heap, which turns the escape into a legal ownership transfer. A stack escape with *no value to lift* (a borrow with no owner, an escape into an opaque sink where Tether cannot establish the heap-allocation pattern) is a hard error in both modes there is nothing to transform. This is the split the [Tether Stack Pointers](/docs/language/tether-promotion/#stack-pointers) section details in full. Either way, the fix in release is to allocate explicitly or restructure. > [!NOTE] > **Data-race detection across threads** is enforced by Tether's strict threading mode. When an allocation is shared across a `spawn` boundary, Tether requires a single writer (or read-only sharing) and treats a second writer, or any unsynchronized write+read, as a hard error. The synchronization primitives that discharge these obligations depend on Kairo's concurrency runtime, which is not yet finalized the analysis shape is fixed, the runtime seam is not. See [Tether Threading](/docs/language/tether-threading/#threading) and [Concurrency](/docs/language/concurrency/). ### What Tether does not enforce Tether does not prevent multiple mutable pointers to the same value in single-threaded code. This is intentional many valid patterns require mutable aliasing (parent/child pointers, graph structures, cache-and-source patterns). The tradeoff: Kairo allows more programs than Rust at the cost of not statically preventing all aliasing bugs. Tether catches the ones that are provably wrong (dangling, invalidation, and across a thread boundary races) and lets the rest through. ### noalias optimization When Tether proves that two pointers do not alias (point to different allocations or non-overlapping regions), it attaches `noalias` metadata to the LLVM IR. This enables the backend optimizer to perform more aggressive transformations (load/store reordering, vectorization) without the programmer writing anything. This is invisible the source code does not change, and the behavior is identical with or without the tag. --- ## Smart Pointer Promotion and Aliasing When Tether promotes a heap pointer to a [smart pointer](/docs/language/pointers/#smart-pointer-promotion) (in debug mode), the aliasing pattern determines which smart pointer type is chosen. In release, the same analysis produces a hard error naming the type to annotate Tether does not silently change pointer types in a release binary. See [Tether Ownership and Promotion](/docs/language/tether-promotion/#ownership-and-promotion). ```kairo // Single owner, no aliasing -> Unique var *cfg = @create Config(8080) return cfg // Tether: cfg has one owner -> Unique ``` ```kairo // Aliased, both pointers escape -> Shared var *cfg = @create Config(8080) server_a.config = cfg server_b.config = cfg // Tether: cfg is aliased across two live bindings -> Shared ``` ```kairo // Aliased, but the alias dies before escape -> Unique var *cfg = @create Config(8080) { var tmp: *Config = cfg validate(tmp) } // tmp is dead cfg has single ownership at this point return cfg // Tether: alias was short-lived, cfg is sole owner -> Unique ``` The promotion trigger is not "multiple pointers exist" but "multiple pointers exist AND the aliasing pattern requires shared ownership for safety." A short-lived alias that dies before the owner escapes does not force `Shared`. Because Tether is whole-program, the cases where promotion is actually needed are narrow. Most pointers have fully contained lifetimes and require no promotion at all. See [Tether Promotion Decision](/docs/language/tether-promotion/#ownership-and-promotion) for the full decision tree. --- ## Closure Captures [Closures](/docs/language/closures/#capture-modes) capture variables from their enclosing scope. The capture mode determines the ownership relationship between the closure and the captured variable. Kairo has no reference types, so a closure holds either its own value or a pointer. ### Default capture (by value) With no capture list, a closure captures every referenced variable by value, using its type's transfer semantics: COPY types are copied, MOVE types are moved. Captures happen at closure creation time, not at invocation: ```kairo var buf = Buffer() // COPY type var file = UniqueFile() // MOVE type var closure = fn () { buf.data.push(1) // operates on the closure's copy file.close() // operates on the moved-in file } buf.data.size() // ok: buf was copied, original is still live file.handle // compile error: file was moved into the closure ``` ### Capture by pointer (`|*|`) `|*|` captures all referenced variables by pointer. The closure holds `*T` to each captured variable and reaches it through explicit dereference. Mutations through the pointer affect the original: ```kairo var count = 0 var inc = fn ()|*| { *count += 1 // modifies the original count through a pointer } inc() inc() count // 2 ``` Tether tracks pointer captures the same way it tracks any other pointer. If the closure escapes and the captured variable is stack-allocated, the heap-promotable / non-promotable split applies exactly as it does for any stack escape (see [Stack escape](#what-tether-enforces) above): a promotable value is heap-lifted in debug and a hard error in release; a non-promotable one is a hard error in both modes: ```kairo fn make_closure() -> fn() -> i32 { var x = 42 return fn ()|*x| -> i32 { return *x } // debug: x is heap-lifted and the capture promoted // release: hard error, capture by value or heap-allocate explicitly } ``` Capture by value sidesteps the escape entirely: the closure owns its own copy with no lifetime dependency on the enclosing frame: ```kairo fn make_closure() -> fn() -> i32 { var x = 42 return fn () -> i32 { return x } // ok: x is copied into the closure, no lifetime dependency } ``` > [!NOTE] > When a closure is captured into a spawned task, pointer captures fall under Tether's threading rules: a `const *` (read-only) capture shares the allocation read-only across the boundary; a mutating `*` capture makes the allocation a shared *mutable* allocation and triggers the single-writer analysis. See [Tether Threading](/docs/language/tether-threading/#threading). ### Per-variable capture Name variables in the capture list to choose a mode for each. Unqualified names are captured by value, `*`-prefixed names by pointer, and `const *`-prefixed names by const pointer: ```kairo var a = Buffer() // COPY var b = 0 var closure = fn ()|a, *b| { a.data.push(1) // closure's own copy of a *b += 1 // modifies the original b through a pointer } ``` See [Closures](/docs/language/closures/) for the full capture syntax. --- ## Destruction Order Values are destroyed at the end of their enclosing scope in **reverse declaration order**. This applies to stack-allocated, heap-allocated, and smart-pointer-promoted values alike: ```kairo fn example() { var a = Resource("first") var b = Resource("second") var c = Resource("third") } // destruction order: c, b, a ``` For smart pointers promoted by Tether: - `std::Unique`: the object destructor runs at the end of the owning binding's lexical scope, in reverse declaration order. - `std::Shared`: each binding decrements the reference count at its own scope boundary in reverse declaration order; the *object* destructor and deallocation run once, when the last `Shared` reference's scope ends. The decrement order is lexical and deterministic; the object destructor fires at the final owner, which is not necessarily the last-declared binding in any single scope. See [Tether Destruction Timing](/docs/language/tether/#destruction-timing). - `std::Weak<*T>`: invalidated at scope exit. Does not affect the reference count. There is no drop-at-last-use optimization for observable destructors. Destruction of a value whose destructor has side effects (file close, lock release, flush) is tied to lexical scope, so the effect is predictable from reading the source. A value whose destructor is trivial may be reclaimed at last use, since that is unobservable see [Tether Destruction Timing](/docs/language/tether/#destruction-timing) for the trivial / non-trivial split. --- ## Moved-From State After a value is moved, the source binding is **invalidated**. Any use of a moved-from binding is a compile error there is no "valid but unspecified" state like C++: ```kairo var a = UniqueFile() var b = a // move a.handle // compile error: a has been moved a = UniqueFile() // ok: a can be reassigned to a new value a.handle // ok: a is live again ``` A moved-from binding can be reassigned. After reassignment, it is live again with the new value. But between the move and the reassignment, any access is a hard error. This is enforced by Tether in both debug and release builds, and it is a **static** determination, not a runtime check there is no runtime fallback for a moved-from access the way there is for an unprovable bounds access. A use-after-move is a logic error the compiler proves at compile time, not a safety property discharged at runtime; the compiler statically tracks which bindings are live and which have been moved. --- ## Summary | Type category | Assignment | Source after | Function param | |---------------|------------|--------------|-----------------------| | COPY | Copy | Live | Copy (caller keeps) | | MOVE | Move | Invalidated | Move (caller loses) | | NON_TRANSFER | Error | N/A | Error | | Struct | memcpy | Live | memcpy (caller keeps) | Escape and ownership violations resolve by *transforming the program* in debug (heap-lift, smart pointer promotion) and a *hard error with the fix* in release. They are never runtime checks that is reserved for access obligations like bounds. See [Tether The Residual Table](/docs/language/tether-proof-model/#the-residual-table). ```kairo // COPY: both sides live after transfer var a = Copyable() var b = a // copy a.method() // ok b.method() // ok // MOVE: source invalidated after transfer var x = Moveable() var y = x // move // x.method() // compile error y.method() // ok // Pointer aliasing (single-threaded): allowed, Tether checks provenance var val = 42 var *p = &val var *q = &val *p = 100 std::io::println(*q) // 100 // Closure capture by value (default) var m = Moveable() var f = fn () { m.use() } // m is moved into f // Closure capture by pointer var n = 0 var g = fn ()|*| { *n += 1 } g() // n is 1 ``` ## See also - [Tether](/docs/language/tether/) - [Ownership and Promotion](/docs/language/tether-promotion/) - [Threading](/docs/language/tether-threading/) - [Pointers](/docs/language/pointers/) - [Class Lifecycle](/docs/language/classes-lifecycle/#lifecycle-categories) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Closures](/docs/language/closures/) - [Structures](/docs/language/structures/#copy-semantics) --- ## Tether URL: https://www.kairolang.org/docs/language/tether/ # Tether Tether is a compile-time proof engine. For every pointer dereference in the program, it attempts to prove that the access is safe. When it succeeds, no runtime code is emitted. When it can prove everything except one residual property, it emits the minimal runtime code required to discharge exactly that property and nothing else. When it cannot prove the access safe and no runtime check or code transformation can establish safety, it is a hard compile error. The system is not a pointer tracker that decides where to insert checks. It is a proof engine that asks one question at every dereference: > What is the strongest proof I have that this access is safe? The answer to that question and only the answer determines what code is generated. Tether never asks "should I insert a check here." It asks "which proof obligations remain after static analysis," and emits code for the residual. Tether operates on [safe pointers](/docs/language/pointers/#safe-pointers-t) (`*T`) only. [Raw pointers](/docs/language/pointers/#raw-pointers-unsafe-t) (`unsafe *T`) carry no obligations and are never analyzed. The programmer owns their correctness. > [!WARNING] > Tether is not yet implemented. The current compiler is **Stage 1.5**; Tether development begins at **Stage 2**. The roadmap: > > - **Stage 0** (retired): the original compiler, written in C++. It was used only to bootstrap Stage 1. > - **Stage 1**: the compiler written in Kairo, built by Stage 0. No lifetime analysis. > - **Stage 1.5** (current, 0.2.0): Stage 1 migrated to Kairo's standard library. It compiles itself. No lifetime analysis. > - **Stage 2**: compiler rewritten using Kairo's extended feature set. **Tether work begins here.** > > This page describes the intended design and target semantics. The analysis is the target, not the current state. A separate formal paper will carry the full proofs; this page states the model and the obligations precisely enough to implement against, but is not itself the proof. ## In this section - [Proof Model](/docs/language/tether-proof-model/): the dereference obligation, the proof lattice and the residual table. - [Bounds and Provenance](/docs/language/tether-bounds/): pointer arithmetic, hoisting, provenance and epochs, interior pointers. - [Ownership and Promotion](/docs/language/tether-promotion/): smart-pointer promotion and stack-pointer escapes. - [Threading](/docs/language/tether-threading/): strict mode and the race-freedom rule set. - [Tether Internals](/docs/language/tether-internals/): C/C++ interop, generic code, `.amt` summaries, soundness and testing. - [Allocators](/docs/language/allocators/): global, scoped and freestanding allocators and the allocator interface. --- ## Destruction Timing Where Tether places a value's destruction depends on whether the destructor is observable. A destructor is **timing-insensitive** if and only if it does nothing but free memory the value owns and run destructors that are themselves timing-insensitive (fields, bases, owned pointees). Everything else is **observable**: a destructor that touches a global or `thread` variable, does I/O, takes or releases a lock, changes a reference count, calls C or C++, or calls any function not known to be timing-insensitive. This is a different property from being trivially destructible: a destructor with a body that only frees an owned buffer is not trivial, but it is timing-insensitive. In the rest of this section, "trivial" means timing-insensitive. **Trivial destructors** (no observable side effect just memory to reclaim) run at **last use**. Tether places the `@destroy`/`@free` as early as the final use permits, since reclaiming memory after the last use is indistinguishable from reclaiming it at the scope brace: ```kairo var *foo = @create SomeClass() // trivial destructor use(foo) // @destroy foo inserted here std::io::println(10) ``` **Non-trivial destructors** (a user-defined `op finally`, or any member with one file close, lock release, flush, disconnect) run at the **end of the owning binding's lexical scope**, in reverse declaration order. Tether does not move these to last use: ```kairo fn example() { var *cfg = @create Config(8080) // side-effecting destructor use(cfg) std::io::println(10) } // cfg's destructor runs here, at the brace not after use(cfg) ``` This is the "predictable from source" guarantee: any observable destructor side effect fires at the scope brace exactly as written. [`finally`](/docs/language/panic/#finally) blocks, lock guards, and [`NON_TRANSFER`](/docs/language/ownership/#non_transfer-types) scope guards depend on it. **Shared objects** separate two events. The **refcount decrement** happens at each `Shared` binding's own scope boundary, in reverse declaration order. The **object destructor and deallocation** happen once, when the last live `Shared` reference's scope ends and the count reaches zero which is not necessarily the last-declared binding in any single scope. Reason about shared destruction as "when the final owner goes away," not "reverse declaration order of the binding in front of me." `Weak` scope exit does not touch the count; a `Weak` simply becomes invalid once the target is freed. Arena memory is freed wholesale at scope end; see [Scoped allocator](/docs/language/allocators/#scoped-allocator). --- ## Copy Elision For [COPY types](/docs/language/ownership/#copy-types), Tether may emit a move instead of a copy when it proves the source is unused after the transfer **and** the elision is unobservable. Elision means the source's destructor runs at the transfer point instead of at its own scope exit; Tether performs it only when the source's destructor is [timing-insensitive](#destruction-timing). A `Shared` source is never elided this way: its decrement can be the one that reaches zero and runs the pointee's destructor, so it counts as observable. If the destructor has timing-sensitive side effects a flush, a lock release, a log line Tether does not elide. The copy is preserved and the source is destroyed at its lexical scope exit as written. Elision is silent precisely because it is only applied where it cannot be observed. The programmer neither opts in nor controls it, and it is never applied if the move constructor is deleted. --- ## What Tether Does Not Do - **Garbage collection.** No tracing, no mark-and-sweep, no runtime collector. Reference counting for `Shared` is the only runtime ownership cost, and it exists only where multiple ownership is required. - **Runtime borrow checking.** Aliasing is resolved at compile time. Tether does not insert runtime aliasing checks; it inserts bounds, epoch, and (for tainted residuals) access checks those are clause discharges, not borrow checks. - **Lifetime annotations.** No `'a`-style parameters, no lifetime polymorphism. Whole-program analysis infers concrete lifetimes from usage. - **Reference counting everywhere.** Single-owner pointers promote to `Unique` (no refcount); contained lifetimes are not promoted at all. Refcounting appears only under proven multiple ownership. - **Cross-language analysis.** C++ is opaque beyond the one-level heuristic on a visible body. Across the [FFI boundary](/docs/language/tether-internals/#cc-interop), Tether fails closed (taint inbound, epoch-freeze outbound) rather than guessing. --- ## Summary The whole system, in one table maps each clause's residual to its response: | Residual | Response | Tier | |--------------------------------------------------|----------------------------------------------|------| | bounds (range) | hoisted/local check, both modes | R | | formation range, unprovable | hoisted/local check at the arithmetic | R | | formation outside `[base, base+count]` (static) | compile error | N | | `<` across allocations / unprovable provenance | compile error | N | | UAF (provenance intact) | epoch compare, both modes | R | | UAF (provenance lost) | hard error | N | | nullability | compile error, both modes | N | | ownership escape (heap-promotable) | debug promote / release error | P | | stack escape (heap-promotable) | debug heap-lift / release error | P | | stack escape (non-promotable) | hard error | N | | scoped-allocator escape | hard error | N | | opaque-container escape | hard error | N | | iterator invalidation | hard error | N | | moved-from use | hard error | N | | second writer to shared allocation | hard error | N | | access residual on shared *mutable* allocation | hard error (strict mode) | N | | access residual on shared *read-only* allocation | normal Tier-R check | R | | taint (provenance recoverable) | runtime check | R | | taint (provenance opaque) | hard error (demand `unsafe`) | N | | Type | Tracked? | Promoted? | Escape | |------------------|----------|---------------------------|-------------------------------------------------------| | Plain *T (stack) | Yes | Heap-lift in debug only | Promotable: debug-lift / release-err; else hard error | | Plain *T (heap) | Yes | Debug: yes / Release: no | Release: hard error (annotate) | | unsafe *T | No | Never | Programmer's problem | | [Scoped-alloc ptr](/docs/language/allocators/#scoped-allocator) | Yes | Never | Always hard error | | Shared (thread) | Yes | n/a | One writer, or many `const` readers | | FFI smart ptr | Yes | Mapped 1:1 | Type mismatch = error | | FFI raw ptr | No | Never | Tainted; requires unsafe/launder | Tether proves every dereference safe statically when it can, and emits nothing. When only a checkable property remains, it emits the minimal check Tier R, the only runtime cost in a release build. When safety needs a program change it transforms in debug and errors in release (Tier P), and when nothing can establish safety it is a hard error in every mode (Tier N). ## See also - [Ownership](/docs/language/ownership/) - [Pointers](/docs/language/pointers/) - [Unsafe](/docs/language/unsafe/) - [Concurrency](/docs/language/concurrency/) - [Class Lifecycle](/docs/language/classes-lifecycle/) --- ## Unsafe URL: https://www.kairolang.org/docs/language/unsafe/ # Unsafe The `unsafe` keyword appears in three distinct contexts in Kairo, each serving a different purpose: | Context | Meaning | |---|---| | `unsafe { ... }` | Block that suspends Tether tracking | | `unsafe *T` | Raw pointer type with no compiler tracking | | `fn foo() unsafe -> T` | Separate function overload namespace | These are independent mechanisms that share a keyword. An `unsafe` block does not make all pointers raw, and a raw pointer does not require an `unsafe` block to use. --- ## Unsafe Blocks An `unsafe { ... }` block suspends [Tether](/docs/language/tether/) for all operations within its scope. Inside an unsafe block: - Tether does not track pointer lifetimes or provenance - Tether does not insert automatic destructors or smart pointer promotions - `forget!()` is available to permanently drop pointers from Tether tracking - `unsafe &x` can create raw pointers from safe bindings ```kairo var *x = @create i32(42) // Tether-tracked safe pointer unsafe { forget!(x) // drop x from Tether tracking c_function(x as unsafe *i32) // pass to C++ which will free it } // x is no longer tracked Tether will not auto-free it ``` ### When unsafe blocks are required An `unsafe` block is required when calling a [C/C++ function](/docs/language/c-cpp-calling/#pointers-and-references) that takes or returns raw pointers: ```kairo ffi "c++" import "native.hh"; fn main() { var *data = @create i32(100) unsafe { forget!(data) native_take_ownership(data as unsafe *i32) } } ``` An [`inline "asm"`](/docs/language/c-cpp/) block is also only allowed inside an `unsafe` block or an unsafe function; anywhere else it is an error (SC296E) with a fix-it that wraps it. ### When unsafe blocks are NOT required Calling C/C++ functions that use safe parameter types does not require an `unsafe` block: | C++ parameter type | Requires `unsafe` block | |---|---| | Value types (`int`, `float`, structs by value) | No | | References (`T&`, `const T&`) | No | | Move references (`T&&`) | No | | `std::unique_ptr` | No | | `std::shared_ptr` | No | | `std::weak_ptr` | No | | Raw pointers (`T*`, `void*`) | Yes | The FFI layer reads C++ declaration signatures and maps C++ smart pointers to Kairo's Tether-tracked equivalents automatically. `std::unique_ptr` maps to `std::Unique`, `std::shared_ptr` maps to `std::Shared`, `std::weak_ptr` maps to `std::Weak<*T>`. A mismatch between Tether's promotion and the C++ function's expected smart pointer type is a compile error. See [C/C++ Interop](/docs/language/c-cpp/) for the full FFI model. --- ## Forget `forget!()` is a [compiler intrinsic](/docs/language/macros-builtin/#compiler-intrinsic-macros) that permanently removes a pointer from Tether tracking. It is only valid inside an `unsafe` block: ```kairo var *ptr = @create Config(8080) unsafe { forget!(ptr) // Tether stops tracking ptr // ptr is now the caller's responsibility } // Tether will not auto-free ptr if nothing else frees it, this is a memory leak ``` The primary use case is [transferring ownership to C++ code](/docs/language/c-cpp-memory/) that will manage the pointer's lifetime: ```kairo ffi "c++" import "engine.hh"; fn init_engine() { var *cfg = @create EngineConfig(defaults()) unsafe { forget!(cfg) engine_init(cfg as unsafe *EngineConfig) // C++ engine now owns the allocation and will free it on shutdown } } ``` > [!CAUTION] > `forget!()` does not free memory it tells Tether to stop tracking the pointer. If the pointer is not freed by other means (C++ code, manual `std::free()`, etc.), the memory leaks. Use `forget!()` only when transferring ownership across the FFI boundary. --- ## Raw Pointers (`unsafe *T`) `unsafe *T` declares a pointer with no Tether tracking, no null checks, and no bounds checks. It is the Kairo equivalent of a raw C/C++ pointer: ```kairo var raw: unsafe *i32 = unsafe &some_value *raw = 42 // no null check UB if null ``` Raw pointers do not require an `unsafe` block to dereference or use. The `unsafe` is part of the type itself by declaring the pointer as `unsafe *T`, the programmer has already opted out of safety for that pointer. ```kairo var buf: unsafe *u8 = unsafe std::alloc(1024) buf[0] = 0xFF // no bounds check buf[100] = 0x00 // no bounds check UB if out of allocation unsafe std::free(buf) ``` See [Pointers](/docs/language/pointers/#raw-pointers-unsafe-t) for the full pointer model. --- ## Unsafe Function Overloads The `unsafe` modifier on a function creates a [separate overload](/docs/language/functions-overloading/#unsafe-overloads) in its own namespace. The caller explicitly selects the unsafe variant with the `unsafe` keyword: ```kairo fn sort(data: [i32]) -> [i32] { // safe: bounds-checked, stable sort return stable_sort(data) } fn sort(data: [i32]) unsafe -> [i32] { // unsafe: unstable sort, may reorder equal elements return quick_sort(data) } var a = sort(my_data) // calls the safe version var b = unsafe sort(my_data) // calls the unsafe version ``` ### What `unsafe` means on a function `unsafe` on a function does **not** mean "unsafe memory." Tether still guarantees memory safety in both safe and unsafe overloads. The `unsafe` qualifier signals that the function may not uphold semantic invariants that the safe version does stability, ordering, precision, idempotency, or any other contract beyond memory safety. The caller writing `unsafe sort(...)` is explicitly acknowledging: "I know this version has weaker guarantees and I accept the trade-off." ### Overload resolution Safe and unsafe overloads live in separate namespaces. They can have identical parameter types because the dispatch is determined by the presence or absence of the `unsafe` keyword at the call site: ```kairo fn process(x: i32) -> i32 { ... } // safe fn process(x: i32) unsafe -> i32 { ... } // unsafe different namespace process(42) // calls safe version unsafe process(42) // calls unsafe version ``` ### Modifier restrictions `unsafe` combines with every other function modifier except [`eval`](/docs/language/eval/#eval-functions): | Combination | Valid | |---|---| | `unsafe` + `const` | Yes | | `unsafe` + `eval` | No | | `unsafe` + `async` | Yes | | `unsafe` + `panic` | Yes | | `unsafe` + `inline` | Yes | | `unsafe` + `volatile` | Yes | `unsafe` is an overload qualifier: the other modifiers apply to the safe and unsafe versions alike. See [Functions](/docs/language/functions-declarations/#modifier-compatibility) for the full modifier compatibility table. --- ## The Safety Boundary Kairo's safety model has a clear boundary: **Inside normal code:** Tether tracks all pointer lifetimes and proves every safe dereference sound. `*T` is non-null by construction, so its dereference needs no check; a [`*T?`](/docs/language/nullables/#pointers-and-nullability) must be unwrapped or proven non-null. Where a proof is missing, the response depends on the clause (see the [Residual Table](/docs/language/tether-proof-model/#the-residual-table)): bounds and epoch residuals get a runtime check in both modes, while nullability and ownership residuals are transformed in debug (null guard, [smart pointer promotion](/docs/language/tether-promotion/)) and are hard errors in release. Everything else is a compile error. Memory safety is the compiler's responsibility. **Inside `unsafe { }` blocks:** Tether is suspended. The programmer is responsible for pointer lifetimes, null safety, and deallocation. The compiler trusts the programmer. **With `unsafe *T` pointers:** No tracking regardless of whether the code is inside an `unsafe` block. The pointer is permanently untracked by its type. **With `unsafe` function overloads:** Memory safety is still guaranteed by Tether. Only semantic invariants beyond memory safety are relaxed. ``` Memory safe? Tether tracked? Who manages lifetime? Normal code Yes Yes Compiler (Tether) unsafe { } Programmer No Programmer unsafe *T Programmer No Programmer fn foo() unsafe Yes Yes Compiler (Tether) ``` --- ## Common Patterns ### FFI ownership transfer ```kairo ffi "c++" import "lib.hh"; fn send_to_native(data: Config) { var *ptr = @create Config(data) unsafe { forget!(ptr) native_take_ownership(ptr as unsafe *Config) } } ``` ### Custom allocator ```kairo fn allocate_aligned(size: usize, align: usize) -> unsafe *void { var raw: unsafe *void = unsafe std::aligned_alloc(align, size) return raw } ``` ### Interfacing with hardware registers ```kairo fn write_register(addr: usize, value: u32) { unsafe { var unsafe *reg = addr as unsafe *u32 // integer-to-pointer cast fabricates provenance *reg = value } } ``` ### Unsafe overload for performance ```kairo fn bounds_check(arr: [i32], index: i32) -> i32 { assert index >= 0 && index < arr.length(), "out of bounds" return arr[index] } fn bounds_check(arr: [i32], index: i32) unsafe -> i32 { // caller guarantees index is valid skip the check return arr[index] } ``` --- ## Summary ```kairo // Unsafe block suspends Tether var *ptr = @create i32(42) unsafe { forget!(ptr) c_function(ptr as unsafe *i32) } // Raw pointer no tracking by type var raw: unsafe *i32 = unsafe &some_value *raw = 100 // no null check // Unsafe overload separate dispatch namespace fn compute(x: f64) -> f64 { /* precise */ } fn compute(x: f64) unsafe -> f64 { /* fast approximation */ } var precise = compute(3.14) var fast = unsafe compute(3.14) // forget!() drop pointer from Tether var *data = @create Buffer(1024) unsafe { forget!(data) // data is no longer tracked manual management required } ``` ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [Inline ASM](/docs/language/c-cpp-calling/#inline-asm) - [Pointers and References across the FFI boundary](/docs/language/c-cpp-calling/#pointers-and-references) - [Pointers](/docs/language/pointers/) - [Tether](/docs/language/tether/) - [Ownership](/docs/language/ownership/) - [Function Overloading](/docs/language/functions-overloading/#unsafe-overloads) - [Allocators & Ownership](/docs/language/c-cpp-memory/) --- ## Panic URL: https://www.kairolang.org/docs/language/panic/ # Panic `panic` is Kairo's error signaling mechanism. A function marked with the `panic` specifier can produce an error instead of its declared return type. Callers must handle the error via `try`/`catch` or propagate it by marking themselves `panic`. The compiler statically verifies that all error types are accounted for: unhandled error types are a compile error. Unlike [C++ exceptions](/docs/language/c-cpp-exceptions/), panics use no unwinding tables and no runtime. The codegen is zero-cost: every panic site becomes a tagged return value checked with a branch. > [!NOTE] > Panic is compiled, in generic functions too. Not supported yet: a panic in a generator or an `async` function, a `for` loop over a panicking `op in`, a call of a panicking `op []` that returns a pointer or of a panicking `op as`, a method that implements two requirements (or overrides a method and implements a requirement) whose panic sets differ, and keeping a caught error in another variable. See [Status](/docs/status/#not-compiled-yet). --- ## Error Types Any type can be panicked. There is no base error class, no required shape, no required operator, and no standard error module: an error type is an ordinary struct, class or enum. The type only has to be movable (an error is returned and propagated by value), and it must be a value type, not a reference or `void`. An error type may define [`op panic`](/docs/language/operator-overloading/#op-panic) to give itself a human-readable message: ```kairo struct ParseError { var message: string var position: i32 fn op panic (const self) -> string { return f"{self.message} at {self.position}" } } ``` `op panic` is optional. It takes `const self` and returns `string`. A panic can never reach `main` unhandled, so Kairo itself never needs an error's message; the message is shown only on the C++ side, where [`value_or_throw`](/docs/language/c-cpp-exceptions/#converting-to-an-exception) turns an error into an exception whose `what()` uses it. Without `op panic`, `what()` gives the type name and source location instead. Raising, propagating and catching an error never call it. - Panicking a type that isn't movable is a compile error, at the `panic`, at a [declared set](#declared-panic-sets) or at a `catch e: T` that names it. - A type you don't own (a primitive, another module's type) can get `op panic` from an [`extend`](/docs/language/extends/). - A C++ type can be panicked too: it is just a value. It can't define a Kairo operator, so its `what()` is always the type name and location. Catching C++ *exceptions* is a separate mechanism; see [Exceptions](/docs/language/c-cpp-exceptions/#exceptions). The examples on this page use these error types and functions: ```kairo struct IOError { var path: string fn op panic (const self) -> string { return f"cannot read {self.path}" } } struct RangeError { var value: i32 fn op panic (const self) -> string { return f"{self.value} is out of range" } } struct EmptyInput { fn op panic (const self) -> string { return "empty input" } } fn read_file(path: string) panic(IOError) -> string { /* ... */ } fn parse_and_validate() panic(RangeError, IOError) -> i32 { /* ... */ } ``` --- ## The `panic` Specifier Add `panic` after the parameter list to indicate a function may produce an error: ```kairo fn parse_port(input: string) panic -> i32 { if input.length() == 0 { panic EmptyInput {} } var port = std::parse(input) if port < 0 || port > 65535 { panic RangeError { value: port } } return port } ``` The `panic` statement inside the function body raises an error. The function's **panic set**, the error types it can produce, is inferred from its body: here `EmptyInput` and `RangeError`, plus whatever `std::parse` can propagate. To fix the set instead of inferring it, write it out: see [Declared Panic Sets](#declared-panic-sets). --- ## Handling Panics with `try`/`catch` Callers handle panics with `try`/`catch`. The compiler tracks every error type that can propagate from the `try` body and verifies that all types are handled: ```kairo fn load_config(path: string) -> Config { var port: i32 try { port = parse_port(read_file(path)) } catch e: IOError { std::io::println(f"cannot read file: {e.path}") port = 8080 } catch e: RangeError { std::io::println(f"bad port: {e.value}") port = 8080 } catch { port = 8080 // EmptyInput, and anything std::parse propagates } return Config(port) } ``` ### Exhaustiveness The compiler enforces that every error type reachable from the `try` body is handled. If any type is missing, it is a compile error unless the function is itself marked `panic`: ```kairo fn partial_handler() panic -> i32 { // This function only handles RangeError. // IOError propagates to the caller. try { return parse_and_validate() } catch e: RangeError { return -1 } // IOError is not caught: it propagates because this function is marked panic } ``` A bare `catch` (no type) acts as a catch-all and satisfies exhaustiveness for all remaining types: ```kairo fn safe_handler() -> i32 { try { return parse_and_validate() } catch { // handles any error type return -1 } } ``` ### Named and unnamed catch The error value can be bound to a variable for inspection, or the catch block can omit the binding: ```kairo try { risky_operation() } catch e: IOError { // e is bound: can inspect the error log_error(e.path) } catch { // no binding: catch-all, error value is discarded } ``` A catch-all can bind the error too: `catch e` holds whichever error the earlier arms did not catch. It can be re-panicked with `panic e`, which keeps the original source location. Holding it in another variable (`var copy = e`) is not supported yet. ### Arms match exact types A panic set is a set of **exact types**. There is no subtyping between error types: `catch e: Base` does not catch a panic whose type is a class derived from `Base`, and a set that holds both `Base` and `Derived` holds two distinct types, each caught by its own arm. ```kairo class NetError { fn op panic (const self) -> string { return "network error" } } class TimeoutError derives NetError { fn op panic (const self) -> string { return "timed out" } } fn fetch() panic -> string { // set: TimeoutError panic TimeoutError() } try { fetch() } catch e: NetError { // warning: NetError is not in the set; this arm never runs // ... } catch e: TimeoutError { // this arm catches it // ... } ``` > [!IMPORTANT] > This differs from C++, where `catch (const Base&)` also catches every derived exception. In Kairo each arm names one exact type, which keeps the dispatch a single compare per arm. ### Dead arms and arm order - A `catch e: T` whose `T` is not in the `try` body's set can never run. It is a **warning**, with a fix-it removing the arm, not an error: a library that removes an error from a function's set must not break every caller that still catches it. - Two arms for the same type are an error. - Any arm after a bare `catch` is an error: the bare `catch` has already handled everything. --- ## Propagation If a function calls a `panic` function without fully handling all error types, it must be marked `panic` itself. The unhandled errors propagate to the caller: ```kairo fn read_config() panic -> Config { var content = read_file("config.txt") // may panic with IOError var port = parse_port(content) // may panic with EmptyInput or RangeError return Config(port) // all of them propagate: the caller must handle them } ``` Calling a `panic` function without `try`/`catch` and without the `panic` specifier is a compile error. The error names every unhandled type; the fix-its add `panic` to the caller or wrap the call in `try`: ```kairo fn bad() -> i32 { return parse_port("8080") // compile error: parse_port may panic, but bad() is not marked panic } ``` ### Re-panic Inside a `catch` arm, `panic e` propagates the caught error to the caller, and its type joins the function's set. The error keeps its **original source location**: the site it reports is where it was first panicked, not the re-panic. ```kairo fn load() panic -> i32 { try { return parse_and_validate() } catch e: RangeError { return -1 } catch e: IOError { log_error(e.path) panic e // still reports the site inside read_file } } ``` --- ## Multiple Error Types A single function can panic with any number of different error types. Without a declared set, the compiler infers the set from the function body: ```kairo struct FormatError { var line: i32 fn op panic (const self) -> string { return f"invalid format on line {self.line}" } } fn process(path: string) panic -> Data { if !file_exists(path) { panic IOError { path: path } } var content = read_file(path) if content.length() == 0 { panic EmptyInput {} } if !validate(content) { panic FormatError { line: 1 } } return parse_data(content) } ``` Callers of `process` must handle `IOError`, `EmptyInput` and `FormatError` (plus any errors from `parse_data`), or propagate them. The order of the `panic` statements does not matter. A set is unordered: two sets holding the same types are the same set. --- ## Declared Panic Sets `panic(E1, E2)` names the set instead of inferring it. Library authors use it to pin their contract: ```kairo fn load_port(path: string) panic(IOError, RangeError) -> i32 { var text = read_file(path) // IOError: in the set return parse_port(text) // compile error: 'EmptyInput' is not in the declared panic set of 'load_port' } ``` Anything panicked or propagated outside the declared set is a compile error, labelled at the `panic` or at the propagating call, with a fix-it adding the type to the list. The list is written right after `panic`, on the same line, wherever the specifier goes: after a function's or closure's parameter list, and after a function type's. There it is always the set, never a tuple. A line break ends the specifier, and in a function body `panic (x)` is the [`panic` statement](#the-panic-specifier) with a parenthesized value. A set names at least one type: `panic()` is an error whose fix-it removes the parentheses, leaving a bare `panic`. ```kairo fn f() panic(IOError) -> (i32, i32) // the set, then a tuple return type fn g() panic -> i32 { panic (IOError { path: "x" }) // the statement, with a parenthesized value } ``` ### Where a declared set is required A bare `panic` is enough on an ordinary function. A declared set is **required** in four positions, and a bare `panic` there is an error whose fix-it writes the inferred set: | Position | Why | |---|---| | A [function type](/docs/language/functions/#function-pointers): `fn(string) panic(IOError) -> i32` | It has no body to infer from | | An [interface requirement](/docs/language/interfaces-requirements/#panicking-requirements) | No body, and it is a contract for every conformer | | A [`virtual`](/docs/language/classes-inheritance/#virtual-dispatch) method of a base class | A contract for every override | | A [closure](/docs/language/closures/#modifiers): `fn () panic(IOError) -> i32 { ... }` | A readability rule: the set is visible where the closure is written | ```kairo interface Loader { fn load(self, path: string) panic(IOError) -> string } fn run(f: fn(string) panic(IOError, RangeError) -> i32) panic -> i32 { return f("port.txt") } var retry = fn () panic(IOError) -> string { return read_file("data.txt") } ``` ### Subsets - An `override` may leave its set inferred, but the set must be a subset of the base method's. - A conforming method's set must be a subset of the interface requirement's. - A function whose set is `S` converts to a function type whose set is `S'` only when `S` is a subset of `S'`. A function that doesn't panic converts to any panicking function type. - A function used as a value (passed, stored, assigned) must declare its set: the value's type carries the set, and an inferred set is only known once the whole program is checked. The compiler's fix-it writes the inferred set. ### Public functions An inferred set on a `pub` function is API surface that changes silently when the body changes. When building a library, the compiler warns about a `pub` function whose set is inferred, with a fix-it that writes the set out. The warning is off for executables. It applies to generic functions too. --- ## Generic Functions A generic function, or a method of a generic type, may panic like any other. Its body is checked once, where it is defined, against its [bounds](/docs/language/generics/), never per instantiation, and so is its set. The set of a generic body is: - every type it panics with, which may be one of its type parameters (`panic x` with `x: T`); - the sets of the ordinary functions it calls; - the **declared** set of every [interface requirement](/docs/language/interfaces-requirements/#panicking-requirements) it calls through a bound, at the bound's arguments: through `T impl Src`, a requirement declared `panic(E)` panics with `IOError`; - the set of every generic function it calls, at that call's type arguments. ```kairo interface Source { fn read(self) panic(E) -> i32 } fn > total(a: T, b: T) panic -> i32 { // panics with E return a.read() + b.read() } fn pick(x: T, first: bool) panic -> i32 { // panics with T and Missing if first { panic x } panic Missing {} } ``` A caller sees the set at its own arguments: `total(f, g)` panics with `IOError`, and `pick(ParseError {}, true)` with `ParseError` and `Missing`. When two members of a set are the same type at some arguments (`pick(Missing {}, true)`), they are one: that call panics with `Missing` only. Everything the body does is checked at the definition, with the bound's types: a requirement's error that is neither caught nor in the function's set is an unhandled panic, and a declared set (`panic(E)`) holds the body to it, whatever the arguments will be. Interface requirements must declare their sets (see [above](#where-a-declared-set-is-required)), so a bound always says what calling through it can raise. A set may name the interface's own type parameters, as `panic(E)` does here. Two rules need the arguments: - **Arms that meet at an instance.** `catch e: T` beside `catch e: Missing` are two arms in the generic body, but at `T = Missing` both catch the same type. That is the [duplicate-arm](#dead-arms-and-arm-order) error, reported where that instantiation is used (with the chain of generic calls that reached it, when there is one). - **Ever-larger arguments.** A function that calls itself at a bigger type (`f(Box { v: x })` inside `f`) and lets that call's errors through would have a set that never stops growing. That is an error; declare the set, or catch what the recursive call raises. Not supported yet: a generic closure that panics, and a [function type](/docs/language/functions/#function-pointers) whose set names a generic parameter (`fn() panic(E) -> i32`). --- ## Try/Catch as an Expression ```kairo var port = try parse_port(input) catch e: RangeError => 8080 catch => 3000 ``` `try`/`catch` can produce a value. Each arm is `catch ... => value`, and every arm must produce the same type. `finally` is not permitted in expression form. An arm may also leave instead of producing a value: `return` from the enclosing function, or `break` / `continue` out of an enclosing loop. Such an arm has type [`!`](/docs/language/type-system/#the-never-type-), so it fits beside arms of any type: ```kairo fn port_or_default(input: string) -> i32 { var port = try parse_port(input) catch => return 3000 return port } ``` Inside a closure, `return` leaves the closure, as everywhere. See [Control Flow](/docs/language/control-flow/#trycatch-as-an-expression) for the `=>` arm rules: arm forms, line breaks, and nesting. --- ## Finally There is one `finally`: a scope-exit block. It runs when control leaves the block it is written in, however it leaves (normal exit, `return`, `break`, `continue`, or a panic), and only if execution reached it. There is no `try`/`finally` clause as in Java, C# or Python: a `finally` written after a `try`/`catch` is the same standalone `finally`, so it does **not** run when the `try` finishes, and a `return`, `break` or uncaught panic leaving the `try` never reaches it. ```kairo fn update() { try { acquire_lock() do_work() } catch e: IOError { handle_error(e) } finally { // warning: runs when update() returns, not after the try release_lock() } log("done") // runs before release_lock() } ``` Because that is easy to misread, a `finally` that directly follows a `try`/`catch` (on the same line as its closing brace or the next) is a [warning](/docs/language/diagnostics/#sc001w-finally-runs-when-the-enclosing-block-exits-like-any-finally-not-when-the-try-before-it-finishes). To clean up as soon as the `try` is done, on every way out of it, register the `finally` first, in a block of its own: ```kairo fn update() { { finally { release_lock() } // runs at this block's closing brace try { acquire_lock() do_work() } catch e: IOError { handle_error(e) } } log("done") // runs after release_lock() } ``` ### Standalone `finally` (scope exit) `finally` can appear without a preceding `try`. In this form it runs when control leaves the enclosing scope, however it leaves: normal exit, `return`, `break`, `continue`, or a panic: ```kairo fn process_file(path: string) panic { var fd = open(path) finally { close(fd) } var data = read(fd) if !validate(data) { return // finally still runs } transform(data) // finally runs here too on normal exit } ``` A standalone `finally` behaves like the [destructor](/docs/language/classes-lifecycle/#destructors---op-finally) of a local declared at the same point. It belongs to its enclosing block rather than the function, runs only if execution reached it, and runs in reverse declaration order (LIFO) together with the scope's destructors. See [Control Flow](/docs/language/control-flow/#standalone-finally-scope-exit) for full `finally` semantics. --- ## `main` and `crash!` `main` can never panic: - `fn main() panic` is a compile error. - A panic that would reach `main` unhandled is a compile error, naming each unhandled type and the call that propagates it. Every error is handled in `main` or below it. - A [script](/docs/language/modules/#scripts)'s top-level code follows the same rule: it must handle every panic. To stop the program, call `crash!()`. It terminates the process and never returns. It is not a panic: it is in no set and cannot be caught. ```kairo fn main() -> i32 { var port = try parse_and_validate() catch => crash!() return serve(port) } ``` `crash!("why")` writes `why` and a newline to stderr, then aborts; `crash!()` writes nothing. The rest of the crash family ends the program the same way, each with a message the compiler builds (what failed and its `file:line:col`): `unwrap!` on null, a failed checked `as` into a closed enum, and a failed [asserting downcast](/docs/language/casting/#downcasting-base-to-derived) `p as *D`. Integer division or remainder by zero crashes the same way, with the message `kairo: division by zero`. > [!NOTE] > A crash runs on a program that is already broken, so it does only what a signal handler may: one `write` of an already-built message (at most 4096 bytes) to stderr, then `abort()`, with any `SIGABRT` handler the program installed reset first. No allocation, no locks, no Kairo code runs. `crash!` is a macro defined in the builtin library ([what it may do](/docs/language/macros-builtin/)). --- ## Panic and No-Return (`!`) A function with return type `!` can never return normally: it crashes, loops forever, or calls another no-return function. The `panic` specifier and `!` cannot coexist, because `panic` implies an alternative return path (the error), while `!` guarantees no return at all: ```kairo struct FatalError { var message: string fn op panic (const self) -> string { return self.message } } fn fatal(msg: string) panic -> ! { // compile error: panic and ! are contradictory panic FatalError { message: msg } // invalid, panic implies an error return, but ! means no return at all } fn fatal(msg: string) -> ! { std::io::println(msg) crash!() // valid: never returns } ``` See [Functions](/docs/language/functions/#no-return-) and [Type System](/docs/language/type-system/#the-never-type-) for `!` semantics. --- ## What Is Not a Panic Some failures stop the program instead of producing an error value. None of them is in a panic set, and none can be caught: - `crash!()`. - [`unwrap!`](/docs/language/nullables/) on a null value. - A failing [asserting downcast](/docs/language/casting/#downcasting-base-to-derived), `p as *Derived`. The compiler warns on every asserting downcast and suggests the checked form `p as *Derived?`, which yields null instead. - Integer division or remainder by zero ([overflow behavior](/docs/language/primitives/#overflow-behavior)). A bad cast or a null unwrap is a programmer error, not a recoverable condition. Making it a panic would add an error type to every function that downcasts, and to every caller above it. --- ## Where Panics Are Not Allowed - **Global initializers.** A `panic`, a `try`, or a call to a panicking function in the initializer of a global variable is a compile error: there is no function for the error to propagate to. A [script](/docs/language/modules/#scripts)'s top-level variables are initialized as part of its top-level code, so they may use `try`. - **Constructors and destructors.** No constructor or destructor can panic, and no panic may escape one: handle it inside, or stop with `crash!()`. Construction that can fail belongs in a static factory function. See [Class Lifecycle](/docs/language/classes-lifecycle/#constructors-and-destructors-never-panic). - **`eval` functions.** `panic` in a function evaluated at compile time is an error. See [Eval](/docs/language/eval/). - **Generators and `async`.** For a [generator](/docs/language/functions-generators/) or an [`async`](/docs/language/concurrency/) function, an error surfaces where the caller resumes it: at the `next()` call (including the hidden one in a `for` loop) or the `await`, which handles or propagates it like any other panicking call. A `panic`, or a panicking call, inside a generator or `async` body is not supported yet. --- ## Codegen Panics compile to zero-cost tagged return values. There are no [unwinding tables](/docs/language/attributes/#unwinding), no runtime exception handler, and no stack unwinding. A function marked `panic` returns a tagged union holding either the success value or one of the errors in its set, together with the source location where the error was raised. Every Kairo function, panicking or not, stays `noexcept` in its generated C++. At a call site, the compiler tests the tag where the call is, so arguments still run left to right and a call on the right of `&&` or `||` still runs only when that side is evaluated. On success, execution continues with the value. An error the caller doesn't handle is returned to its own caller as it is, keeping its tag and source location; the payload is moved, or copied as raw bytes when the two results have the same layout. A call in tail position (`return g()`) needs no test at all. `try`/`catch` lowers to one tag compare per `catch` arm, in order, with a bare `catch` as the final fallback, and a catch binding refers to the error in place. An error type's tag is the same in every set that contains it, so passing an error up through callers with larger sets never translates it. When a `try` body holds a single panicking call, the arms read that call's result directly. With more than one, the first error is moved into storage that is only ever built on the error path, and moved out again before any arm runs, so every way of leaving an arm (falling through, `return`, `break`, `continue`, a re-panic) destroys it exactly once. An override of a `virtual` method returns its base method's result type, whatever its own (smaller) set: callers through the base and through the derived type see one function. A generic function is one C++ template for every instantiation, and its result names its type parameters. The C++ compiler orders that set at each instantiation, removing a type that appears twice, into the same order every other function with that set uses, so a generic function's result and a concrete caller's are one type. The compiler checks that ordering against its own at each instantiation it sees. A function value whose type allows more errors than the function it holds (or any, when the function cannot panic) is wrapped where it is converted. This means: - No runtime overhead on the success path beyond a single branch (which the branch predictor handles efficiently) - No stack unwinding: errors propagate via normal return values - No unwinding tables for panics: smaller executables - No Kairo function throws; only a C++ exception can unwind through Kairo code > [!NOTE] > The same `try`/`catch` syntax can also catch an exception thrown by C++ code called inside the `try` (`catch e: cxx::std::exception`). That path does use the platform unwinder: the `try` becomes a C++ `try` inside the still-`noexcept` function. See [Exceptions](/docs/language/c-cpp-exceptions/#c-to-kairo) in C/C++ Interop. > > C++ code calling a panicking Kairo function gets the tagged union by value and reads it with `::builtin::ok`, `value`, `is`, `error` and `site`, or converts it to an exception with `::builtin::value_or_throw`. See [Kairo to C++](/docs/language/c-cpp-exceptions/#kairo-to-c-kairo-never-throws). > [!NOTE] > The `panic` statement inside a function body (`panic SomeError { ... }`) does not halt the program. It produces the error as the function's return value. The term "panic" refers to the signaling mechanism, not to a crash. Because an error can never reach `main` unhandled, a panic never terminates the program; [`crash!`](#main-and-crash) does. ### Performance: keep error types small The result of a panicking function is returned in registers only while it is at most 16 bytes (on x86-64): an 8-byte header holding the tag and the source location, plus the largest of the return type and the error types in its set. When every payload is at most 8 bytes, the result travels in two registers. One large error type in a set changes that for every function whose result has that set: they all return through memory. That is correct, only slower. The compiler emits a remark when a result type exceeds 16 bytes, naming the payload that pushed it over. To keep a large error cheap, store its bulky part behind a pointer, or give the detailed context its own error type that only cold paths produce. --- ## Summary ```kairo // An error type: any movable type (op panic gives it a message) struct DivideByZero { fn op panic (const self) -> string { return "division by zero" } } // Function that may panic; its set is inferred: DivideByZero fn divide(a: i32, b: i32) panic -> i32 { if b == 0 { panic DivideByZero {} } return a / b } // A declared set fn checked_divide(a: i32, b: i32) panic(DivideByZero) -> i32 = divide(a, b) // Full handling: no panic propagation fn safe_divide(a: i32, b: i32) -> i32 { try { return divide(a, b) } catch e: DivideByZero { std::io::println("error: division by zero") return 0 } } // Partial handling: propagates unhandled types fn partial() panic -> i32 { return try parse_and_validate() catch e: RangeError => -1 // IOError propagates } // Expression form, and an arm that leaves fn expression_forms(s: string) -> i32 { var result = try divide(10, 0) catch => 0 var port = try parse_port(s) catch => return result return port } // A closure declares its set var risky = fn () panic(DivideByZero) -> i32 { return divide(1, 0) } // A generic body: its set is the requirement's, at the bound (E) fn > first(src: T) panic -> i32 { return src.read() } // Scope exit fn with_cleanup() panic { var resource = acquire() finally { release(resource) } do_work(resource) } // Stopping the program fn main() -> i32 { return try partial() catch => crash!() } ``` ## See also - [Control Flow](/docs/language/control-flow/#error-handling) - [Assert](/docs/language/control-flow/#assert) - [Operator Overloading: `op panic`](/docs/language/operator-overloading/#op-panic) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [Unwinding](/docs/language/attributes/#unwinding) - [Requires and Panic](/docs/language/requires/#requires-and-panic) - [Where and Panic](/docs/language/where/#where-and-panic) - [Closure Modifiers](/docs/language/closures/#modifiers) - [Diagnostics](/docs/language/diagnostics/) --- ## Compile-Time Eval URL: https://www.kairolang.org/docs/language/eval/ # Compile-Time Eval The `eval` keyword forces compile-time evaluation. An `eval` variable, function, or control flow construct must be fully resolvable at compile time if it depends on runtime values, the compiler emits an error. There is no "maybe compile-time, maybe runtime" mode. `eval` means compile-time, always. --- ## Eval Variables `eval` declares a [binding](/docs/language/variables/#compile-time-constants-eval) whose value is computed at compile time. The result is baked into the binary as a constant: ```kairo eval PI = 3.14159265358979 eval MAX_BUFFER = 1024 * 1024 eval HEADER_SIZE = sizeof u32 + sizeof u16 + sizeof u8 ``` `eval` bindings are implicitly `const` they cannot be reassigned (writing `eval const` or `const eval` is accepted and means the same). The initializer must be a compile-time evaluable expression. An `eval` binding or `eval fn` can be declared anywhere a declaration can: at file scope, inside a `module`, as a class member, or in a function body. An imported `eval` binding is a compile-time constant in the importing module too (`eval NEXT = lib::N + 1`), and so is it to C++ code that includes the module. ### Type annotation Type annotations are optional. The compiler infers the type from the initializer: ```kairo eval N = 10 // i32 eval NAME = "Kairo" // string eval N: u64 = 10 // explicitly u64 ``` ### Usage as generic arguments `eval` variables can be used wherever a compile-time constant is required, including array sizes and [generic arguments](/docs/language/generics/): ```kairo eval BUFFER_SIZE = 256 var buffer: [u8; BUFFER_SIZE] eval TABLE_WIDTH = 16 eval TABLE_HEIGHT = 16 var grid: [[f64; TABLE_WIDTH]; TABLE_HEIGHT] ``` --- ## Eval Functions An `eval` function must be fully evaluable at compile time. The compiler executes it during compilation and replaces the call site with the result: ```kairo eval fn factorial(n: i32) -> i32 { if n <= 1 { return 1 } return n * factorial(n - 1) } eval FACT_10 = factorial(10) // computed at compile time: 3628800 ``` ### Calling other eval functions Eval functions can call other eval functions: ```kairo eval fn square(x: i32) -> i32 = x * x eval fn sum_of_squares(n: i32) -> i32 { var total = 0 for i in 1..=n { total += square(i) } return total } eval RESULT = sum_of_squares(10) // 385 ``` ### Recursion Eval functions can be recursive. The compiler evaluates the recursion at compile time: ```kairo eval fn fib(n: i32) -> i32 { if n <= 1 { return n } return fib(n - 1) + fib(n - 2) } eval FIB_20 = fib(20) // 6765 ``` > [!WARNING] > Deeply recursive eval functions can significantly increase compile times. The compiler may impose a recursion depth limit to prevent unbounded compilation. --- ## Restrictions Eval bodies must be deterministic and free of side effects. The following are not permitted inside `eval` functions or `eval` variable initializers: | Not allowed | Reason | |---|---| | Heap allocation (`@create`, `[T]` growth) | No runtime allocator at compile time | | IO operations (file, network, console) | Side effects | | Pointer operations (`*T`, `unsafe *T`) | No addressable memory at compile time | | `async` / `await` / `spawn` | No runtime scheduler at compile time | | `panic` | No runtime error handler at compile time | | Global, static, or thread variables that are not `eval` (a `const` global is initialized at run time) | Side effects across evaluations; no value at compile time | | Calls to non-`eval` functions | Cannot guarantee compile-time evaluation | | Locals whose type has a non-trivial destructor | No runtime to run it at compile time | | A `where` clause on an `eval` function | Use `requires` | ### What is allowed | Allowed | Examples | |---|---| | Arithmetic and logic | `+`, `-`, `*`, `/`, `%`, `&&`, `\|\|`, `!` | | Comparisons | `==`, `!=`, `<`, `>`, `<=`, `>=` | | Control flow | `if`/`else`, `for`, `while`, `loop`, `match` | | Local variables | `var`, `const` within the eval body | | Calling other `eval` functions | `eval fn` calls | | `sizeof`, `alignof` | Type size queries | | `typeof` (type position) | Compile-time type resolution | | Struct/enum construction (trivial) | Literal aggregate initialization | | String literals | `eval NAME = "Kairo"`, `NAME.len`, a `string` parameter or result of an `eval fn` (not f-strings, which format into a heap buffer) | | Fixed-size arrays (`[T; N]`) | Stack-like allocation in the evaluator | --- ## Eval If `eval if` selects a branch at compile time. The condition must be a compile-time constant. Only the selected branch is compiled the others are discarded entirely (no codegen, no type checking): ```kairo eval if defined!(__linux__) { fn init_platform() { /* linux-specific */ } } else if defined!(_WIN32) { fn init_platform() { /* windows-specific */ } } else { fn init_platform() { /* fallback */ } } ``` `eval if` can appear at the top level, in a `module` or in a class body (selecting between declarations) or inside function bodies (selecting between code paths). The declarations of the selected branch belong to the enclosing scope, exactly as if the `eval if` were not there: at file scope and in a module they are the scope's declarations, in a class body a `var` is a field and a `fn` a method, and in a function body the branch's locals are the function's. Outside a function body the condition decides which declarations exist. It may use literals, `eval` constants (including ones an earlier `eval if` declared), `!`, `&&`, `||`, comparisons, integer arithmetic, [`defined!`](/docs/language/macros-builtin/#conditional), and type facts: `sizeof` and `alignof` of builtins, pointers, arrays, and plain enums and structs of them, and `is_trivially_copyable!(T)` / `is_trivially_destructible!(T)` of any concrete type. A condition that reads a type fact is decided once types are known, and the compiler checks its answer against C++'s, so the branch kept is the one C++ would keep. Its branches may declare functions, constants and fields, not types. Calling an `eval fn` there is an error, and so is a type fact that depends on a generic parameter: a generic's members are the same for every instantiation, so select a type instead, with a partial specialization chosen by a `requires` clause. Inside a function body a condition that depends on a generic parameter (`sizeof T`) is decided per instantiation. ```kairo eval if sizeof usize == 8 { eval WORD_BITS = 64 } else { eval WORD_BITS = 32 } ``` ```kairo struct Plain { var x: i32 } class Holder { eval if is_trivially_copyable!(Plain) { var fast: Plain // the member set is chosen once types are known } else { var slow: *Plain } } ``` ```kairo fn process(x: T) -> T { eval if sizeof T <= 8 { return fast_path(x) } else { return slow_path(x) } } ``` ### Type-based branching `eval if` combined with [`typeof`](/docs/language/type-system/#compile-time-typeof) enables type-specialized code paths in generic functions: ```kairo fn serialize(value: T) -> [byte] { eval if typeof T == i32 { return int_to_bytes(value) } else if typeof T == string { return value.to_bytes() } else { return generic_serialize(value) } } ``` The unselected branches are not type-checked, so they can contain code that would be invalid for the current `T`. This is the mechanism for writing type-specialized generic code without separate [overloads](/docs/language/functions-overloading/). > [!NOTE] > Not yet: today a generic body is checked once against its bounds, so both branches are type-checked and the example above does not compile. See [Status](/docs/status/). See [Control Flow](/docs/language/control-flow/#compile-time-branching) for `eval if` in the context of control flow. --- ## Eval For `eval for` unrolls a loop at compile time: the body is compiled once per value, and in each copy the loop variable is a compile-time constant, so it can be tested with `eval if`: ```kairo fn fill_squares(@inout table: [i32; 16]) { eval for i in 0..16 { table[i] = i * i // sixteen assignments, no loop at run time } } var squares: [i32; 16] fill_squares(&squares) ``` What an `eval for` can iterate: | Iterable | Example | |---|---| | A range whose bounds are compile-time values | `eval for i in 0..N`, `eval for i in -3..=3` | | An `eval` array, or an array literal of compile-time values | `eval for p in PRIMES` | | A call of an `eval` generator | `eval for k in evens(10)` | Anything else (a run-time bound, a `var` array, a generator that is not `eval`) is a compile error. `continue` and `break` work as in any loop, and so does `return` out of the enclosing function. An `eval` generator is an `eval fn` that yields. It runs at compile time, so it can do whatever an `eval fn` can, loops and conditions included, and the `eval for` iterates the values it yielded: ```kairo eval fn evens(n: i32) -> yield i32 { for var k: i32 = 0; k < n; ++k { if k % 2 == 0 { yield k } } } fn sum_evens() -> i32 { var total = 0 eval for e in evens(10) { total += e } // 0 + 2 + 4 + 6 + 8 return total } ``` An eval generator can only be iterated by an `eval for`. In each copy the loop variable is a constant, so it can also size an array or be a generic value argument: ```kairo eval for i in 0..3 { var row: [i32; i + 1] // 1, 2, then 3 elements row[i] = 1 } ``` Inside an `eval fn` the whole function already runs at compile time, so an `eval for` there is an ordinary loop, and its bounds may be the function's parameters (see `sum_range` in the [Summary](#summary)). --- ## Eval and Types `eval` works with any type that can be constructed and manipulated at compile time: ### Primitives All integer, float, bool, char, and string types are eval-compatible: ```kairo eval X = 42 eval PI = 3.14159 eval FLAG = true eval INITIAL = 'K' eval NAME = "Kairo" ``` A string literal is a compile-time value wherever it is used at compile time: an `eval` binding, the body of an `eval fn`, an argument of an `eval fn` called from ordinary code, a field of an eval class. An `eval fn` can take and return a `string`, and an eval class can hold one: ```kairo eval fn greet() -> string { return "hi!" } eval GREETING = greet() class Config { pub var label: string eval fn Config(self, label: string) { self.label = label } } eval DEFAULT = Config("default") ``` An f-string is not a compile-time value: it formats into a buffer allocated at run time. The primitives' [limits](/docs/language/primitives/#limits) are compile-time values too: `eval BIG = u32::MAX`, `eval TINY = f64::MIN_POSITIVE`, and `eval if usize::BITS == 64 { ... }`. ### Fixed-size arrays ```kairo eval PRIMES = [2, 3, 5, 7, 11, 13, 17, 19] eval IDENTITY: [f64; 4] = [1.0, 0.0, 0.0, 1.0] ``` ### Structs (trivially constructible) ```kairo struct Point { var x: f64 var y: f64 } eval ORIGIN = Point { x: 0.0, y: 0.0 } eval UNIT_X = Point { x: 1.0, y: 0.0 } ``` ### Enums (plain and ADT) ```kairo enum Mode { Debug, Release, Test } eval BUILD_MODE = Mode::Release ``` ### Types that are NOT eval-compatible Classes with constructors that are not marked `eval`, classes and function who leak allocations across the function boundary, can not be used in `eval` context. --- ## Eval vs Const | | `eval` | `const` | |---|---|---| | Evaluation time | Compile time only | Runtime (at initialization) | | Initializer | Must be compile-time evaluable | Any expression | | Reassignment | No | No | | Can use in array sizes | Yes | No | | Can use as generic argument | Yes | No | | Heap allocation in initializer | No | Yes | | IO in initializer | No | Yes | [`const`](/docs/language/variables/#constants) is an immutable binding. `eval` is a compile-time computed value. Use `const` for values that are fixed after initialization but may depend on runtime computation. Use `eval` for values that must be known at compile time. ```kairo const config = load_config("config.toml") // runtime: reads a file eval MAX_CONNECTIONS = 1024 // compile time: baked into binary ``` --- ## Eval and Requires Clauses `eval` expressions are valid in `requires` clauses. When a `requires` clause contains only `eval`-compatible expressions, it is checked at compile time: ```kairo fn stack_alloc() -> T requires sizeof T <= 4096 { // guaranteed at compile time: T fits on the stack } ``` > [!WARNING] > Using `eval` and [`where`](/docs/language/where/#what-where-cannot-do) will cause a compile error. Only `requires` based bounding is allowed in a `eval` context. See [Requires Clauses](/docs/language/requires/) for the full constraint system. --- ## Eval in Classes Inside a class, `eval` marks three different things: - **An `eval` field** is a compile-time constant of the class, one value shared by every object (like a `static` field, but computed at compile time). It is read as `ClassName::NAME` and cannot be assigned. - **An `eval` method** runs at compile time. It can be called wherever its object and arguments are compile-time values; it takes `const self` to be called on an `eval` object (an `eval` binding is const). - **An `eval` constructor** makes the class an *eval class*: its objects can be built at compile time, so an `eval` binding can hold one. The same constructor builds an object at run time too, as long as its arguments are compile-time values. An `eval` field can be an array length (`[i32; Grid::W]`), also for a field of its own class when its initializer is plain arithmetic over literals and constants. One whose value has to be computed by calling an `eval fn` cannot size a field of its own class: inside its own body the class is still incomplete, so the value does not exist there yet. The compiler reports it (SC116E) and offers to move the constant to module scope, where it can size the field. For the same reason, a field's length may call an `eval fn` (`var a: [i32; size()]`) only when that function does not itself need the class: one that takes `sizeof` of it, builds a local of it or is a method of it is an error. A class can mix `eval` and regular members; regular methods cannot be called from compile-time code. A class with a non-trivial [destructor](/docs/language/classes-lifecycle/#destructors---op-finally) cannot be an `eval` value: a compile-time object is never destroyed. A destructor cannot be `eval` (SC290E). An `eval` constant cannot have a slice type yet (SC116E); use a fixed array. ```kairo eval FNV_OFFSET: u64 = 2166136261 eval FNV_PRIME: u64 = 16777619 class Hasher { pub eval SEED: u64 = FNV_OFFSET // a class constant pub var state: u64 // per-object state, set by the constructor eval fn Hasher(self, start: u64) { self.state = start } eval fn mix(const self, b: u64) -> u64 { return (self.state ^ b) * FNV_PRIME } } eval H = Hasher(Hasher::SEED) // a compile-time object eval MIXED = H.mix(7) // computed at compile time ``` ## Summary ```kairo // Eval variable eval MAX_SIZE = 1024 * 1024 eval TABLE_SIZE = 256 // Eval function eval fn power(base: i32, exp: i32) -> i32 { if exp == 0 { return 1 } return base * power(base, exp - 1) } eval TWO_TO_16 = power(2, 16) // 65536 // Eval as array size var buffer: [u8; MAX_SIZE] // Eval if (platform selection) eval if defined!(__linux__) { eval CACHE_LINE = 64 } else { eval CACHE_LINE = 128 } // Eval if (type specialization) fn zero() -> T { eval if typeof T == i32 { return 0 } else if typeof T == f64 { return 0.0 } else if typeof T == string { return "" } else if typeof T == bool { return false } } // Eval for (compile-time loop) eval fn sum_range(n: i32) -> i32 { var total = 0 eval for i in 1..=n { total += i } return total } eval SUM_100 = sum_range(100) // 5050 ``` ## See also - [Compile-time constants](/docs/language/variables/#compile-time-constants-eval) - [Compile-time `typeof`](/docs/language/type-system/#compile-time-typeof) - [Conditional macros](/docs/language/macros-builtin/#conditional) - [Requires Clauses](/docs/language/requires/) - [Generics](/docs/language/generics/) - [Macros](/docs/language/macros/) - [Attributes](/docs/language/attributes/) --- ## Modules URL: https://www.kairolang.org/docs/language/modules/ # Modules Kairo's module system maps source files and directories to namespaces. Every `.k` file is a module. A directory containing a `module.k` entry file is a library. Use the `module` keyword to declare namespaces within a file, similar to C++ `namespace`. See [Imports](/docs/language/imports/) for how to bring names from modules into scope. ## File-to-Module Mapping Each `.k` file is automatically a module named after the file (without the `.k` extension): ``` project/ main.k <- module "main" math.k <- module "math" utils/ module.k <- library entry for "utils" strings.k <- module "utils::strings" io.k <- module "utils::io" internal/ helpers.k <- module "utils::internal::helpers" ``` Nested files create nested module names via `::`. A file at `utils/io.k` is accessible as the module `utils::io`. ### Module paths are C++ namespaces A module's path is exactly its C++ namespace. `utils/strings.k` in a library named `utils` is `utils::strings` in Kairo and `namespace utils::strings` in the [emitted C++](/docs/language/c-cpp-exposing/#what-a-kairo-declaration-looks-like-in-c); a `module codec { }` block inside it is `utils::strings::codec`. The mapping is fixed by the file's location in its library or [search directory](#search-directories-and-library-names), not by how any importer spelled the import, not by an alias, and not by the directory a library happens to be checked out in. So the C++ name of a declaration is the same in every build of the same tree. This holds for the files you compile, too. A `.k` named on the command line, or included from C++, is a module like any other, with the path an import of it gets: compiled from `project/`, `utils/io.k` is `utils::io` whether it is compiled, imported or included. So `kcc -c utils/io.k` in one run defines `utils::io::read_file`, and a `main.k` compiled in another run that imports `utils::io` links against it. A path segment that is not a valid C++ identifier is rewritten into one (`operator.k` is `namespace operator_`). `main` is the exception: a file-scope `fn main` is the program's global `int main` in whatever file it is declared, never in a namespace, and so is the `main` a [script](#scripts) gets. A `main` inside a `module foo { }` block is the ordinary function `foo::main`. A file outside every [search directory](#search-directories-and-library-names) and every [library](#naming-a-library) has no module path. Its declarations are emitted in a namespace named after the file's stem (`/tmp/scratch.k` becomes `namespace scratch`), its `priv` and `internal` declarations sit in an unnamed namespace and cannot be reached from any other translation unit, and it has no header. A file-scope declaration with no visibility written is `priv`, or `prot` when a `module.k` is above the file (see [Visibility on Top-Level Declarations](#visibility-on-top-level-declarations)). Two files under one root that both open `module codec` reopen one namespace, as in C++. Reopening never crosses a root. ## Scripts A file named on the command line (by `kairo` or `kcc`) that has statements at the top level and no `fn main` is a **script**: its top-level statements are the program, run in order as the body of a `main` the compiler writes. The end of the file returns `0`; a top-level `return` returns from that `main`, and its value, an integer, is the exit status. ```kairo fn load() -> i32 { return 42 } const LIMIT: i32 = 10 // a constant: initialized before anything runs var answer = load() // not a constant: runs here, at its line println(f"start {LIMIT}") println(f"answer {answer}") if answer > LIMIT { return 1 } // exit status 1 ``` Every top-level `var`, `const`, `static`, `thread` and `eval` stays a global: functions in the file can name it. A binding whose initializer is a constant (a literal, `sizeof` / `alignof`, or an integer the compiler can evaluate) is initialized before the first statement, as any global is; so are `eval` and `thread` bindings and a binding with no initializer. Every other initializer runs at its own line, in order with the statements around it. Reading such a variable before its line has run is an error when the compiler can see it: a read in the top-level code above the line, a read in the variable's own initializer, or a top-level call, above the line, of a function in the file that reads it on every path. Anywhere the order cannot be seen (in a function called through another function, a method, a closure), the read is checked when it runs, and the program stops with `script variable 'x' used before its line ran (file:line)`, in every build mode. Values whose line has run are destroyed when the program ends, in reverse order, after the last statement and on every `return`. A file with `fn main` cannot also have top-level statements, and only the file the program starts from runs them: a top-level statement in an imported module, or in a `.k` file a C++ file includes, is an error. Every command-line input may be a script, but two scripts linked into one program are an error naming both (compiling them with `-c` and no link is fine). A `jump!` at the top level may not cross a line whose initializer runs there. See [Diagnostics](/docs/language/diagnostics/#scripts) for the errors, and [Implementation Status](/docs/status/) for what is not supported yet. ## Library Entry Files A directory with a `module.k` file is a **library**. The entry file controls what the library exports publicly: ```kairo // utils/module.k pub import self::strings // re-export utils/strings.k pub import self::io // re-export utils/io.k priv import self::internal // NOT re-exported (implementation detail) ``` An entry file reaches the files beside it with [`self::`](/docs/language/imports/#sibling-imports): [`pub import self::strings`](/docs/language/imports/#re-export-pattern) resolves to `utils/strings.k`. In a [named library](#naming-a-library) a plain path works too, since a library's files resolve plain paths from the library's own top directory; `self::` says the same thing in any directory, named or not. Consumers of the library see only the public API: ```kairo utils::strings::trim(" hello ") // from utils/strings.k utils::io::read_file("data.txt") // from utils/io.k // utils::internal::... // compile error: not exported ``` The library entry file is the public face of the library. Use it to re-export submodules, hide internal organization, and present a clean API boundary. ## Search Directories and Library Names The compiler finds modules in **search directories**: the working directory, and every directory given with `-I`. A search directory has no name of its own. A file under one is its path relative to that directory, so with `kairo main.k -I vendor`, `./math.k` is `math` and `vendor/text/utf8.k` is `text::utf8`. The folder name `vendor` is not part of either path. `-I` is also Clang's `-I`. The same directory is searched for the headers of C and C++ inputs, for [`ffi` header imports](/docs/language/imports/#ffi-header-imports), and for [`#include "foo.k"`](/docs/language/c-cpp-toolchain/#how-kcc-works) in C++, so a `.k` file can sit next to the headers that include it. `--cxx-include` and `--ffi-include` add a directory for Clang only. ### Naming a library A library gets a name from its `module.k`. When the first declaration in `module.k` is a bare `module` followed by a module path, that path is the library's name, whatever the folder is called: ```kairo // vendor/geometry/module.k module geo pub import self::shapes ``` ```kairo ``` Every file under the directory is `geo::::`, whether it is imported, compiled on its own (from any directory, including the library's own or one inside it), or included from C++: the compiler finds a file's library by walking up from the file to the nearest `module.k` that names one, past the working directory and any `-I` directory. So `kcc -c inner/x.k` run in `vendor/geometry`, `kcc -c x.k` run in `vendor/geometry/inner`, and an importer anywhere all agree that the file is `geo::inner::x`. A name can have several segments (`module acme::tools`). The standard library's name comes from the compiler, which registers `Lib/std` as `kairo::std` and lets source write `std` to reach it. `Lib/std/module.k` says `module kairo::std` as well, and the compiler checks that the two agree. The bare `module name` declaration is only allowed in a `module.k`, and only as its first declaration, which is the one the compiler reads the name from. Anywhere later in a `module.k`, or a second time, it is an error. In any other file it is an error that points at the block form, `module name { ... }`, which declares a [namespace](#module-namespaces) inside the file. The compiler looks for named libraries in each search directory and in its immediate subdirectories. It does not search deeper, because a search directory can be a whole repository. A `module.k` deeper in the tree still names the files under it, but its library cannot be imported by name from outside it. Inside it, its files import each other by the library's name (`import geo::shapes`) or by their path in it (`import shapes`), as in any library. Import a library by its name. A file in a library never falls back to the search directories: a library does not depend on what one build's command line contains. Files beside each other can always use [`self::`](/docs/language/imports/#sibling-imports), and files anywhere in one module [`module::`](/docs/language/imports/#module-imports). > [!NOTE] > Older compilers named a directory after its folder (`-I ~/foo` was library `foo`) or with `-I name=dir`. Both are gone. An `-I` with an `=` that is not an existing directory is an error that says where the name goes: put `module name` as the first line of that directory's `module.k`. ### Collisions One module path must mean one file, so the compiler never chooses between two files that claim the same path: - Two libraries with the same name are an error (R018E) before anything is compiled. Rename one library's `module` declaration. - The same path in two search directories is an error (R017E) at the import that reaches them. With `./a.k` and `inc/a.k` under `-I inc`, both files are module `a`, so `import a` reports both. Remove or rename one, or give one directory a `module.k` that names it as a library. - Two files that end up with one module path any other way are an error (R018E) that names both: a deeper `module.k` claiming a name another library already has, or two files given on one command line from two search directories (`kairo a.k inc/a.k -I inc`, rejected before either is compiled, since both would be module `a` and write one object). - A file and a library entry with one name in the place an import looks (`util.k` and `util/module.k`) are an error (R005E) at the import that reaches them. Rename or remove one. Giving the same directory twice (`-I inc -I inc`, or a symlink and the directory it points to) is not a collision, and neither is an `-I` naming the standard library's own directory. Because a search directory has no name, several `-I .../include` directories do not collide with each other. ## Module Namespaces The `module` keyword declares a namespace within a file. It is equivalent to C++ `namespace`: ```kairo module serialization { pub fn to_json(data: Config) -> string { ... } pub fn from_json(input: string) panic -> Config { ... } priv fn escape_string(s: string) -> string { ... } } serialization::to_json(my_config) ``` ### Anonymous Modules A module without a name creates a scope for grouping declarations without introducing a named namespace: ```kairo module { var internal_state: i32 = 0 // not accessible from outside this block } ``` ### Nested Modules Modules can be nested: ```kairo module api { pub module v1 { pub fn handle_request(req: Request) -> Response { ... } } pub module v2 { pub fn handle_request(req: Request) -> Response { ... } } } api::v1::handle_request(req) api::v2::handle_request(req) ``` ## Module Visibility Modules themselves have visibility. The default is `pub`: ```kairo pub module api { // accessible to consumers fn handle_request(req: Request) -> Response { ... } } priv module cache { // only accessible within this file var store: {string: Data} = {} } prot module platform { // accessible within this file and sibling files in the library fn detect_os() -> string { ... } } ``` ### Visibility Scopes | Modifier | Scope | |---|---| | `pub` | Everywhere: any file that imports this one | | `prot` | Every file of the declaring file's module | | `priv` | The declaring file only | A file's **module** is the directory tree under the nearest directory, at or above the file, that holds a `module.k`. The `module.k` does not have to name a library (an empty one is enough): it marks where a module starts. That directory is also the **module root** that [`import module::x`](/docs/language/imports/#module-imports) resolves from, so the files that share `prot` are exactly the files one `module::` path reaches. `prot` (protected) reaches every file anywhere under that directory, including subdirectories that have no `module.k` of their own; a deeper `module.k` starts a separate module. This is analogous to "package-private" in other languages. A file with no `module.k` above it belongs to no module, and its `prot` reaches only what `priv` reaches: the file itself (and, for a class member, the classes deriving from it). Using such a `prot` declaration from another file is the same error as using a `priv` one, with a warning (SC272W) on the use that says a `module.k` is missing to share it. A module (namespace) block written with no modifier takes no visibility of its own: each declaration in it has its own. ## Module Reopening A module can be reopened across multiple files to extend its contents: ```kairo // encoding.k pub module codec { pub fn encode_base64(data: [byte]) -> string { ... } } ``` ```kairo // compression.k pub module codec { pub fn compress(data: [byte]) -> [byte] { ... } } ``` ```kairo // main.k encoding::codec::encode_base64(data) // defined in encoding.k compression::codec::compress(data) // defined in compression.k ``` ### Reopening Rules - Reopening a module with different visibility than the original is a compile error. - Reopening may only **add** new top-level declarations (functions, types, constants). It cannot modify existing declarations or add members to types defined in the original. - Both declarations must be at file scope (not nested inside other modules). ## Scope Resolution (`::` The `::` operator resolves names uniformly across all scoping contexts: | Context | Example | |---|---| | Module access | `std::io::println(...)` | | Library submodule | `math::vector::cross_product(...)` | | Class static members | `Counter::count` | | Enum variants | `Direction::North` | | Nested types | `Packet::Header` | | Base class methods | `Base::method(self)` | There is no separate syntax for module access vs type member access, all use `::`. ## The Standard Library (`std`) `std` is not automatically imported. It must be imported explicitly: ```kairo std::io::println("hello") @create i32(42) ``` Individual items can be imported selectively: ```kairo println("hello") ``` [**Core language primitives**](/docs/language/primitives/) (`i32`, `string`, `bool`, `[T]`, etc.) and **built-in syntax** (`if`, `for`, `match`, etc.) are always available without any import. Only **standard library functions and types** (`std::io::println`, `std::parse`, `std::Shared`, etc.) require an explicit import. See [Imports](/docs/language/imports/) for import syntax and the `pub import` pattern for re-exporting. ## Circular Dependencies Modules may import each other in a cycle: `a` imports `b` and `b` imports `a`, a longer chain, or a file that imports itself. A cycle compiles: every file on it sees the others' declarations and macros, functions may call each other across it, and a `pub import` on a cycle re-exports through it. The compiler warns on each cycle ([R001W](/docs/language/diagnostics/#r001w-import-cycle)), because a cycle hinders maintainability: no module on it can be read, built or tested without the others. ```kairo // a.k pub fn fa(n: i32) -> i32 { return if n <= 0 => 0 else => fb(n - 1) + 1 } // b.k pub fn fb(n: i32) -> i32 { return fa(n) } ``` `-fno-import-cycles` makes every import cycle an error (R001E) and stops the build. `-Werror` promotes the warning and `-w` silences it, as for any other warning. **Break circular dependencies** by extracting shared declarations into a third module that both A and B import: ```kairo // shared.k pub fn common_utility() { ... } // a.k // no import b // b.k // no import a ``` Circular dependencies at the module level reflect circular dependencies in the design, restructuring to break the cycle usually improves the architecture. ## Visibility on Top-Level Declarations A top-level declaration (function, class, constant, ...) with no visibility written is `priv` to its file, or `prot` to its module when the file is under a `module.k`. Write `pub` on what other modules may use: ```kairo pub fn public_api() { ... } fn helper() { ... } // priv, or prot under a module.k priv fn internal_helper() { ... } prot fn library_internal() { ... } pub class Server { ... } priv class ConnectionPool { ... } pub eval MAX_CONNECTIONS = 1024 priv static request_count: i32 = 0 priv thread request_id: u64 = 0 ``` Using a declaration where it is not visible is an error at the use, with a note at the declaration and a fix-it that makes it `pub`: SC242E when it is reached through its module (`geo::area()`) or named as a type, R047E when an `import geo::*` brought its bare name in. > [!NOTE] > Until 2026-11-08 an unmarked declaration was `pub` (a class's variables `priv`). The standard library and `builtin` still follow that rule until they are marked, and so does the compiler's own source, built with an internal flag. See [Imports](/docs/language/imports/#visibility-on-imports) for how visibility affects what is re-exported via `pub import`. In a script, a list literal of constants initializes a top-level array in place. An array variable with a non-constant initializer is SC235E. ## See also - [Imports](/docs/language/imports/) - [Re-export Pattern](/docs/language/imports/#re-export-pattern) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [A Note on C++ Modules](/docs/language/c-cpp/#a-note-on-c-modules) - [Macro Scoping](/docs/language/macros/#scoping) - [Class Visibility](/docs/language/classes/#visibility) --- ## Extends URL: https://www.kairolang.org/docs/language/extends/ # Extends `extend` blocks add methods, operators, and static functions to types declared elsewhere. They are the primary way to attach behavior to [structs](/docs/language/structures/) and [enums](/docs/language/enums/), which cannot contain methods in their body. Classes can also be extended. --- ## Basic Syntax ```kairo struct Point { var x: f64 var y: f64 } extend Point { fn length(const self) -> f64 { return std::sqrt(self.x * self.x + self.y * self.y) } fn op +(self, other: Point) -> Point { return Point { x: self.x + other.x, y: self.y + other.y } } static fn origin() -> Point { return Point { x: 0.0, y: 0.0 } } } var p = Point { x: 3.0, y: 4.0 } p.length() // 5.0 Point::origin() // Point { x: 0.0, y: 0.0 } ``` Methods added via `extend` are called the same way as methods defined in a class body there is no syntactic distinction at the call site. An `extend` body is the extended type's scope. Members still need an explicit qualifier `self.x` or `Self::x`, exactly as in a class body (see [Members always need a qualifier](/docs/language/classes/#members-always-need-a-qualifier)) and the same one exception applies: the target's nested types and type aliases are visible unqualified. As in a class body, the bare form warns; write `Self::Node`. ```kairo class Tree { struct Node { var value: i32 } var count: i32 } extend Tree { fn add(self) { var n = Self::Node { value: 0 } // ok var m = Node { value: 1 } // ok, but warns: write `Self::Node` self.count += 1 // ok // count += 1 // error: needs `self.` } } ``` --- ## What Can Be Extended | Type | Supports `extend` | |---|---| | Structs | Yes the only way to add methods | | Enums | Yes the only way to add methods | | Classes | Yes | | Unions | No | | Interfaces | No | | Primitive types (`i8`–`u512`, `isize`, `usize`, the floats, `bool`, `char`, `byte`, `void`, `string`) | Yes. A static is called through the type: `i32::make()` | | `[T]`, `[T;]`, `[T; N]`, `{T}`, `{K: V}`, tuples | Yes (operators and `impl` on a concrete `[T; N]` work; a generic `[T; N]` extension is not supported yet, SC116E) | | Pointers (`*T`, `*const T`, `unsafe *T`) | No (SC282E): extend the pointee type. A container of pointers (`[*T]`) can be extended | | Nullables (`T?`: `i32?`, `string?`, `Foo?`, ` [T]?`) | Yes. `self` is the `T?`, so a method can be called on a null value. A static is called through an alias (`type OI = i32?`, `OI::make()`). A binary operator (`+ - * / % & \| ^ << >> < <= > >=`) in a non-generic extension of a struct's or class's nullable is the nullable's own: `a + b` with `a: Foo?` calls it whether `a` is null or not. Where `Foo` has that operator too, the use is an error. Other operators on a nullable, and any operator on a primitive's or a library container's nullable, are not supported yet | | Function types (`fn(A) -> R`, `unsafe fn`) | No (SC283E): write a free function, or wrap the function in a struct | | A bare type parameter (`extend T`, ` T`, ` T?`) | No (SC284E): it would add members to every type; extend a named type or a generic type such as `[T]` | --- ## What Extends Can Add The rules differ by type: ### Structs | Allowed | Not allowed | |---|---| | Methods | Constructors | | Static functions | Destructors (`fn op finally`) | | Arithmetic / comparison operators | Copy / move assignment (`fn op =`) | | `fn op in` (iteration) | Member-only operators (`as`, `[]`, `->`) | Structs are trivially copyable. Extending lifecycle operations (destructors, copy/move) would break that guarantee. See [Structures](/docs/language/structures/#copy-semantics). ### Enums | Allowed | Not allowed | |---|---| | Methods | Constructors | | Static functions | Destructors | | Comparison / arithmetic operators | Copy / move assignment | | | Member-only operators (`as`, `[]`, `->`) | ### Classes | Allowed | Not allowed | |---|---| | Methods | Constructors | | Static functions | Destructors | | Operators other than the member-only ones | Copy / move assignment | | | Member-only operators (`as`, `[]`, `->`, `finally`) | Classes already support methods and operators in their body. `extend` on a class is useful for separating interface conformance or adding functionality in a different section of the codebase (within the same file). > [!NOTE] > Constructors, destructors, and copy/move assignment cannot be added via `extend` on any type. Neither can the member-only operators `as`, `[]`, `->`, and `finally`; declare them in the type's own body. If you need construction logic on a struct, extend a static factory function instead. If you need a destructor, use a [class](/docs/language/classes/). --- ## Interface Conformance `extend ... impl` declares that a type satisfies an interface and provides the required methods: ```kairo interface Drawable { fn draw(const self) -> string } extend Point impl Drawable { fn draw(const self) -> string { return f"({self.x}, {self.y})" } } ``` The compiler verifies at the `extend` declaration that all interface requirements are satisfied. Missing methods are a compile error. > [!NOTE] > The current compiler does not report missing methods at the `extend` declaration yet. See [Implementation Status](/docs/status/#not-diagnosed). A type can conform to multiple interfaces through separate `extend` blocks: ```kairo extend Point impl Drawable { fn draw(const self) -> string { ... } } extend Point impl Serializable { fn serialize(const self) -> [byte] { ... } fn byte_size(const self) -> i32 { ... } } ``` See [Interfaces](/docs/language/interfaces/) for interface declarations and structural conformance. --- ## Generic Extends A generic `extend` declares its own [type parameters](/docs/language/generics/): ```kairo struct Pair { var first: T var second: T } extend Pair { fn swap(self) -> Pair { return Pair { first: self.second, second: self.first } } } ``` The parameters belong to the `extend` block, not to the type. Its target can be any instance pattern of the type, so an extension can apply to only some instantiations: ```kairo struct Box { var value: T } struct Wrap { var inner: T } extend Wrap> { fn unbox(const self) -> T { // only on Wrap> return self.inner.value } } ``` `Wrap>` has `unbox`; `Wrap` does not. Constraints on an extension's parameters are written with `impl`, `derives`, or a [`requires` clause](/docs/language/requires/): ```kairo extend Pair { fn max(const self) -> T { return if self.first > self.second => self.first else => self.second } } ``` This `max` method is only available on `Pair` when `T` satisfies `Comparable`. Calling `pair_of_noncomparable.max()` (or `Pair::max(p)`) is a compile error. > [!NOTE] > The current compiler does not check an extension's bounds at the call site yet. See [Implementation Status](/docs/status/#not-diagnosed). ### Generic interface conformance ```kairo interface Container { fn size(const self) -> i32 fn get(const self, index: i32) -> T } extend Pair impl Container { fn size(const self) -> i32 { return 2 } fn get(const self, index: i32) -> T { return if index == 0 => self.first else => self.second } } ``` See [Requires Clauses](/docs/language/requires/) for the full constraint system. --- ## Visibility Extended methods can have `pub`, `prot`, or `priv` visibility: ```kairo extend Point { pub fn distance(const self, other: Point) -> f64 { return (self - other).length() } priv fn validate(const self) -> bool { return self.x >= 0.0 && self.y >= 0.0 } } ``` An extension member with no modifier is `priv`, or `prot` when the `extend` block's file is under a `module.k`, like any other declaration; the members of an `extend X impl I` block are the exception, `pub` unless marked, since they implement the interface wherever the conformance is used. A `priv` extension member is visible only inside the file that contains the `extend` block, not everywhere the type is visible. `prot` reaches every file of the module. An `extend` in another file of the type's module reads the type's `prot` members (written, or unmarked under the `module.k`), so a large class can be split across the files of one module; its `priv` members stay with the file that declares the type. An `extend` is outside code, not a subclass: an `extend Derived` does not get the `prot` members of Derived's base. It can use them only where any code can, in a file of the module that declares them (the base's module); the error says so and names that module's root. ### Which files see an extension The members an `extend` block adds (methods, statics, operators, and the conformance of an `extend X impl I`) are visible in a file only when the block is: 1. in that file itself; 2. in a file it imports (any import form: `import m`, `import m::*`, `import m::{x}`, `import m as n`), or in a file one of those re-exports: through a `pub import` (a library's `module.k` exports are its `pub import`s), or a `prot import` when your file is in that module. A `priv import` further down the chain carries nothing: what a file imports privately is its own business; 3. in the file that declares the extended type: an extension written beside its type goes wherever the type goes; 4. in the builtin library, which every file sees. The conformance an `extend X impl I` declares follows the same rule: an impl your file cannot see cannot satisfy a bound in it. ```kairo // shapes.k pub struct Point { pub var x: i32 } extend Point { pub fn half(self) -> i32 = self.x / 2 } // rule 3: travels with Point // ext.k extend Point { pub fn twice(self) -> i32 = self.x * 2 } // user.k fn f(p: Point) -> i32 { return p.half() + p.twice() // error R025E: no member named 'twice'; ext.k is not imported } ``` The error names the file whose extension declares the member and offers the import. Which other files the program happens to compile has no effect: `user.k` reads the same in every build. --- ## `Self` in Extend Blocks `Self` is available in `extend` blocks and resolves to the extended type: ```kairo extend Pair { fn duplicate(const self) -> Self { // Self resolves to Pair return Pair { first: self.first, second: self.second } } } ``` --- ## Same-File Restriction A plain `extend` block must be in the same file as the type definition: ```kairo // point.k struct Point { var x: f64; var y: f64 } extend Point { fn length(const self) -> f64 { ... } // ok: same file as Point } ``` ```kairo // other.k // extend Point { ... } // compile error: Point is defined in a different file ``` For `extend ... impl` blocks (interface conformance), the rule is looser: either the type or the interface must be defined in the same file as the `extend` block: ```kairo // drawable.k interface Drawable { fn draw(const self) -> string } // This is legal even though Point is defined in point.k, // because Drawable is defined here: extend Point impl Drawable { fn draw(const self) -> string { return f"({self.x}, {self.y})" } } ``` This prevents conflicts between extensions in different files while still allowing interface conformance to be declared where the interface is defined. > [!NOTE] > The current compiler does not reject an `extend` in the wrong file yet. See [Implementation Status](/docs/status/#not-diagnosed). --- ## Multiple Extend Blocks A type can have multiple `extend` blocks in the same file. Each block can target different interfaces or group related functionality: ```kairo struct Color { var r: u8 var g: u8 var b: u8 } // Arithmetic operations extend Color { fn op +(self, other: Color) -> Color { return Color { r: (self.r as i32 + other.r as i32).min(255) as u8, g: (self.g as i32 + other.g as i32).min(255) as u8, b: (self.b as i32 + other.b as i32).min(255) as u8, } } } // Serialization extend Color impl Serializable { fn serialize(const self) -> [byte] { ... } fn byte_size(const self) -> i32 { return 3 } } // Display extend Color impl Drawable { fn draw(const self) -> string { return f"rgb({self.r}, {self.g}, {self.b})" } } ``` --- ## Extend vs Class Methods A method in the class body and a method in an `extend` block are called the same way, but they are different entities: - An extension member is not virtual, cannot override, and cannot be a constructor, destructor, or assignment operator. - A same-file `extend` can read the type's private members. An `extend ... impl` placed in the interface's file cannot: its members see only what other code in that file sees. - A `priv` or `prot` member satisfies an interface requirement only if the type's own file declares the conformance (`class X impl I`, or an `extend X impl I` in that file). A generic bound met only structurally, from another file, needs the member to be `pub`. - C++ code calling a Kairo type sees body methods as member functions, and extension members as static functions of a companion struct emitted beside the type. A same-file `extend`'s companion is a friend of the type, so its members reach `priv` members in C++ too. See [Using Kairo in C++](/docs/language/c-cpp-exposing/#what-a-kairo-declaration-looks-like-in-c). Put anything that needs [dynamic dispatch](/docs/language/classes-inheritance/#virtual-dispatch), overriding, or [lifecycle behavior](/docs/language/classes-lifecycle/) in the body. Use `extend` for the rest, such as interface conformance kept apart from the core type: ```kairo class Server { var port: i32 fn Server(self, port: i32) { self.port = port } // Core functionality in the class body fn start(self) { ... } fn stop(self) { ... } } // Interface conformance separated extend Server impl Loggable { fn to_log_string(const self) -> string { return f"Server(:{self.port})" } } ``` --- ## Summary ```kairo // Extend a struct with methods struct Vec2 { var x: f64; var y: f64 } extend Vec2 { fn length(const self) -> f64 = std::sqrt(self.x * self.x + self.y * self.y) fn op +(self, other: Vec2) -> Vec2 = Vec2 { x: self.x + other.x, y: self.y + other.y } static fn zero() -> Vec2 = Vec2 { x: 0.0, y: 0.0 } } // Extend an enum with methods extend Direction { fn opposite(self) -> Direction { match self { case .North { return .South } case .South { return .North } case .East { return .West } case .West { return .East } } } } // Interface conformance extend Vec2 impl Drawable { fn draw(const self) -> string = f"({self.x}, {self.y})" } // Generic extend with constraints extend Pair { fn max(const self) -> T = if self.first > self.second => self.first else => self.second } ``` ## See also - [Structures](/docs/language/structures/#extends) - [Enums](/docs/language/enums/#extends) - [Classes](/docs/language/classes/) - [Interfaces](/docs/language/interfaces/#conformance) - [Generics](/docs/language/generics/) - [Requires Clauses](/docs/language/requires/) --- ## Attributes URL: https://www.kairolang.org/docs/language/attributes/ # Attributes Attributes are compile-time AST transformations. They modify the structure of declarations renaming fields, injecting code, adding members with full access to the parsed syntax tree and type information. Unlike [macros](/docs/language/macros/), which operate on raw tokens before parsing, attributes run after parsing and can inspect and modify typed AST nodes. | Property | Guarantee | |---|---| | Type safety | Yes | | Hygiene | Yes | | Scope | Yes | | Expansion time | Compile time | | Expansion order | Inner to outer | | Expansion context | The node the attribute is attached to | --- ## Defining Attributes > Attribute macros parse, but the compiler does not expand them yet: using one is rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) rather than doing nothing. See [Status](/docs/status/). Attributes are defined with the `macro` keyword followed by `@name` and a parameter list. The first parameter is always a pointer to the AST node being transformed: ```kairo macro @add_logging(node: *AST::FunctionDecl) { node->body.prepend( AST::parse!(std::io::println(f"entering {stringify!(node->name)}")) ) node->body.append( AST::parse!(std::io::println(f"exiting {stringify!(node->name)}")) ) } ``` ```kairo @add_logging fn process_data(x: i32) -> i32 { return x * 2 } ``` After expansion: ```kairo fn process_data(x: i32) -> i32 { std::io::println("entering process_data") var __result = x * 2 std::io::println("exiting process_data") return __result } ``` ### Node preservation rule Attributes must preserve the node type. An attribute attached to a function declaration receives a `*AST::FunctionDecl` and must leave it as a function declaration it cannot replace it with a class or a variable. This ensures the expansion process is deterministic and the AST remains structurally consistent. To add new nodes, create them with `@create AST::NodeType()` and attach them to the existing node (e.g., appending statements to a function body, adding members to a class). --- ## Attribute Arguments Attributes can take additional arguments beyond the implicit node parameter: ```kairo macro @repeat(block: *AST::Block, times: i32) { var original = block->clone() var *expanded = @create AST::Block() for i in 0..times { expanded->body.append(original.clone()) } *block = *expanded } @repeat(3) { std::io::println("hello") } ``` After expansion: ```kairo { { std::io::println("hello") } { std::io::println("hello") } { std::io::println("hello") } } ``` Arguments are passed in parentheses after the attribute name at the use site. The node parameter is implicit it is always the declaration or block the attribute is attached to. --- ## Overloading Attribute definitions can be overloaded by node type or argument types. The compiler selects the correct overload based on what the attribute is attached to: ```kairo macro @serialize(node: *AST::ClassDecl) { // generate serialization for a class } macro @serialize(node: *AST::StructDecl) { // generate serialization for a struct } ``` ```kairo @serialize class Config { ... } // calls the ClassDecl overload @serialize struct Point { ... } // calls the StructDecl overload ``` --- ## Expansion Order When multiple attributes are stacked on a single declaration, they expand inner to outer the attribute closest to the declaration runs first: ```kairo @deserialize // runs second, on the result of @serializable @serializable // runs first, on the original class class Config { var host: string var port: i32 } ``` This allows attributes to compose `@serializable` can add serialization methods, and `@deserialize` can then inspect those methods to generate the inverse. --- ## Attaching Attributes Attributes can be attached to any AST node: ```kairo // On a function @no_unwind fn checksum(data: [u8;]) -> u32 { ... } // On a class @packed class Header { ... } // On a struct @align(16) struct SimdData { ... } // On a block @repeat(3) { std::io::println("repeated") } // On a variable (if the attribute accepts VariableDecl) @deprecated("use new_config instead") var old_config: Config ``` An attribute can also be applied to an expression: `@name operand`, or `@name(args) operand`. The operand is one unary expression, including its calls, member accesses and initializers, so `@create Config(8080)` applies to the whole constructor call. Binary operators bind looser (`@a x + 1` is `(@a x) + 1`), and a member access on the result needs parentheses: `(@create Config(8080))->port`. At the start of a statement, an `@name` is an expression attribute when an expression follows it on the same line (`@destroy p`, `@create Config(8080)`); it attaches to the statement or declaration instead when what follows is a declaration (`@deprecated var`, `@copy fn`), a keyword statement (`@likely if`), a block (`@repeat(3) { ... }`), a loop label, or a line break. > Two expression attributes have a meaning: `@create T(args)` and `@destroy p` (see [Heap Allocation](/docs/language/pointers/#heap-allocation)). Every other one parses but is rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported), as is the initializer form `@create T{...}`. See [Status](/docs/status/). --- ## Built-in Attributes Kairo provides built-in attributes that are handled directly by the compiler: ### Layout attributes | Attribute | Description | Applies to | |---|---|---| | `@packed` | Remove padding between members | Classes, structs, unions | | `@align(N)` | Set minimum alignment to N bytes | Classes, structs, unions, fields, variables | `@packed` lays the members out back to back at alignment 1, with no padding between them or at the end, as C's `__attribute__((packed))` does. `@align(N)` raises the alignment to N (it never lowers it below the natural alignment), and the size rounds up to a multiple of it. N is an integer literal, a power of two, at most 2^28; anything else is an error. On a field or a variable, `@align(N)` raises that member's or variable's alignment the same way. Together on one record, `@packed @align(N)` packs the members and aligns the whole to N, like `__attribute__((packed, aligned(N)))`. ```kairo @packed struct P { var a: u8; var b: u32 } // sizeof 5, alignof 1 @align(16) struct Q { var a: u8 } // sizeof 16, alignof 16 @packed @align(4) struct PA { var a: u8; var b: u32 } // sizeof 8, alignof 4 struct F { var a: u8; @align(8) var b: u8 } // b at offset 8; sizeof 16 ``` The layout the compiler computes for `sizeof` and `alignof` in a declaration-scope `eval if` is the same one the generated C++ has, so a branch chosen on a record's size matches the size at run time. A heap allocation of an `@align(N)` type through `create` is N-aligned: it asks the allocator for `alignof T`. See [Classes](/docs/language/classes/#memory-layout-and-allocation) and [Structures](/docs/language/structures/#memory-layout) for layout details. ### Branch hints | Attribute | Description | Applies to | |---|---|---| | `@likely` | Condition is expected to be true | `if` statements | | `@unlikely` | Condition is expected to be false | `if` statements | | `@unreachable` | Branch should never execute (UB if reached). Not implemented yet: rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) | `match`/`if` branches | | `@likely` / `@unlikely` before `else` | Hint for the `else` or `else if` branch that follows | `else`, `else if` | | `@assume(cond)` | The optimizer may take `cond` as true from here on (UB if it is false) | A statement of its own | `@likely` and `@unlikely` also go between a branch's closing `}` and the `else` after it; each hint is for the branch it precedes. `@assume(cond)` is not an attribute on anything: it is a statement on its own line. ```kairo @likely if a { fast() } @unlikely else if b { rare() } @unlikely else { rarer() } @assume(n > 0) ``` See [Control Flow](/docs/language/control-flow/#branch-hints) for branch prediction hints. ### Diagnostics | Attribute | Description | Applies to | |---|---|---| | `@no_warn(CODE)` | Suppress a specific compiler warning | Any declaration | | `@deprecated(msg)` | Mark a declaration as deprecated | Any declaration | `@deprecated` (with no argument) or `@deprecated("message")` makes every use of the declaration a warning that names it and the message, with a note at the attribute. The declaration itself is not reported, and neither is a use inside it. ```kairo @deprecated("use read_all instead") fn read() -> i32 { return 0 } fn main() -> i32 { return read() } // warning: 'read' is deprecated: use read_all instead ``` `@no_warn(CODE, ...)` drops those warnings wherever they are reported inside the declaration, by any stage of the compiler. Each code must be a warning code (`SC031W`): an unknown code is an error, and so is an error code, since an error cannot be suppressed. ```kairo @no_warn(SC031W) fn f() -> i32 { var y: i32 = 1 as i32; return y } // no redundant-cast warning ``` ### Unwinding | Attribute | Description | Applies to | |---|---|---| | `@unwind` | Let a C++ exception pass through this function | Functions, methods | | `@no_unwind` | Keep the function `noexcept`, even under `-funwind` | Functions, methods | Every Kairo function is `noexcept` in its generated C++ declaration and definition: a C++ exception that reaches a Kairo frame terminates the program (`std::terminate`). `@unwind` removes the `noexcept` from one function, so a C++ exception thrown by a C++ callee unwinds through it to the next frame up. The `-funwind` flag removes it from every Kairo function, closures included; `@no_unwind` keeps it on one function even then. Marking one function both is an error. ```kairo fn add(a: i32, b: i32) -> i32 { return a + b } // C++: int add(int a, int b) noexcept @unwind fn relay(x: i32) -> i32 { return cxx_may_throw(x) } // C++: int relay(int x) ``` Writing `@unwind` or `@no_unwind` on any one declaration of a function covers all of them: a [forward declaration](/docs/language/functions-declarations/#forward-declarations), the declaration inside a class, or the [out-of-line definition](/docs/language/classes-out-of-line/). ```kairo class Counter { var n: i32 @unwind fn get(const self) -> i32 // declared here... } fn Counter::get(const self) -> i32 { return self.n } // ...so this definition is not noexcept either ``` A closure cannot carry `@unwind` yet: written before a closure, it is an expression attribute, which is not supported. A closure follows `-funwind`. See [Exceptions](/docs/language/c-cpp-exceptions/#exceptions) for how C++ exceptions move through Kairo code. ### Function hints | Attribute | Description | C++ | Applies to | |---|---|---|---| | `@hot_path` | The function runs often: optimize it for speed and keep it close to other hot code | `[[gnu::hot]]` | Functions, methods | | `@cold_path` | The function runs rarely (error handling, setup): optimize it for size and keep it out of the way | `[[gnu::cold]]` | Functions, methods | | `@pure` | The function's result depends only on its inputs and memory it can read, and it writes nothing else | `[[gnu::pure]]` | Functions, methods | | `@no_inline` | Never inline the function: it keeps its own symbol and its own code, as for a benchmark kernel or a rarely taken path kept out of its caller | `__attribute__((noinline))` | Functions, methods | ```kairo @hot_path fn next(state: *Rng) -> u64 { /* ... */ } @cold_path fn report_failure(code: i32) { /* ... */ } @pure fn length_sq(v: *Vec3) -> f64 { return v->x * v->x + v->y * v->y + v->z * v->z } ``` Each is a promise to the optimizer, written on the function and checked where the compiler can. `@hot_path` together with `@cold_path` on one function is an error, and any of the three on something that is not a function ('`@hot_path` applies only to a function') is an error with a fix-it that removes it. `@pure` is checked. The function must return a value, must not be `-> !`, `@unwind`, `virtual` or an interface requirement (an override would not be held to the promise), and its result type must not own memory. In its body the compiler reports: - a write to a global or `static` variable; - an assignment through a pointer (`*p = x`, `p->field = x`, `p[i] = x`), to a field of `self`, or to an `@inout` parameter; - a call to anything that is not a const function, another `@pure` function, an `eval fn` or a side-effect-free compiler intrinsic; a user operator is a call too, and a call through a function value or an interface requirement is always an error; - making a value that owns memory (a `string`, an f-string, a vector, a local of such a type, a by-value copy of one); - `assert`, `unwrap!`, an asserting downcast, `delete`, inline C++, `spawn`, `thread` and `await`; - a `for ... in` loop over anything but a range (`0..n`) or a fixed-size array. Reading globals and reading through pointers is allowed; that is the difference between `@pure` and a [const function](/docs/language/functions-declarations/#const-functions), which may read only its own inputs. A `@pure` function whose result changes between calls with the same arguments because something else wrote the memory it reads is fine: the optimizer only merges calls when no write could have happened in between. By default the compiler also finds the functions that keep the const or `@pure` promise without saying so, by the same rules, and gives them the same C++ attribute, on their declaration in every file that imports them. `-fno-infer-purity` turns this off. ### Calling conventions | Attribute | Description | C++ | Applies to | |---|---|---|---| | `@preserve_most` | The callee saves nearly every general-purpose register: for a rarely taken slow path called from hot integer code | `__attribute__((preserve_most))` | `priv` functions and methods | | `@preserve_all` | As `@preserve_most`, and the callee also saves the floating-point and vector registers | `__attribute__((preserve_all))` | `priv` functions and methods | | `@preserve_none` | The callee saves nothing: for tail-call-heavy dispatch, such as an interpreter's opcode handlers | `__attribute__((preserve_none))` | `priv` functions and methods | At most one per function, never on a function C or C++ can see, and only on x86-64 and AArch64. See [Calling conventions](/docs/language/functions-declarations/#calling-conventions) for the rules and the register table. ### Enums | Attribute | Description | Applies to | |---|---|---| | `@open` | The enum may hold any value of its underlying type: no checked `as`, no niche | Plain enums | A plain enum is closed by default; see [Closed and open enums](/docs/language/enums-plain/#closed-and-open-enums). `@open` on anything else is an error. ### Conversions | Attribute | Description | Applies to | |---|---|---| | `@implicit` | Lets a conversion operator apply without `as` | `fn op as` in a type's body | See [Implicit `op as`](/docs/language/operator-overloading/#implicit-op-as) for the rules. ### Other | Attribute | Description | Applies to | |---|---|---| | `@core::where_handler` | Custom handler for where-clause failures. Not implemented yet | Functions | See [Where Clauses](/docs/language/where/) for the where handler system. ### Unknown and misplaced attributes An attribute is never accepted and ignored. An attribute name the compiler does not know is an error, `unknown attribute '@name'`, with a fix-it that removes it and a suggestion when the name is close to a built-in one (`@pakced`: did you mean `@packed`?). A built-in attribute written where it does not apply is an error that says where it does (`'@packed' applies only to a class, struct or union`), also with a fix-it that removes it. A [user-defined attribute](#defining-attributes) is rejected with [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported) for now: attribute macros parse, but they are not expanded yet. --- ## The `std::AST` API Attribute definitions interact with the AST through the `std::AST` module. This module provides types representing each kind of AST node (`FunctionDecl`, `ClassDecl`, `StructDecl`, `Block`, `VariableDecl`, etc.) and methods for inspecting and modifying them. > [!IMPORTANT] > The `std::AST` API is under development. The full set of node types, their fields, and available methods will be documented once the API is finalized. The examples on this page demonstrate the intended usage patterns. Key operations available on AST nodes: | Operation | Description | |---|---| | `node->name` | Access the declaration name | | `node->body` | Access the body (for functions, blocks) | | `node->body.append(stmt)` | Add a statement to the end | | `node->body.prepend(stmt)` | Add a statement to the beginning | | `node->clone()` | Deep-copy the node | | `AST::parse!(code)` | Parse a code fragment into an AST node | | `@create AST::T()` | Create a new AST node of type T | --- ## Macros vs Attributes | | Macros | Attributes | |---|---|---| | Operates on | Raw tokens | AST nodes | | Type awareness | No | Yes | | Expansion time | Before parsing | After parsing | | Can modify structure | Token substitution only | Can transform the AST | | Syntax | `name!(args)` | `@name` on declarations | | Must preserve node type | N/A | Yes | Use macros for simple substitutions and [conditional compilation](/docs/language/macros-builtin/#conditional). Use attributes for structural transformations that need to inspect or modify declarations. See [Macros](/docs/language/macros/) for the token-level macro system. --- ## Summary ```kairo // Define an attribute macro @timer(node: *AST::FunctionDecl) { node->body.prepend( AST::parse!(var __start = std::time::now()) ) node->body.append( AST::parse!(std::io::println(f"elapsed: {std::time::now() - __start}ms")) ) } // Use an attribute @timer fn expensive_computation() { // ... work ... } // Attribute with arguments macro @version(node: *AST::ClassDecl, ver: string) { // add a static VERSION member to the class } @version("2.1.0") class MyLibrary { ... } // Stacked attributes (inner to outer) @json_output @validate_fields struct ApiResponse { var status: i32 var body: string } // Built-in attributes @packed @align(16) struct CacheLine { var data: [u8; 64] } @likely if hot_path { fast_operation() } ``` `@no_warn` also covers warnings the parser reports inside the declaration, such as S055W. Lexer and preprocessor warnings, such as S025W, are not covered. ## See also - [Macros](/docs/language/macros/) - [Built-in Macros](/docs/language/macros-builtin/) - [Compile-Time Eval](/docs/language/eval/) - [Structures](/docs/language/structures/#memory-layout) - [Unions](/docs/language/unions/#memory-layout) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [Operator Overloading](/docs/language/operator-overloading/#implicit-op-as) - [Where Clauses](/docs/language/where/) --- ## Macros URL: https://www.kairolang.org/docs/language/macros/ # Macros Macros in Kairo are token-level substitutions they operate on raw tokens before parsing, similar to C/C++ `#define` but with scoping and balanced-delimiter requirements. Macros are identified by the `!` suffix on their name. For AST-level transformations with type awareness, see [Attributes](/docs/language/attributes/). ## In this section - [Built-in Macros](/docs/language/macros-builtin/) --- ## Defining Macros A macro is defined with the `macro` keyword, a name ending in `!`, optional parameters, and a body. The body must have balanced delimiters: ```kairo macro double!(x) { x + x } macro greeting! { "hello, world" } ``` At every use site, the preprocessor replaces the macro invocation with the body, substituting parameters: ```kairo var a = double!(5) // replaced with: 5 + 5 var b = greeting! // replaced with: "hello, world" ``` ### Parameters Parameters are typeless they accept any sequence of tokens. Multiple parameters are comma-separated: ```kairo macro clamp!(value, lo, hi) { if value < lo => lo else if value > hi => hi else => value } var x = clamp!(temperature, 0, 100) ``` #### Default values A parameter may declare a default token run with `=`. When the caller omits the argument, the default tokens substitute instead. Defaulted parameters must come after required ones: ```kairo macro log!(msg, level = "info") { std::io::println(f"[{level}] {msg}") } log!("started") // level defaults to "info" log!("failed", "error") ``` #### Ignoring extra arguments A bare `...` (no name) as the last parameter accepts any number of extra arguments and discards them. Useful for macros that mirror a wider signature: ```kairo macro trace!(msg, ...) { std::io::println(msg) } trace!("hit", state, depth) // state, depth are consumed and dropped ``` A `...` parameter (named or bare) must be last, and cannot follow defaulted parameters. ### Variadic macros and pack expansion The `...` prefix on the last parameter declares a token pack: it captures any number of comma-separated arguments. Inside the body, the pack expands with a **postfix** `...`. This is the same declaration-prefix / expansion-postfix split used by [variadic functions](/docs/language/functions-parameters/#variadic-functions) and [pack expansion](/docs/language/functions-parameters/#pack-expansion-and-forwarding) expressions: ```kairo macro list!(...xs) { [ xs... ] } list!() // [ ] list!(1) // [ 1 ] list!(1, 2, 3) // [ 1, 2, 3 ] ``` A bare splat `xs...` emits the pack's elements joined by commas. An empty pack consumes the splat and emits nothing. #### Pattern expansion A parenthesized token run followed by `...` replicates the whole pattern once per pack element, substituting the pack name with that element each time. Instances are comma-joined: ```kairo macro wrap_all!(...xs) { [ (box(xs))... ] } wrap_all!(1, 2, 3) // [ box(1), box(2), box(3) ] ``` Ordinary parameters substitute inside patterns as usual: ```kairo macro call_each!(f, ...xs) { (f(xs))... } call_each!(log, a, b) // log(a), log(b) ``` The outer parentheses are grouping syntax and are not emitted. To emit parentheses around each instance, double them: ```kairo macro pairs!(k, ...xs) { [ ((k, xs))... ] } pairs!(id, 7, 8) // [ (id, 7), (id, 8) ] ``` Two rules keep macro expansion from colliding with expression-level pack expansion in the output: a postfix `...` after an identifier that is not the macro's pack, or after a parenthesized run that never mentions the pack, passes through verbatim as target-language code. Expansion is single-level: a nested `...` inside a pattern is emitted verbatim. ### Macros as arguments Macros can be passed to other macros. The inner macro is expanded at the final substitution site: ```kairo macro tag! { "debug" } macro repeat!(m) { m! m! m! } var labels = repeat!(tag) // becomes: "debug" "debug" "debug" ``` --- Built-in macros are covered in [Built-in Macros](/docs/language/macros-builtin/). --- ## Scoping Unlike C/C++ `#define`, Kairo macros respect scope. A macro defined inside a [module](/docs/language/modules/) or block is only visible within that scope: ```kairo module internal { macro BUFFER_SIZE! { 4096 } var buf: [u8; BUFFER_SIZE!] } // BUFFER_SIZE! is not visible here ``` Top-level macros follow the same [visibility rules](/docs/language/modules/#visibility-on-top-level-declarations) as other declarations: ```kairo pub macro MAX_RETRIES! { 3 } // visible to importers priv macro INTERNAL_FLAG! { true } // file-scoped ``` --- A declaration made by a macro is reported at the macro's invocation; a duplicate adds a note "in expansion of macro" pointing into the macro body. ## Macros vs Attributes | | Macros | Attributes | |---|---|---| | Operates on | Raw tokens | AST nodes | | Type awareness | No | Yes | | Expansion time | Before parsing | After parsing | | Can modify structure | Token substitution only | Can transform the AST | | Syntax | `name!(args)` | `@name` on declarations | | Hygiene | Scoped, balanced delimiters | Full AST hygiene | Use macros for simple substitutions, constants, and [conditional compilation](/docs/language/macros-builtin/#conditional). Use attributes for code transformations that need type information or structural awareness. See [Attributes](/docs/language/attributes/) for the AST-level transformation system. --- ## Summary ```kairo // Define a macro macro square!(x) { x * x } var s = square!(5) // 25 // No-parameter macro macro VERSION! { "1.0.0" } std::io::println(f"version: {VERSION!}") // Built-in macros std::io::println(f"file: {file!}, line: {line!}") eval SHADER = embed_str!("shader.glsl") eval ICON = embed!("icon.png") // Variadic helpers var n = count!(a, b, c, d) // 4 // Diagnostics eval if !defined!(__LP64__) { compile_error!("64-bit platform required") } // Conditional compilation macro DEBUG! { true } eval if defined!(DEBUG) { fn trace(msg: string) { std::io::println(f"[TRACE] {msg}") } } // Scoped macros module config { priv macro DEFAULT_PORT! { 8080 } pub eval PORT = DEFAULT_PORT! } ``` --- Import a macro by its `!` name: `import lib::MAX_RETRIES!`, or `import lib::{MAX_RETRIES!, f}`. ## See also - [Built-in Macros](/docs/language/macros-builtin/) - [Attributes](/docs/language/attributes/) - [Eval](/docs/language/eval/) - [Modules](/docs/language/modules/) - [Functions](/docs/language/functions/) - [Variadic Functions](/docs/language/functions-parameters/#variadic-functions) --- ## Concurrency URL: https://www.kairolang.org/docs/language/concurrency/ # Concurrency > [!IMPORTANT] > This page is under development. The concurrency model is being designed. Full documentation will be added once the design is finalized. Kairo's concurrency system provides async/await, coroutines, and thread-level primitives. The following features are planned and referenced across the existing documentation: ### Async/Await The `async` modifier on functions and the `await` keyword for waiting on asynchronous results. See [Functions](/docs/language/functions-declarations/#function-modifiers) for the `async` modifier. ### Coroutines (`yield`) Functions with a `yield T` return type are generators: they produce values cooperatively. The `yield` keyword suspends the function and produces a value to the caller. See [Generators](/docs/language/functions-generators/#generators) for the rules. ### `spawn` `spawn f(args)` starts an `async` function as a concurrent task and returns its future. `await` on the future joins the task; a task whose future is never awaited is detached. The runtime model (green threads, OS threads, or event loop) is being finalized. See [Threading](/docs/language/tether-threading/) for how Tether analyzes what a task captures. ### Atomic Types (`atomic T`) Thread-safe wrapper type for lock-free operations. Referenced in [Functions](/docs/language/functions-generators/#special-return-types). ### Thread-Local Variables See [Thread-Local Variables](/docs/language/variables/#thread-local-variables). ### Synchronization Primitives Mutexes, channels, and other coordination mechanisms will be documented here once the standard library concurrency API is finalized. ### Custom Awaitables Classes can define `fn op await(self, obj: std::forward) -> T` to customize the behavior of `await` when called on an instance. See [Operators](/docs/language/operator-overloading/#special-operators) for the `op await` overload. ```kairo await async_fn() // syntax sugar for a state machine var fut = spawn some_async_fn() // start a concurrent task await fut // join it; never awaiting detaches it yield some_value // syntax sugar for a coroutine, function must have yield on return type fn get_tokens() -> yield string { yield "token1" yield "token2" } ``` `op await` is overloadable: `fn op await (self) -> T` for custom async types. - `await async_fn()` syntax sugar for state machine - `spawn some_async_fn()` starts a concurrent task and returns its future; never awaiting it detaches the task - `yield some_value` coroutine syntax, function must have `-> yield T` return type - `fn op await (self) -> T` overloadable for custom async types - `atomic T` thread-safe wrapper type ## See also - [Threading](/docs/language/tether-threading/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/#function-modifiers) - [Operator Overloading](/docs/language/operator-overloading/#special-operators) - [Closures](/docs/language/closures/) - [Ownership](/docs/language/ownership/) - [Panic](/docs/language/panic/) --- ## C & C++ Interoperability URL: https://www.kairolang.org/docs/language/c-cpp/ # C & C++ Interoperability Kairo provides zero-overhead, bidirectional interoperability with C and C++. There is no serialization layer, no binding generator, and no runtime bridge. Kairo emits ABI-compatible object code and consumes C/C++ headers directly. The guarantee that makes this work is not a clever calling convention. It is that **Kairo ships its own pinned Clang, and every translation unit on both sides of the boundary goes through it.** The failure mode that breaks C++ interop for most languages (header parsed by compiler A, code compiled by compiler B, ABI mismatch discovered at runtime) is designed out rather than mitigated. This page covers the toolchain model, calling C/C++ from Kairo, exposing Kairo to C/C++, inline assembly, pointer and reference passing, templates and concepts, allocators and ownership, the exception model, and the ABI contract enforced at link time. ## In this section - [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [Allocators & Ownership](/docs/language/c-cpp-memory/) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [ABI Contract & Verification](/docs/language/c-cpp-abi/) --- ## Coverage Matrix What crosses the boundary, feature by feature. Each row is rated in two directions: - **C++ → Kairo**: Kairo code uses the C or C++ feature, through an [`ffi` import](/docs/language/imports/#ffi-header-imports). - **Kairo → C++**: C or C++ code uses the Kairo feature, through [`#include "x.k"`](/docs/language/c-cpp-toolchain/#how-kcc-works) or a [generated header](/docs/language/c-cpp-exposing/#headers). Each direction cell holds one of: - ✅ works - ◐ partial: the Notes say what does not work yet - ❌ not supported, or not compiled yet - - n/a: the feature exists on one side only; nothing to rate in this direction - ? not documented yet **Kairo-only** and **C++-only** in the Notes mark a feature with no counterpart on the other side, and say what it becomes across the boundary. "Not yet" follows [Implementation Status](/docs/status/#not-compiled-yet). | Feature | Kairo uses it from C/C++ (C++ → Kairo) | C/C++ uses it from Kairo (Kairo → C++) | Notes | |---|---|---|---| | **Toolchain and linkage** | | | | | Using the other side's declarations | ✅ | ◐ | C and C++ headers import with [`ffi "c"` / `ffi "c++"`](/docs/language/imports/#ffi-header-imports); Objective-C headers cannot be imported yet. C++ and Objective-C++ files use Kairo through `#include "x.k"` ([kcc](/docs/language/c-cpp-toolchain/#how-kcc-works)) or [`--emit-headers`](/docs/language/c-cpp-exposing/#headers); plain C and Objective-C files cannot include a `.k` yet ([Status](/docs/status/#not-in-this-release)) | | C and C++ linkage (`ffi "c"`, `ffi "c++"`) | ✅ | ✅ | `ffi "c"` follows `extern "C"` rules: no classes, overloading or templates. See [The `ffi` keyword](/docs/language/c-cpp-calling/#the-ffi-keyword) | | Name mangling and platform ABI | ✅ | ✅ | Itanium or MSVC, taken from Clang's own mangler; vtables, RTTI and struct layout follow the platform. See [ABI Compatibility](/docs/language/c-cpp-abi/#abi-compatibility) | | Layout-affecting C++ flags (`-fno-rtti`, `-fshort-enums`, packing) | ❌ | - | **C++-only.** Rejected in any translation unit that touches Kairo types. See [Layout-affecting](/docs/language/c-cpp-toolchain/#3-layout-affecting) | | Namespaces and modules | ✅ | ✅ | A module path is its C++ namespace, and `module` blocks are namespaces. C++'s `std` is `cxx::std::` in Kairo; Kairo's library is `kairo::` in C++. A module that only re-exports has no header. See [Namespace Mapping](/docs/language/c-cpp-calling/#namespace-mapping) and [Modules](/docs/language/modules/#module-paths-are-c-namespaces) | | Argument-dependent lookup | ◐ | - | **C++-only.** Operators are always found by ADL. An unqualified call of a function found only by ADL is not found unless a Kairo function of that name is visible ([Status](/docs/status/#not-compiled-yet)); qualify it | | C++20 named modules (`import std;`) | ❌ | ❌ | Neither consumed nor produced. See [A Note on C++ Modules](#a-note-on-c-modules) | | C and C++ preprocessor macros | ◐ | - | **C++-only.** Macros are expanded inside the imported headers before Kairo sees the declarations. [`defined!`](/docs/language/macros-builtin/#conditional) sees the target's predefined macros and every macro the file's `ffi` headers define | | A `#define` constant used as a Kairo value | ❌ | - | **C++-only.** An object-like macro (`#define N 4`) cannot be named in Kairo: `N` is R020E, an undeclared identifier, because no macro crosses the boundary. Wrap the value in the header as a `constexpr` (`constexpr int K = 6;` is a Kairo value, and `eval X: i32 = sq(3)` calls a `constexpr` function); [`defined!`](/docs/language/macros-builtin/#conditional) tests that a macro exists | | Kairo macros (`macro m!`) | - | - | **Kairo-only.** Token substitutions expanded before parsing; C++ gets only the code they expand to. See [Macros](/docs/language/macros/) | | Inline C++ (`inline "c++"`, `__inline_cpp`) | ❌ | - | `__inline_cpp` no longer exists (R020E, an undeclared identifier). Import the declarations with `ffi "c++"` instead. See [Namespace Mapping](/docs/language/c-cpp-calling/#namespace-mapping) | | Inline assembly (`inline "asm"`) | - | - | **Kairo-only** syntax, in an `unsafe` block, with GCC-style outputs, inputs and clobbers. A function that uses it is called like any other. See [Inline ASM](/docs/language/c-cpp-calling/#inline-asm) | | **Types** | | | | | Integers, floats, `bool` | ✅ | ✅ | Fixed C++ equivalents (`i32` is `std::int32_t`, `f64` is `double`; `i64` is the target's `int64_t`). Fixed-width integers widen into `size_t` / `ptrdiff_t` parameters where that is lossless. See [Primitives](/docs/language/primitives/) and [Argument conversions](/docs/language/c-cpp-calling/#argument-conversions) | | Characters (`char`, C's `char`, `wchar_t`, `char16_t`, `char8_t`, `byte`) | ✅ | ✅ | C's `char` is [`std::c_char`](/docs/language/primitives/#cs-char-stdc_char), a third type beside `i8` and `u8`. `wchar_t`, `char16_t` and `char8_t` are [`std::c_wchar`, `std::c_char16` and `std::c_char8`](/docs/language/primitives/#cs-wide-characters-stdc_wchar-stdc_char16-stdc_char8), not integers. Kairo's `char` is `char32_t`, `byte` is `std::byte` | | C bit-fields | ✅ | - | **C++-only.** Read and written from Kairo; a write wraps at the field's width. See [Primitives](/docs/language/primitives/) | | Structs | ✅ | ✅ | C layout and calling convention. In C++ a Kairo struct is a plain aggregate with public fields. A bodiless `ffi "c" struct T` names a header's tagged struct ([Tags and ordinary names](/docs/language/c-cpp-calling/#tags-and-ordinary-names)). See [Structs](/docs/language/structures/) | | Unions | ✅ | ✅ | Untagged, laid out by the C++ ABI. See [Unions](/docs/language/unions/) | | Plain enums | ✅ | ✅ | `enum Dir derives u8` is `enum class Dir : std::uint8_t`. An imported C or C++ enum is always [open](/docs/language/enums-plain/#closed-and-open-enums). See [Enums](/docs/language/enums/) | | ADT enums (variants with payloads) | - | ◐ | **Kairo-only.** To C++, a class holding the tag and the payload storage: it can be held, passed and returned, and built and inspected through Kairo functions. No C++ API over the variants is documented. It has no default value, so `map::operator[]` with one as the element fails ([Status](/docs/status/#not-compiled-yet)). See [ADT Enums](/docs/language/enums-adt/#memory-layout) | | Tuples | - | ✅ | **Kairo-only.** `::builtin::TupleN`, a plain struct template with fields `_0`, `_1`, ..., so every translation unit agrees on the type; C++ can name, return and specialize on it. C++'s `std::tuple` / `std::pair` are ordinary class templates. See [Tuples across the boundary](/docs/language/c-cpp-exposing/#tuples-across-the-boundary) | | Nullables (`T?`) | - | ◐ | **Kairo-only.** `::builtin::Nullable`, with `null` as `::builtin::null`; `*T?` is pointer-sized, and a closed enum's `E?` is the enum's size. Not yet: `bool?` is two bytes, not one ([Status](/docs/status/#not-compiled-yet)). A nullable can be a C++ template argument (`vector`). See [Nullables Across the Boundary](/docs/language/c-cpp-exposing/#nullables-across-the-boundary) | | Pointers (`*T`, `unsafe *T`) | ✅ | ✅ | A safe `*T` is `T*` in C++. Passing a pointer to a C or C++ function needs an [`unsafe` block](/docs/language/unsafe/#unsafe-blocks); `unsafe &x` makes a raw pointer from a safe binding, and an `unsafe *T` is C's `T*`. A C++ container keeps the pointer kind written (`vector<*Node>`). See [Pointers and References](/docs/language/c-cpp-calling/#pointers-and-references) | | C++ references (`T&`, `const T&`, `T&&`) | ✅ | ✅ | Reference parameters are the [parameter modes](/docs/language/functions-parameter-modes/) `@inout x: T`, `x: T` and `@move x: T`, in both directions. A call returning a reference is usable as an operand and as an assignment target ([Reference returns](/docs/language/functions-parameter-modes/#reference-returns-from-c)). `const T&&` can be called, not declared | | C++ smart pointers (`unique_ptr`, `shared_ptr`, `weak_ptr`) | ◐ | ? | Usable as imported class templates: a header function returning `std::unique_ptr` or `std::shared_ptr` is called and read with `.get()`, and `cxx::std::make_unique(9)` works. Their automatic mapping to `std::Unique` / `Shared` / `Weak` ([Smart Pointer Promotion](/docs/language/pointers/#smart-pointer-promotion)) is part of [Tether](/docs/language/tether-internals/#cc-interop), which is not in this release. How Kairo's own smart pointers look to C++ is not documented | | Function pointers | ✅ | ✅ | `int (*)(int)` imports as `unsafe fn(i32) -> i32` and takes a named function or a closure that captures nothing. A Kairo `unsafe fn` is a plain C function pointer, and so is every `fn` parameter of an `ffi "c"` function. See [Function pointers and callbacks](/docs/language/c-cpp-calling/#function-pointers-and-callbacks) | | Closures and `fn` values | ◐ | ◐ | A `fn(i32) -> i32` value is `::__kairo_fn` in C++. Kairo to C++: a closure, capturing or not, can be passed to a C++ template parameter (`template int call(F f, int x)`), but not to a `std::function` parameter (SC063E, no matching overload). C++ to Kairo: a function, or a captureless lambda converted with unary `+` (`+[](int x) { return x + 1; }`), is passed where Kairo takes a `fn`; a lambda written without the `+`, a capturing lambda and a `std::function` are compile errors. A capturing closure, or any `fn` value, passed where a C function pointer is expected is a compile error. Not yet: generic closures. As a C++ template argument a written `fn(A) -> R` is the C++ function type `R(A)` (`function_ref`), while a raw `unsafe fn(A) -> R` is the pointer `R(*)(A)`. See [Closures](/docs/language/closures/) | | Arrays (`[T; N]`, C arrays) | ✅ | ✅ | A Kairo array is passed to a C++ `const int (&)[3]` parameter, and a C++ global array is reached through a pointer to its first element (`unsafe &g[0]`). A `const [T; N]` parameter is `const T (&)[N]` in C++, and a C++ array binds to it. An array is not copyable: `var a = g_arr` is SC083E. `cxx::std::array` works as an imported template. See [Collections](/docs/language/collections/#arrays-t-n) | | Slices, vectors, maps, sets | - | ◐ | **Kairo-only.** Plain class templates in the `::builtin` library, used from C++ through the same include: a vector `[T]` is `::builtin::containers::vector::Vector` (`size()`, `operator[]`, `push_back`), a slice is `Slice` (`data` and `len` fields, built from a pointer and a length), and a map `{K: V}` is `HashMap` (`size()`, `contains`, `operator[]`, `begin()` / `end()` over entries with `key` and `value`, so C++'s range `for` works); a set is `HashSet`. Vector, set and map literals compiled and ran in a test of 0.2.0; the [Status](/docs/status/) page lists what is left. C++ containers are used through `cxx::std::`. See [Collections](/docs/language/collections/) | | Strings | ◐ | ◐ | A `const char*` is `*const c_char`. A string literal is a C string at a `const char*` parameter (and through C's `...`); any other Kairo `string` passes `s.c_str()` ([Strings and `const char*`](/docs/language/c-cpp-calling/#strings-and-const-char)). `std::string` is an imported class. To C++, a Kairo `string` is `::builtin::string::string`: `size()`, `c_str()`, a copy constructor, and a constructor from `const unsigned char*` (not `const char*`, so a C++ string literal needs a cast). Through `#include "x.k"` the class is complete only where the `.k` has a type that holds a `string` by value; a function that merely returns one leaves it incomplete in C++ ("incomplete return type"), which `--emit-headers` plus `#include "builtin/string.hh"` avoids | | f-strings | - | - | **Kairo-only.** A `*const c_char` prints as a pointer: there is no C-string formatter yet. See [Status](/docs/status/#not-compiled-yet) | | Type aliases | ✅ | ✅ | C and C++ typedefs and `using` aliases import (`typedef struct X X` is one type). A Kairo member `type` alias is a C++ member `using` at the same access; top-level aliases are not documented. See [Type Aliases](/docs/language/type-aliases/) | | **Functions** | | | | | Functions and methods | ✅ | ✅ | A Kairo method in the class body is a C++ member function. See [What a Kairo declaration looks like in C++](/docs/language/c-cpp-exposing/#what-a-kairo-declaration-looks-like-in-c) | | Overloading | ✅ | ✅ | An imported overload set is ranked as C++ ranks it, parameter modes included; a header that overloads `f(T)` against `f(const T&)` is an error at the import. See [Overloading](/docs/language/functions-overloading/) | | Default arguments | ✅ | ✅ | C++ applies an imported function's defaults, so only trailing arguments can be left out ([SC107E](/docs/language/functions-parameters/#defaults-on-imported-c-functions)). A Kairo default reaches C++ callers: `pub fn dflt(a: i32, b: i32 = 10)` is called as `lib::dflt(1)` and returns 11 | | Named arguments | - | - | **Kairo-only.** Work on imported functions, but cannot skip an earlier defaulted parameter. See [Named arguments](/docs/language/functions-parameters/) | | C variadic functions (`...`) | ✅ | ? | Callable from Kairo (`printf`). Whether Kairo can declare a C-variadic function, and how C sees it, is not documented: the declaration forms tried (`fn f(n: i32, ...)`, `fn f(*const c_char, ...)`) were syntax errors | | Variadic templates and packs | ✅ | ◐ | A C++ forwarding pack (`Args&&...`) takes any number of arguments ([Template arguments](/docs/language/c-cpp-calling/#template-arguments-pointers-and-forwarding)). A Kairo `...xs: T` is one `Slice` parameter in C++, so C++ passes a slice, not a list of arguments (`lib::sum(1, 2, 3)` is an error). The C++ form of [generic variadic functions](/docs/language/functions-parameters/#generic-variadic-functions) is not documented | | `where` dispatch | - | ✅ | **Kairo-only.** Each group is one C++ function under its public name; the candidates stay private. See [where](/docs/language/where/) | | Function hints (`@hot_path`, `@cold_path`, `@pure`, `@no_inline`, `fn f() const`) | - | ✅ | **Kairo-only.** Emitted as `[[gnu::hot]]`, `[[gnu::cold]]`, `[[gnu::pure]]`, `__attribute__((noinline))`, `[[gnu::const]]`. See [Function hints](/docs/language/attributes/#function-hints) | | Calling conventions (`@preserve_most`, `@preserve_all`, `@preserve_none`) | - | ❌ | **Kairo-only.** Never on a function C or C++ can see (SC136E): only `priv` and local functions. See [Calling conventions](/docs/language/attributes/#calling-conventions) | | `eval` (compile-time) | ✅ | ✅ | An imported `eval` constant is a compile-time constant to C++ code that includes the module, and an `eval` value is a valid C++ template argument (`array`). A C++ `constexpr` function is called in Kairo's `eval` (`eval X: i32 = sq(3)` is 9), and a `constexpr` variable is a Kairo value. See [Eval](/docs/language/eval/) | | Global and `static` variables | ✅ | ✅ | C and C++ globals import (glibc's `timezone`). A namespace-scope `static const` is a C++ `const` variable, a class member a `static const` data member. See [Static Variables](/docs/language/variables/#static-variables) | | **Generics** | | | | | Templates and generics | ◐ | ✅ | Imported templates take Kairo types and values as arguments, and are chosen as C++ chooses them, SFINAE included. Not yet: a ranged `for` over an imported template inside a generic Kairo function over its own `T` (an internal error), a defaulted non-type parameter that depends on an earlier one ([Status](/docs/status/#not-compiled-yet)). Kairo generics are C++ templates, bodies included. See [Templates and Concepts](/docs/language/c-cpp-calling/#templates-and-concepts) and [Generics](/docs/language/c-cpp-exposing/#generics) | | C++ concepts and Kairo `impl` bounds | ◐ | ◐ | A C++ concept imports as a constraint-only interface, usable as a Kairo bound; a concept-constrained template imports as a generic. An overload set told apart by a concept that calls a method of a Kairo class you pass is chosen correctly. A Kairo interface is a C++ concept, and an `impl` bound on a generic function or method is a `requires` clause; a bound on a generic class or struct is not translated, so a bad C++ instance fails inside the member that needs it. See [Templates and Concepts](/docs/language/c-cpp-calling/#templates-and-concepts) and [Generics](/docs/language/c-cpp-exposing/#generics) | | `requires` clauses | ✅ | ◐ | A C++ `requires` clause, `enable_if`, `decltype` return or `void_t` test that fails removes the candidate, as in C++. A Kairo [`requires`](/docs/language/requires/) clause on a generic function or method is a `static_assert` in the C++ template body, not a C++ `requires`: a failing call is a hard error, not a removed candidate | | Virtual interfaces | - | ❌ | **Kairo-only.** Not compiled yet: a call through a pointer to an interface is an internal compiler error. Dispatch through a base class with `virtual` methods instead. See [Virtual Interfaces](/docs/language/interfaces/#virtual-interfaces) | | **Classes** | | | | | Classes | ◐ | ✅ | Imported C++ classes are constructed and called directly. Not yet: inherited constructors (`using Base::Base;`) are not callable (SC063E). Kairo classes keep their layout and vtables; copy and move constructors and the destructor (`op finally`) are public in C++ so C++ containers can hold the type. See [Classes](/docs/language/classes/) | | Inheritance (`derives`) | ✅ | ✅ | A Kairo class can derive a C++ class, and a C++ class a Kairo one, abstract classes included. Every base is a public C++ base; a `priv` or `prot` base narrows its members through using-declarations. See [Inheritance](/docs/language/classes-inheritance/) | | Multiple inheritance | ✅ | ✅ | A Kairo class with several bases has the platform's C++ layout, and a Kairo class can derive from several C++ classes (`class M derives A, B1`; the fields of both are readable). See [Multiple inheritance](/docs/language/classes-inheritance/#multiple-inheritance) | | Virtual methods and abstract classes | ✅ | ✅ | Vtable-compatible both ways. A C++ override of a Kairo `virtual fn` must be `noexcept` unless the Kairo method is `@unwind`; a Kairo override of a `noexcept` C++ virtual must not be `@unwind`. See [Virtual Dispatch](/docs/language/classes-inheritance/#virtual-dispatch) | | Access control (`pub`, `prot`, `priv`) | ◐ | ✅ | `priv` is `private:`, `prot` is `protected:`; the class befriends its file's functions. Struct fields are public in C++. A `priv` top-level declaration does not cross unless a `pub` inline or generic body names it. Kairo does not check C++ access itself: reading a private member of an imported class is refused by the generated C++ and reported as an internal error (I003E), not a Kairo access diagnostic. See [What crosses an include](/docs/language/c-cpp-exposing/#what-crosses-an-include) | | `extend` | - | ✅ | **Kairo-only.** An extension member is not a C++ member function: it is a static function of a companion struct beside the type, taking the receiver as its first parameter, and a same-file `extend`'s companion is a friend of the type, so `priv` access works. An extension operator is also a free C++ operator. See [Using Kairo in C++](/docs/language/c-cpp-exposing/#what-a-kairo-declaration-looks-like-in-c) | | RTTI and `dynamic_cast` | ✅ | ✅ | Kairo's checked downcast `p as *D?` compiles to `dynamic_cast`, and Kairo classes carry the platform's RTTI. It works on an imported polymorphic C++ class too: `a as *D?` is non-null for a `D` and null for a plain `A`. See [Casting](/docs/language/casting/) | | **Operators** | | | | | Operator overloading | ✅ | ✅ | C++ member operators, free operators found by ADL, hidden friends and operator templates all apply; unary `*` calls `operator*`. A Kairo `op` is a C++ operator. See [Operators on C++ types](/docs/language/c-cpp-calling/#operators-on-c-types) | | Three-way comparison (`<=>`) | ✅ | ✅ | On a C++ operand, `<` and the other relational operators fall back to `<=>` as in C++20, and `!=` to `!(a == b)`. Kairo's `op <=>` returns `Ordering`. See [Derived comparisons](/docs/language/operator-overloading/#derived-comparisons) | | `for` over a range | ✅ | ✅ | An imported C++ class iterates through `begin()` / `end()`, members or found by ADL ([for](/docs/language/control-flow/#for-range-and-iterator)). C++'s range `for` works over a Kairo map (`begin()` / `end()` over entries). A Kairo type's own `op in` in C++'s range `for` is not documented | | **Errors** | | | | | Panics (`panic`, `try` / `catch`) | - | ✅ | **Kairo-only.** C++ gets the `[[nodiscard]]` result union and reads it with `::builtin::ok`, `value`, `is`, `error`, `site`, or converts it to an exception with `value_or_throw`. The error's source location is found on ELF targets only so far. A C++ type can be panicked as a value. See [The value API](/docs/language/c-cpp-exceptions/#the-value-api) | | C++ exceptions | ◐ | ❌ | **C++-only.** Caught by `catch e: cxx::std::exception` in either `try` form, provided every Kairo frame in between is `@unwind`; a `noexcept` Kairo frame terminates the program. Not yet: printing `what()` in an f-string. Kairo never throws by design: C++ code may convert a result with `value_or_throw`. See [Exceptions](/docs/language/c-cpp-exceptions/#exceptions) | | `@unwind`, `@no_unwind`, `-funwind` | - | ✅ | **Kairo-only.** Every Kairo function is `noexcept` in C++; `@unwind` (or `-funwind`) removes it so a C++ exception can pass through. Not yet on a closure. See [C++ exceptions through Kairo frames](/docs/language/c-cpp-exceptions/#c-exceptions-through-kairo-frames) | | **Memory** | | | | | Heap allocation (`@create`, `@destroy`) | - | ✅ | **Kairo-only.** `@create T(args)` and `@destroy p` compile, with no import needed; the initializer form `@create T{...}` is not compiled yet (SC116E, [Status](/docs/status/)). Its pointer is a plain `T*` to C++: free it through Kairo (`@destroy`), or from C++ with a `delete` of a Kairo type (see the next row), never with `free()` ([What is still an error](/docs/language/c-cpp-memory/#what-is-still-an-error)). See [Heap Allocation](/docs/language/pointers/#heap-allocation) | | C++ `new` / `delete` on Kairo classes | - | ✅ | Every Kairo class, struct and ADT enum in C++-facing output (an `--emit-headers` header, `#include "x.k"`) carries class-scope `operator new` / `operator delete` functions bound to Kairo's global allocator, so C++'s `new` / `delete` of a Kairo type goes through Kairo's allocator. Kairo code cannot define or overload them; a class defines only its constructors and destructor. See [Class-specific operator new and operator delete](/docs/language/c-cpp-memory/#class-specific-operator-new-and-operator-delete) | | `@cxx::new` / `@cxx::delete` | - | ✅ | **Kairo-only.** `@cxx::new T(args)` is a plain C++ `new T(args)` (an `unsafe *T`), `@cxx::new [T; n]` is `new T[n]`, `@cxx::delete p` is `delete p` and `@cxx::delete [] p` is `delete[] p`: for memory that crosses into or comes from C++. See [Memory that belongs to C++](/docs/language/c-cpp-memory/#memory-that-belongs-to-c-cxxnew-and-cxxdelete) | | Global allocator (`@set_global_allocator`) | ✅ | ✅ | The global allocator is five C symbols: C or C++ can supply them, and C can call them. See [The global allocator ABI](/docs/language/allocators/#the-global-allocator-abi) | | `CxxNewAllocator` | ❌ | - | Specified, but not in the 0.2.0 library: `@set_global_allocator(CxxNewAllocator)` is R021E, an unknown type name. See [CxxNewAllocator](/docs/language/c-cpp-memory/#cxxnewallocator) | | Scoped allocators | - | ? | **Kairo-only.** Specified to never reach a C++ `delete`, which relies on the class-specific operators above and on Tether, which is not in this release. See [Scoped allocator](/docs/language/allocators/#scoped-allocator) | | Ownership and lifetime attributes in headers | - | ❌ | **Kairo-only.** Clang's `ownership_returns` / `ownership_takes`, `lifetimebound` and `gsl::Owner` / `gsl::Pointer` are derived from Tether and come with Stage 2 ([ABI stability](/docs/language/c-cpp-abi/#abi-stability-across-compiler-stages)). See [Ownership annotations](/docs/language/c-cpp-memory/#ownership-annotations-in-generated-headers) | | Tether (lifetime analysis) | - | ❌ | **Kairo-only.** Not in this release. As designed, a raw pointer from C++ is untracked, a pointer handed to C++ loses its facts, and a function C++ can reach is treated as entered from an unknown thread. See [Tether: C/C++ Interop](/docs/language/tether-internals/#cc-interop) | | **Concurrency** | | | | | `thread` variables | ✅ | ✅ | A Kairo `thread` variable is a C++ `thread_local` (`lib::tv` reads 5 from C++). A C++ `thread_local` is read and assigned from Kairo. See [Thread-Local Variables](/docs/language/variables/#thread-local-variables) | | Generators and coroutines | ? | ◐ | Kairo generators (`-> yield T`) compile to C++20 coroutines. C++ gets `::builtin::coro::generator::Yield` and drives it with `next()` and `current()` (a loop summing two yielded values gave 3). A C++ coroutine type consumed from Kairo is not documented. Yielding a literal fails in the C++ step. See [Generators](/docs/language/functions-generators/) | | `async`, `await`, `spawn`, `thread f()` | ❌ | ❌ | Not compiled yet: see [Concurrency](/docs/language/concurrency/) and [Status](/docs/status/). A test with `async fn` was a syntax error (S052E) | --- ## A Note on C++ Modules C++20 named modules (`import std;`, `import my_module;`) are **not currently supported**. The interop layer relies on header-based inclusion via Clang's preprocessor, and module interface deserialization (consuming pre-compiled BMIs) is a future roadmap item. Exporting Kairo code as a C++ module interface unit (`.cppm`) is also planned but not yet implemented. **For now:** use header-based interop ([`ffi "c++"`](/docs/language/c-cpp-calling/#the-ffi-keyword) + [`kcc`](/docs/language/c-cpp-toolchain/#kcc-the-c-driver)) for all cross-language boundaries. ## See also - [Modules](/docs/language/modules/) - [Imports](/docs/language/imports/) - [Pointers](/docs/language/pointers/) - [Unsafe](/docs/language/unsafe/) --- ## Allocators URL: https://www.kairolang.org/docs/language/allocators/ # Allocators Allocation goes through [`@create T()`](/docs/language/pointers/#heap-allocation) and `@destroy`; both route to the allocator in effect at that point. `@destroy p` runs the destructor (`fn op finally`) of `*p` and returns the memory to the allocator (`@free p`). Kairo has no `delete` expression, and `x.finally()` runs the destructor early without freeing. See [Freeing memory](/docs/language/classes-lifecycle/#freeing-memory). Three kinds exist, chosen by scope: **global**, **scoped** and **freestanding**. ### Global allocator The default for [`@create T()`](/docs/language/pointers/#heap-allocation) and all standard-library heap operations. Out of the box it is `System`, the runtime's bundled [mimalloc](https://github.com/microsoft/mimalloc) (see [Sharing the heap with C and C++](#sharing-the-heap-with-c-and-c)). A program replaces it with `@set_global_allocator`, on a line of its own at file scope: ```kairo class Arena { static fn alloc(size: usize, align: usize) -> unsafe *u8 { ... } static fn free(ptr: unsafe *u8, size: usize, align: usize) { ... } static fn resize(ptr: unsafe *u8, old_size: usize, new_size: usize, align: usize) -> bool { ... } static fn realloc(ptr: unsafe *u8, old_size: usize, new_size: usize, align: usize) -> unsafe *u8 { ... } static fn alloc_zeroed(size: usize, align: usize) -> unsafe *u8 { ... } } @set_global_allocator(Arena) ``` The choice is made when the program **links**, not per file: every file's allocations, and those of every library linked in, go to `Arena` without any of them mentioning it. The argument must be a class or struct with the five static functions above (the `FullAllocator` interface); a missing one is an error at the attribute. **One per program.** Exactly one linked file may set it. A second in the same file, or in another file of the same build, is a compile error naming both; two objects compiled separately that each set it are a link error naming both objects. A library should not set the global allocator: that decision belongs to the program. Libraries that want their own memory use a [scoped allocator](#scoped-allocator) or the `_in` functions with an allocator of their own. How it works, and what is fixed for compatibility, is under [The global allocator ABI](#the-global-allocator-abi). ### Scoped allocator An allocator with RAII semantics it frees everything it allocated when it leaves scope. Set with `@mem::set_scoped_allocator(MyAllocator)` on a function or block. ```kairo @mem::set_scoped_allocator(ArenaAllocator) fn process_frame() { var *a = @create Mesh(vertices) var *b = @create Texture(pixels) // freed wholesale when process_frame returns } ``` A pointer allocated through a scoped allocator that escapes the allocator's scope is [**Tier N**](/docs/language/tether-proof-model/#the-residual-table). The arena frees the memory at scope end; no smart pointer and no runtime check rescues a pointer to freed arena memory (and across threads, the free races the access). The escape increments the allocation's epoch at the scope close, so the escaping pointer fails C1 by the same machinery as any other dangling pointer. The only fix is restructuring: allocate through the global allocator, or move the scoped boundary outward. ### Freestanding allocator A scoped-allocator variant for embedded and bare-metal targets, conforming through `static` functions only no indirection, no vtable. The compiler replaces `@create T()` with a direct static call plus placement construction. Tether treats freestanding allocators identically to scoped allocators for lifetime tracking; the difference is a codegen concern. --- ## The Allocator Interface A type passed to `@set_global_allocator` or `@mem::set_scoped_allocator`, or used as a freestanding allocator, must satisfy `Allocator` (and `@set_global_allocator` needs the whole `FullAllocator`: `Resizer`, `Reallocator` and `ZeroAllocator` too). Conformance is [structural](/docs/language/interfaces/#structural-conformance) and goes through static functions only, so an allocator carries no instance state and no vtable: ```kairo interface Allocator { static fn alloc(size: usize, align: usize) -> unsafe *u8 static fn free(ptr: unsafe *u8, size: usize, align: usize) } interface Reallocator derives Allocator { static fn realloc(ptr: unsafe *u8, old_size: usize, new_size: usize, align: usize) -> unsafe *u8 } ``` An allocator that does not conform to `Reallocator` is grown with `alloc`, a copy, and `free`. This is not the same thing as the `Heap` example on the Interfaces page. That is a [virtual interface](/docs/language/interfaces/#virtual-interfaces): instance-based, called through a pointer with dynamic dispatch. `Allocator` is static and resolved at compile time. --- ## The global allocator ABI The global allocator is five C symbols. The builtin's `Global` calls them; which allocator answers is decided by the linker: ```c unsigned char *kairo_global_alloc(size_t size, size_t align); void kairo_global_free(unsigned char *ptr, size_t size, size_t align); bool kairo_global_resize(unsigned char *ptr, size_t old_size, size_t new_size, size_t align); unsigned char *kairo_global_realloc(unsigned char *ptr, size_t old_size, size_t new_size, size_t align); unsigned char *kairo_global_alloc_zeroed(size_t size, size_t align); ``` - The runtime defines all five **weakly**, as `System`: mimalloc's allocation, free, realloc and zeroed allocation up to an alignment of `2 * sizeof(void *)`, its aligned variants past it. `resize` grows nothing and keeps any shrink, except a shrink from above 128 words to 128 words or less, which it refuses (`false`) so `realloc` moves the block: mimalloc's small free cannot release a block from a large page. - The file that writes `@set_global_allocator(A)` defines all five **strongly**, each a forwarder to `A`'s static function of the same name. A strong definition beats a weak one, so the program gets `A`. Two strong definitions are the duplicate-symbol error described above. - C or C++ code can supply the global allocator the same way: define the five symbols (with C linkage) in any object of the link. - Without LTO, a call through `Global` is one direct call to the symbol. With LTO the forwarder, and `A`'s functions where they are inline, inline into the caller. The contract is `Allocator`'s: `align` is a power of two and `size` is never 0 (the front end handles both before an allocator is reached); `free` gets the size and alignment the block was made with, or the new size of its last successful `resize`/`realloc`; failure is a null return, never an abort; a failed `resize` or `realloc` leaves the block as it was; every function is thread-safe. `resize` never moves the block (`false`: nothing changed); `realloc` may (null: nothing changed). The names, the argument order and these types are fixed across compiler versions, so objects built by different Kairo releases, and hand-written C, link together. ### `ScopeFrame` A [scoped allocator](#scoped-allocator) in effect is one `ScopeFrame` on the stack of the function that opened it, linked into a per-thread stack (`scope_top`; a plain global on targets with no threads). Allocation goes to the top frame; `free` goes to the frame whose range holds the address, or to the global allocator when none does. Code built by different compiler versions shares this stack, so the frame's layout is ABI: seven pointer-sized fields, in this order, with no padding between them: | # | Field | Type | |---|-----------|---------------------------------------------------------------| | 0 | `alloc` | `unsigned char *(*)(size_t size, size_t align)` | | 1 | `free` | `void (*)(unsigned char *ptr, size_t size, size_t align)` | | 2 | `resize` | `bool (*)(unsigned char *ptr, size_t old, size_t new, size_t align)` | | 3 | `realloc` | `unsigned char *(*)(unsigned char *ptr, size_t old, size_t new, size_t align)` | | 4 | `lo` | `unsigned char *`, the first address the allocator hands out | | 5 | `hi` | `unsigned char *`, one past the last | | 6 | `prev` | `ScopeFrame *`, the frame below, or null | The four functions are the allocator's static functions, with the same contract as the global symbols. `lo`/`hi` are the allocator's `range()` when the scope opened. Reordering, removing or retyping a field is an ABI break between objects built by different compiler versions. --- ### Sharing the heap with C and C++ On ELF targets (Linux, FreeBSD, NetBSD) and on WebAssembly, the bundled mimalloc also replaces `malloc` and `free` for the whole program, so C, C++ and Kairo share one heap and a block may cross between them: a block `System` allocated may be released by C's `free`. On Windows and Apple targets it does not (those keep the CRT heap and malloc zones): there a block Kairo allocates is freed by Kairo, and a block C or C++ allocates is freed by C or C++. ## Allocators and C++ In the C++ an including file sees (a `kcc` `#include "x.k"`, an `--emit-headers` header), every Kairo class, struct and ADT enum carries class-specific `operator new` and `operator delete`, defined by the compiler (Kairo code cannot define or overload them), that always bind to the global allocator. C++ code can `new` and `delete` Kairo objects directly, a C++ `delete` may free what `@create` made (and `@destroy` what C++ `new`ed), and a C++ global `operator new` override does not affect them. In the other direction, memory that must come from or go to C++'s allocator is allocated with `@cxx::new T(args)` (plain C++ `new`, returning `unsafe *T`) and freed with `@cxx::delete p`, never with `@destroy`. To route Kairo's own allocations through C++'s allocation path instead, set `core::CxxNewAllocator` as the global allocator. See [Allocators & Ownership](/docs/language/c-cpp-memory/) for the details. ## See also - [Tether](/docs/language/tether/) - [Pointers](/docs/language/pointers/) - [Ownership](/docs/language/ownership/) - [Allocators & Ownership (C++)](/docs/language/c-cpp-memory/) - [Unsafe](/docs/language/unsafe/) --- ## ABI Contract & Verification URL: https://www.kairolang.org/docs/language/c-cpp-abi/ # ABI Contract & Verification ## Link-time ABI Verification Flag translation only sees a single invocation. Objects compiled at different times, by different people, with different flags, and linked later are outside its reach. **[`kld`](/docs/toolchain/kld/)** closes that gap. Every object produced by `kairo` or `kcc` carries an ABI note section recording: - the set of ABI-affecting settings that were in effect, canonicalized and sorted - a hash of that set, for fast comparison - a format version - the calling conventions the object defines or calls (`@preserve_most`, `@preserve_all`, `@preserve_none`), and, when it uses any, the LLVM major that generated it. LLVM does not keep these conventions stable across releases, so `kld` rejects a link in which two objects that use them were built by different LLVM majors (see [Calling conventions](/docs/language/functions-declarations/#calling-conventions)). Objects that use none of them never take part in this check. At link time, `kld` compares hashes. A mismatch is a clean link error naming the specific flag: ``` error: ABI mismatch between input objects a.o was compiled with -fno-rtti b.o was compiled with -frtti note: these settings change type layout and cannot be mixed in one binary ``` The raw setting list is kept alongside the hash precisely so this message is possible. A hash alone can only say *that* something mismatched, not *what*. > [!NOTE] > The hash covers the semantic set of resolved settings, not the command-line string. Flag order and alternate spellings of the same setting produce the same hash. ### Objects not built with the Kairo toolchain `kld` links ordinary C++ objects, including prebuilt system libraries. Those have no ABI note, so nothing can be verified about them. `kld` reports what it could not check: ``` warning: 3 object(s) were not built with kcc or kairo; ABI compatibility unchecked libfoo.a(bar.o), libfoo.a(baz.o), /usr/lib/qux.o ``` If one of those objects was built with mismatched settings, the result is a runtime crash with no diagnostic. That is unavoidable (the information was never recorded), but the boundary of the guarantee is made visible rather than left implicit. Suppress with `-Wno-unverified-abi`. **This is the reason to use `kcc` rather than the system `clang++`.** Every object that goes through the Kairo toolchain is covered. ## Name mangling Kairo does not implement Itanium or MSVC mangling itself. Kairo constructs the corresponding Clang declaration and asks Clang's `MangleContext` for the symbol. Both ABIs come from the same source of truth as the C++ side of the boundary, and there is no second implementation to drift. --- ## ABI Compatibility Kairo emits object code conforming to the platform's native C++ ABI: - **Unix-like systems:** Itanium C++ ABI - **Windows:** Microsoft C++ ABI Name mangling, vtable layout, RTTI, and struct layout all follow the platform convention, so Kairo `.o`/`.obj` files link with object files from any ABI-compliant C++ compiler without shims or translation layers. [`ffi "c++"` declarations](/docs/language/imports/#ffi-linkage-declarations) use C++ mangling. `ffi "c"` declarations use C mangling (no decoration). This matches the behavior of `extern "C++"` and `extern "C"` in C++. Two Kairo-specific guarantees strengthen the baseline: - **Kairo never throws.** See [above](/docs/language/c-cpp-exceptions/#kairo-to-c-kairo-never-throws). - **ABI settings are recorded in the object and verified at link.** See [Link-time ABI verification](#link-time-abi-verification). ### ABI stability across compiler stages Later compiler stages emit *more* information, not different information, so the ABI does not change: | Stage | Emits | |---|---| | Stage 1.5 (the current, self-hosted compiler) | Declarations, definitions, ordering, mangling. | | Stage 2 (planned) | The same, plus lifetime, aliasing, and ownership attributes derived from Tether analysis. | Objects from either stage are ABI-compatible. Stage 2's additions give the C++ side more static checking, not a different layout. --- ## Declaration Ordering C++ requires a type to be complete before it is used by value. Kairo does not impose that ordering on the programmer (declarations may appear in any order in a `.k` file), so the emitter reconstructs a valid order. Emission proceeds in four phases: 1. Forward declarations for every user type, in any order. This satisfies every pointer and reference edge. 2. Function and method declarations, in any order. 3. Type definitions, in dependency order over **by-value** edges only: value members, bases, fixed-array elements, and template arguments that land by value. 4. Function bodies, in source order. A cycle in the phase-3 graph is a genuine error: a type whose definition requires its own layout has no finite size. It is diagnosed on the Kairo side with the full cycle path: ``` error: recursive type definition requires infinite size `A` contains `B` by value `B` contains `A` by value note: use `*A` to break the cycle ``` Pointer and reference members do not create this edge, which is why `struct B { *A a; }` is legal alongside `struct A { B b; }`. --- ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [Allocators & Ownership](/docs/language/c-cpp-memory/) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [Attributes](/docs/language/attributes/) - [Classes](/docs/language/classes/) --- ## Calling C and C++ from Kairo URL: https://www.kairolang.org/docs/language/c-cpp-calling/ # Calling C and C++ from Kairo ## Calling C/C++ from Kairo Import a C or C++ header with the [`ffi` directive](/docs/language/imports/#ffi-header-imports). The compiler parses the header, extracts declarations, and makes them available as native Kairo symbols. No wrapper code is required. ```kairo // main.k ffi "c++" import "my_code.hh"; fn main() { var obj = MyClass("Kairo") obj.greet() my_function(42) } ``` Given this C++ header: ```cpp // my_code.hh #include #include class MyClass { public: MyClass(const char *name) : name(name) {} void greet() const { std::cout << "name = " << name << std::endl; } private: std::string name; }; inline void my_function(int x) { std::cout << "Hello from C++! x = " << x << std::endl; } ``` Build and run: ```sh kairo main.k -o main ./main ``` ``` name = Kairo Hello from C++! x = 42 ``` > [!NOTE] > `ffi "c++"` invokes the pinned Clang's frontend internally to parse the header. All exported declarations (functions, classes, enums, templates) become available in Kairo's scope with their original names and signatures. No code generation or binding step is visible to the user. Kairo, not clang, decides which declaration a call means. Overload ranking, argument-dependent lookup, template specialization selection and `requires` / SFINAE constraints on imported declarations are all resolved by Kairo's own semantic analysis, with C++'s rules (so a Kairo and a C++ caller of the same overload set get the same answer). Clang is asked for exactly two things: to complete the instance of an imported class template (`cxx::std::vector` gets its members from clang's instantiation), and to deduce the template arguments of an imported function-template candidate. Everything it is asked is an answer about one declaration, never a choice between several. An imported function's default arguments are applied by C++, which can only leave out trailing arguments. Naming a later parameter while an earlier defaulted one is omitted is an error (SC107E); pass the earlier ones explicitly. See [Functions](/docs/language/functions-parameters/#defaults-on-imported-c-functions). ### Operators on C++ types Using an operator on C++ types follows C++ lookup: - **Member operators:** `a.operator+(b)`. - **Free operators:** found by argument-dependent lookup in the operands' namespaces, across every header that reopens that namespace. - **Hidden friends** (`friend bool operator==(...)` defined inside a class): found through either operand's class. - **Operator templates:** chosen by C++'s partial ordering. - **C++20 rewrites:** when an operand is a C++ type and no `!=` takes the operands, `a != b` is `!(a == b)`; `<` and the other relational operators fall back to `<=>` the same way. Kairo types keep Kairo's own rule: `!=` is derived from `op ==` only when the type declares no `op !=`. See [Derived comparisons](/docs/language/operator-overloading/#derived-comparisons). Unary `*` on an imported C++ class calls its `operator*`, which is how C++ iterators and smart pointers are read. ### Argument conversions C and C++ signatures are judged by Kairo's conversion rules, with one addition: a fixed-width integer argument widens into a `size_t`, `ptrdiff_t`, `uintptr_t` or `intptr_t` parameter, and a `usize`/`isize` argument widens into a fixed-width one, whenever that is lossless on every 32- and 64-bit target. `n: u32` passes to a `size_t` directly on 32- and 64-bit targets; `n: u64` needs `as usize`. See the [Conversion Lattice section 4.1](/docs/language/conversion-lattice/#41-the-cc-boundary). C++'s own implicit conversions do not apply by default: an argument C++ would convert through a converting constructor or conversion operator (a string literal to a `std::string` or a class with a `const char*` constructor, an `A` to a `B(const A&)`) is an error whose fix-it writes ` as T`. `-fcxx-implicit-conv` lets C++ apply that one conversion at calls, initialisations and returns that cross into C++. `-fimplicit-conv` governs only Kairo's own conversions and does not turn this on. ### Tags and ordinary names C and C++ keep struct, class, union and enum names (tags) apart from variables, functions and typedefs, so a header can declare both under one name. glibc does: `struct timezone` in `` and `extern long timezone` in ``. As in C++, the plain name means the ordinary declaration: ```kairo ffi "c++" import "time.h" ffi "c++" import "sys/time.h" fn example() { var west: i64 = timezone // the variable } ``` The struct is still the type of everything that uses it, such as `gettimeofday`'s second parameter. To name it yourself, declare it with a bodiless `ffi` struct, which refers to the header's `struct timezone` instead of declaring a new type: ```kairo ffi "c++" import "time.h" ffi "c++" import "sys/time.h" ffi "c" struct timezone fn now(tv: unsafe *timeval, tz: unsafe *timezone) -> i32 { // the struct var west: i64 = timezone // still the variable return gettimeofday(tv, tz) } ``` In a type, `timezone` is then the struct; in an expression, it is still the variable. `class` and `union` work the same way. Without a matching struct in the imported headers, `ffi "c" struct T` is an ordinary forward declaration. `typedef struct X X` is one type, not two names. Two different variables or typedefs under one name, which C++ only allows through inline namespaces, are an error where the name is used, not at the import: `ambiguous import: '{name}' names more than one non-function symbol` (R016E), with a note at each candidate. --- ## The `ffi` Keyword `ffi` controls linkage and name mangling. It is written on a declaration. > [!NOTE] ```kairo // C++ linkage: name mangling, overloading, classes, templates all permitted ffi "c++" fn compute(x: i32) -> i32 { return x + 1; } // C linkage: no name mangling, same restrictions as extern "C" in C++ ffi "c" fn add(x: i32, y: i32) -> i32 { return x + y; } ``` `ffi "c"` follows the same rules as `extern "C"` in C++: no classes, no overloading, no templates. `ffi "c++"` follows the same rules as `extern "C++"`: full C++ feature set, Itanium or MSVC mangling depending on the target. The language string is matched without case: `ffi "C"` is `ffi "c"`, and `ffi "c++"` may also be written `"cpp"` or `"cxx"`. Name mangling is covered in [ABI Contract & Verification](/docs/language/c-cpp-abi/#name-mangling). --- ## Namespace Mapping `std` means different things on the two sides of the boundary. The mapping is fixed: | Spelling | On the Kairo side | On the C++ side | |---|---|---| | `std::` | Kairo's standard library | C++'s standard library | | `cxx::std::` | C++'s standard library | - | | `kairo::` | - | Kairo's own namespace, including its standard library | From Kairo, the C++ standard library is always reached through `cxx::std::`: ```kairo ffi "c++" import "vector" fn example() { var v: cxx::std::vector v.push_back(42) } ``` Kairo's standard library lands inside `namespace kairo`, which is why a C++ translation unit sees Kairo's library under `kairo::` and its own under the unqualified `std::` it already uses. Nothing is renamed on the C++ side. Your own code lands in its module's namespace, the files you compile included, or, for a file outside every search directory, in a namespace named after the file's stem. See [Modules](/docs/language/modules/#module-paths-are-c-namespaces). > [!NOTE] > `inline "c++"` blocks are not supported. Use `ffi "c++"` to import declarations and call them as ordinary Kairo symbols. The older `__inline_cpp("...")` form is likewise removed. --- ## Inline ASM For cases where you need to embed hardware-specific instructions, use `inline "asm"` blocks. Kairo uses the extended assembly syntax (outputs, inputs, and clobbers) to allow safe interaction between assembly and Kairo variables. > [!NOTE] > Not yet: an `inline "asm"` block parses and type-checks, but code generation does not emit it. A program containing one stops with an internal compiler error (`EmitIR: inline foreign block; not emitted yet`). The examples below show the intended syntax. ```kairo fn get_timestamp() -> u64 { var low: u32 var high: u32 // The syntax follows: "instruction" : outputs : inputs : clobbers unsafe { inline "asm" { "rdtsc" : "=a"(low), "=d"(high) : : } } return (high as u64 << 32) | (low as u64) } fn syscall_example(fd: i32, buf: *u8, len: usize) -> isize { var ret: isize unsafe { inline "asm" { "syscall" : "=a"(ret) : "a"(1), "D"(fd), "S"(buf), "d"(len) : "rcx", "r11", "memory" } } return ret } ``` ### Constraints and Safety - **Volatile**: the `volatile` modifier (`inline "asm" volatile { ... }`), meant for assembly with side effects the optimizer might otherwise remove, is not accepted yet: the parser rejects it (S056E). - **Clobbers**: Always list registers modified by the assembly (like `memory` or specific registers) to prevent the [Tether analysis](/docs/language/tether-internals/#cc-interop) and LLVM from making incorrect assumptions about the state of the machine. - **Unsafe**: Assembly code is inherently unsafe and must be inside an `unsafe` block or an unsafe function (SC296E otherwise); it is wrapped in an [`unsafe` block](/docs/language/unsafe/#unsafe-blocks) to indicate that the programmer is responsible for ensuring the correctness of the assembly. --- ## Pointers and References Kairo's [pointer model](/docs/language/pointers/) distinguishes safe pointers (`*T`, non-nullable, tracked) from raw pointers (`unsafe *T`, no tracking). Passing any pointer or reference across the FFI boundary requires explicit [`unsafe` context](/docs/language/unsafe/#when-unsafe-blocks-are-required) because the compiler cannot enforce safety guarantees on the C/C++ side. C++ reference *parameters* (`T&`, `const T&`, `T&&`) are not pointers. They map to Kairo's parameter modes (`@inout x: T`, `x: T`, `@move x: T`). See [Parameter passing modes](/docs/language/functions-parameter-modes/). So an argument to a non-const `T&` parameter is marked `&x`, as for any `@inout` parameter, and is passed by reference: nothing is copied or moved, and an object of a class derived from `T` binds too. A bare `x` is an error (SC097E) with a fix-it that adds the `&`. A safe `&x` is the marker, so `pick(&x)` calls `pick(int&)` over `pick(int*)`; `pick(unsafe &x)` passes the raw pointer and calls `pick(int*)`. ```kairo ffi "c++" import "sstream" var f = cxx::std::istringstream(cxx::std::string("a\nb\n")) var line = cxx::std::string() while cxx::std::getline(&f, &line) as bool { // istream&: f is borrowed, not moved // ... } ``` ### Function objects An object of a C++ class with `operator()` (a lambda's closure type, `std::function`, `llvm::function_ref`) is called as `f(args)`. The call is resolved over the class's `operator()` overloads as C++ resolves it: a const object picks the const overload, and the arguments pick among the rest. The object itself is not moved by the call. Through a pointer, call `(*p)(args)`; a pointer to a function object is not itself callable. ### Calls that return a reference A call that returns a C++ reference, such as `v.at(i)`, `*p`, or `cout << x`, is usable directly as an operand and as the target of an assignment: ```kairo ffi "c++" import "vector" fn main() { var v: cxx::std::vector v.push_back(1) v.at(0) = 3 // assign through int& v.at(0) += 2 // compound assignment var x = v.at(0) + 1 // operand } ``` An override of a C++ virtual must return what the virtual returns; a mismatch is SC294E with the C++ type as a fix-it. A C++ `operator[]` that returns by value gives a temporary: `c[0] = x` on it is an error. One that returns a reference is a place. `std::pair` of a move-only Kairo class is move-only: it moves, and copying it is SC182E. `std::optional`, `std::tuple`, `std::variant` and `std::expected` of a move-only Kairo class are move-only too: they move, and copying one is SC182E. A `std::span` of one is a view and copies. A field of a temporary (`f().x`, `v[0].x` through a by-value `operator[]`) is not assignable, and its address cannot be taken. Such a call is an lvalue of the referenced type (an xvalue for `T&&`): `&v.at(0)` is a `*i32`, and `var x = v.at(0)` copies. Editor hovers show these functions with the return spelling a Kairo definition uses, `-> ffi::ref`. To define or override a C++ function that returns a reference, see [Reference returns from C++](/docs/language/functions-parameter-modes/#reference-returns-from-c). See [Reference returns from C++](/docs/language/functions-parameter-modes/#reference-returns-from-c) for how these calls are typed. ### Safe variable, unsafe pass ```kairo ffi "c++" import "my_code.hh"; fn main() { var x = 41 // compile error: cannot pass reference to C function without unsafe block // add_one(&x) unsafe { add_one(unsafe &x) // strips tracking; caller owns the memory contract } // for calling c++ with pointers and back, you must use unsafe blocks; // shorthand syntax is not allowed: `unsafe add_one(unsafe &x)` is a compile error io::println(f"x = {x}") // x = 42 } ``` `unsafe &` creates a [raw pointer](/docs/language/pointers/#creating-raw-pointers) from a safe binding. The compiler relinquishes tracking for that pointer, and the caller is responsible for lifetime and aliasing correctness. ### Heap value, raw pass `@create` returns a safe `*T`, never a raw one, so `var x: unsafe *i32 = @create i32(41)` is an error (SC028E). A heap value passed to C/C++ is converted at the call, inside `unsafe`: ```kairo ffi "c++" import "my_code.hh"; fn main() { var *x = @create i32(41) unsafe { add_one(x as unsafe *i32) } io::println(f"x = {*x}") // x = 42 } ``` Passing the safe `*i32` straight to an `int*` parameter is a no-matching-overload error (SC063E). > [!WARNING] > `unsafe *T` pointers can be null. Dereferencing a null `unsafe *T` is undefined behavior. The compiler will not insert a null check. ### Strings and `const char*` C's `char` is [`std::c_char`](/docs/language/primitives/#cs-char-stdc_char), so a C++ `const char*` is `*const c_char` in Kairo, and back: a function returning one can be stored, compared with `&null`, indexed and passed on to any C or C++ parameter of that type. `char`, `signed char` and `unsigned char` are three types, as in C++, so a header that overloads on them gives three Kairo overloads (`c_char`, `i8`, `u8`). Likewise `wchar_t`, `char16_t` and `char8_t` are `c_wchar`, `c_char16` and `c_char8`, so `f(wchar_t)` beside `f(int)` is two overloads, and a `const wchar_t*` is `*const c_wchar`. A string **literal** passed to an imported C or C++ function's `const char*` parameter (`*const c_char`, safe or `unsafe`) is the C string itself: the compiler passes the literal's static, NUL-terminated bytes, and no `string` is made. The same holds for a `const unsigned char*` (`*const u8`) parameter and for the `...` of a variadic C function such as `printf`. The parameter must be `const`: a literal's bytes are read-only, so a `char*` parameter does not take one. Any other [`string`](/docs/language/primitives/#strings) passes its bytes with `s.c_str()`, which returns `unsafe *const c_char`. It costs nothing: a Kairo string keeps a NUL after its last byte, a literal's and an owned string's alike. The pointer is valid until the string is next changed or destroyed. Passing the `string` itself is an error whose fix-it inserts `.c_str()`: ```kairo ffi "c" import "string.h" ffi "c" import "stdlib.h" ffi "c" import "stdio.h" fn main() { var n = strlen("hello") // 5: the literal is the C string var unsafe *home = getenv("HOME") printf("%s %zu\n", "count", n) // literals through C's `...` too var s = "hello" s += ", world" var m = strlen(s.c_str()) // 12 // strlen(s) // error SC063E: a string other than a literal passes its bytes with '.c_str()'; fix-it: `.c_str()` // printf("%s\n", s) // error: a 'string' cannot pass through C's '...'; fix-it: `.c_str()` } ``` The `string`'s bytes are also `data` (`*const u8`). Bytes and C chars are unrelated types, so passing `data` to a `const char*` parameter needs an `as unsafe *const c_char` cast inside an `unsafe` block ([pointer cast rules](/docs/language/casting/#pointer-cast-rules)); passing the `*u8` itself is an error whose fix-it inserts the cast. A `*const c_char` in an f-string prints as a pointer (`const c_char @ 0x...`), like any pointer: there is no C-string formatter yet. ### Function pointers and callbacks A C or C++ function pointer type (`int (*)(int)`) imports as the raw Kairo type `unsafe fn(i32) -> i32`. A named Kairo function or a closure that captures nothing can be passed there. A closure that captures, or a `fn(...)` value (which may hold one), is a compile error, because C has nowhere to keep the captured variables: ```kairo ffi "c" import "callbacks.h" // int c_apply(int (*f)(int), int x); fn twice(x: i32) -> i32 { return x * 2 } fn main() -> i32 { var k = 3 var a = c_apply(twice, 4) // 8 var b = c_apply(fn (v: i32) -> i32 { return v + 1 }, 4) // 5 // c_apply(fn (v: i32) -> i32 { return v * k }, 4) // error: the closure captures 'k' return a + b } ``` --- ## Templates and Concepts Kairo [generics](/docs/language/generics/) and C++ templates meet in both directions. Calling a constrained C++ template from Kairo works; bounding a Kairo generic by a C++ concept does not compile yet. A C++20 concept imports as a constraint-only interface, and a function template constrained by it imports as a generic: ```cpp // concept.h #pragma once template concept Addable = requires(T a, T b) { a + b; }; template T add_twice(T a) { return a + a; } ``` ```kairo ffi "c++" import "concept.h" fn main() -> i32 { var x: i32 = 21 io::println(f"{add_twice(x)}") // 42 return 0 } ``` > [!NOTE] > Not yet: a Kairo generic bounded by an imported concept (`fn add(a: T, b: T) -> T { return a + b }`) is rejected with R025E, because the concept's `requires` expression grants no operations on `T`. A bound whose body does not use `T`'s operations works: the imported concept is named by its own C++ name. A bound on a Kairo interface works: `fn twice(a: T)` becomes a `requires` clause over the concept the compiler emits for `Shape`, and a C++ call with a type that does not satisfy it fails with `'Bad' does not satisfy 'Shape_c'`. A bound on a generic class or struct is not translated (see [Generics](/docs/language/c-cpp-exposing/#generics)). ### Template arguments, pointers and forwarding Non-type template arguments are written as Kairo values: `cxx::std::array`, `llvm::SmallVector<*Node, 8>`, `Flag`. An `eval` constant or arithmetic over constants works (`array`). The argument's identity is its integer, so `array` with `eval N: usize = 4` and `array` are the same type. A container of Kairo pointers keeps the pointer kind you wrote: `cxx::std::vector<*Node>` hands out `*Node`, `vector` hands out `unsafe *Node`. Both are `std::vector` in C++. Any Kairo type with a C++ spelling may be an argument of an imported class template: builtins, pointers, records and generic records, tuples, plain enums, ADT enums (generic or not), and nullables (`vector`, `vector<*Node?>`). The instance's members read back as the Kairo types, so `push_back(null)`, `if x? { ... }`, `v[0] ?? d`, `v[0] = null` and `match` on an element work as for any value. A written `fn(i32) -> i32` as a template argument is the C++ function type `i32(i32)`, so `function_ref bool>(closure)` names the same instance as a C++ `function_ref` parameter; a raw `unsafe fn(i32) -> i32` is the function pointer `R(*)(A)`, a different instance. Not yet: calling a function-type element (`v[0](3)` is rejected). A C++ function template with a forwarding pack (`template void emplace_back(Args&&... args)`) takes any number of arguments; each is passed as written and C++ deduces its reference kind. A `const Ts&...` pack takes any argument, a `Ts&...` pack only variables (lvalues). Overloaded C++ function templates are chosen as C++ chooses them, SFINAE included: an overload whose `enable_if` condition, `requires` clause, `decltype(...)` return type or `void_t` test fails for the arguments is not a candidate. So `cxx::std::make_unique(9)`, `make_unique(n)` (through a header alias such as `using IntArr = int[];`, since `[T;]` in Kairo is a slice) and `make_shared` work, and `v.assign(n, x)` on a `cxx::std::vector` takes the count overload while `v.assign(a.begin(), a.end())` takes the iterator one. When every overload is removed, the error lists each with C++'s reason (`requirement 'std::is_integral_v' was not satisfied`). Only the generic arguments you write are passed (`make_unique`); C++ deduces the rest from the arguments, so a variable passed through `Args&&` stays a reference to that variable. Inside a generic function, a call whose choice depends on `T` is decided for each instantiation. A C++ method with a ref-qualifier is called only on the object it accepts: `int q() &` on a variable, `int q() &&` on a temporary (`make().q()`), and with both declared a temporary calls the `&&` one. A method without a ref-qualifier can be called on either. ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [ABI Contract & Verification](/docs/language/c-cpp-abi/) - [Pointers](/docs/language/pointers/) - [Unsafe](/docs/language/unsafe/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Generics](/docs/language/generics/) --- ## Exceptions & Panics URL: https://www.kairolang.org/docs/language/c-cpp-exceptions/ # Exceptions & Panics ## Exceptions Kairo and C++ signal failure differently, and the two models meet at one place: a Kairo `try`/`catch`. - **Kairo never throws.** A Kairo failure is a [panic](/docs/language/panic/): a tagged union value returned to the caller. No exception ever starts in Kairo code. - **C++ throws.** A C++ exception is unwound by the platform unwinder (libunwind on Unix-like systems). - **Kairo frames are `noexcept`.** Every Kairo function, method, constructor, operator and closure is `noexcept` in its generated C++, unless it is marked [`@unwind`](/docs/language/attributes/#unwinding) or the program is built with `-funwind`. A C++ exception that reaches a `noexcept` Kairo frame terminates the program (`std::terminate`). - **`try`/`catch` handles both.** Around a Kairo call it lowers to a tag compare per `catch` arm on the returned tagged union. Around a C++ call it catches C++ exceptions through the unwinder. ### C++ to Kairo Kairo can catch C++ exceptions using its standard `try`/`catch` syntax. ```kairo ffi "c++" import "my_code.hh"; // void might_throw(bool); void log_message(const char*) fn main() { try { might_throw(true); } catch e: cxx::std::exception { log_message(e.what()) // e is the C++ exception object } } ``` > [!NOTE] > One limit on reading the message from Kairo for now. `e.what()` is a `*const std::c_char` (C's `const char*`), which can be passed on to C or C++ code, as above, or read through C (`strlen(e.what())`), but an f-string prints it as a pointer, `const c_char @ 0x...`, not as text: there is no C-string formatter yet. `e.what()` also works on an arm for a class that redeclares it, such as `cxx::std::runtime_error`. A `catch e: T` arm whose `T` is a C++ type that the `try` body cannot [panic](/docs/language/panic/) with catches a C++ exception of type `T`, by C++'s own rules: an exception of a class derived from `T` matches too, and the arms are tried in order. `e` refers to the exception object. Such an arm is never checked against the panic set and never reported as dead. A C++ type that *is* in the body's panic set is an ordinary panic arm. Which C++ calls are covered is decided by where they are written: a C++ call inside the `try` body, however deeply nested in its expressions and blocks, is covered. The function holding the `try` stays `noexcept`; the `try` is a real C++ `try` inside it. An exception that no arm matches reaches the function's `noexcept` boundary and terminates the program, as one thrown anywhere else in a `noexcept` frame does. A bare `catch` catches panics only, never a C++ exception. ```kairo fn read_or_default(x: i32) -> i32 { try { return checked_double(x) } catch e: cxx::std::runtime_error { return 0 // a std::logic_error here would terminate } } ``` The expression form works the same way: `try checked_double(x) catch e: cxx::std::exception => -1`. C++ arms and panic arms can share one `try`. `panic e` inside a C++ arm panics a copy of the caught exception (of the arm's type) as a Kairo error, raised at that `panic`. C++ exception arms need C++ exceptions: in a build with `-fno-exceptions`, or for a target with no OS where they default off, such an arm is an error ([SC001E](/docs/language/diagnostics/)), with a fix-it removing it. The exception can come from a C++ call several Kairo frames down, but every Kairo frame between the `throw` and the `catch` must let it through: mark each one [`@unwind`](/docs/language/attributes/#unwinding), or build with `-funwind`. A frame that is `noexcept` (the default) stops the exception by terminating the program, before the `catch` is reached. The frame holding the `try` itself does not need `@unwind`: the exception stops there. ```kairo @unwind fn relay(x: i32) -> i32 { return checked_double(x) + 1 // C++, may throw: passes through relay } fn guarded(x: i32) -> i32 { try { return relay(x) } catch e: cxx::std::exception { return -1 } } ``` > [!NOTE] > Unlike Kairo's [panic system](/docs/language/panic/), the compiler cannot statically determine every exception type a C++ function might throw. A `catch` block that doesn't handle a thrown type lets the exception continue to the next enclosing frame, which terminates the program if it is `noexcept`. ### C++ exceptions through Kairo frames A C++ function that throws and catches internally works under any Kairo caller: nothing reaches the Kairo frame. What `noexcept` decides is an exception that leaves the C++ code Kairo called: | The Kairo frame it reaches | What happens | |---|---| | A plain Kairo function (the default) | `std::terminate`: the program aborts | | An `@unwind` function, or any function under `-funwind` | The exception passes through, to the next frame up (a C++ `catch` in a C++ caller works) | | A `@no_unwind` function | `std::terminate`, even under `-funwind` | ```kairo ffi "c++" import "guard.hh" // int checked(int) throws; int guard(int (*)(int), int) catches @unwind fn relay(x: i32) -> i32 { return checked(x) + 1 } fn main() -> i32 { return guard(relay, -4) // -1: thrown through relay, caught by guard in C++ } ``` Without `@unwind` on `relay`, the same program aborts with the C++ runtime's "terminating due to uncaught exception" message. The flags: - `-fno-unwind` (the default): every Kairo function is `noexcept`, except those marked `@unwind`. - `-funwind`: no Kairo function is `noexcept`, except those marked `@no_unwind`. Closures follow the flag (a closure cannot be marked `@unwind` yet). Build every Kairo module and `kcc` host of one program with the same setting. - C++ exceptions themselves are on for a hosted target. A freestanding target (no OS in the target triple, `--freestanding`, kernel mode) has no unwinder and keeps them off unless `-fexceptions` asks; `-fno-exceptions` turns them off anywhere. `noexcept` is part of the C++ contract a Kairo declaration exposes. A C++ class that overrides a Kairo `virtual fn` must mark its override `noexcept` too (C++ rejects an override whose exception specification is laxer than the base's), unless the Kairo method is `@unwind`. The other way, a Kairo override of a C++ `virtual` that is `noexcept` must not be `@unwind`. A function declared with `ffi` linkage, or imported from a C/C++ header, keeps the exception specification its C/C++ declaration states. ### Kairo to C++: Kairo never throws Kairo does not throw. [`panic`](/docs/language/panic/#the-panic-specifier) is a checked effect with a typed set, inferred or declared: a Kairo error is a tagged union value returned to the caller, not an object propagated by the unwinder. No exception ever starts in Kairo code. - A C++ caller never needs a `try`/`catch` to handle a Kairo error; it inspects the returned value. - A C++ exception thrown by C++ code that Kairo calls terminates the program when it reaches a Kairo frame, unless that frame is [`@unwind`](/docs/language/attributes/#unwinding) (or the program is built with `-funwind`), in which case it unwinds through. - Every Kairo function that is not `@unwind` has `noexcept` on its generated C++ declaration and definition, so `noexcept`-conditional C++ code that calls it (`std::vector` reallocation, `std::move_if_noexcept`) takes the `noexcept(true)` branch. #### The value API A fallible Kairo function returns its result union directly, by value and `[[nodiscard]]`. C++ sees a type carrying the tag, the source location of an error, and the possible outcomes, and inspects it without any unwinding involved. The API over the result is a set of free function templates in the `::builtin` namespace (the same namespace that holds `::builtin::null`), emitted with the generated C++. They are free functions rather than members because the result type's class text must be identical in every translation unit and header. | Helper | Meaning | |---|---| | `::builtin::ok(p)` | `true` when `p` holds a value | | `::builtin::value(p)` | The value, by reference; only valid when `ok(p)` | | `::builtin::is(p)` | `true` when `p` holds an error of type `E` | | `::builtin::error(p)` | The error, as `E&`; only valid when `is(p)` | | `::builtin::site(p)` | A `::builtin::source_site { file, line, col }`: where the error was raised. `file` is null for a result that holds a value | | `::builtin::type_id` | The id of error type `E`, the value stored in the tag | | `::builtin::panic_set

` | A trait over a result type `P`: `value_type` (`T`), `types` (`::builtin::panic_types`), `size` (the number of error types) and `payload_offset` (where the value and every error start) | ```cpp #include "config.k" // pub fn load_port(path: string) panic(IOError, RangeError) -> i32 int port_or_default() { auto r = config::load_port("port.txt"); if (::builtin::ok(r)) return ::builtin::value(r); if (::builtin::is(r)) return 0; // ::builtin::error(r) is the Kairo error value return 8080; // IOError } ``` A panic set holds exact types (there is no subtyping between error types; see [Panic](/docs/language/panic/#arms-match-exact-types)), so `is` matches only `E` itself. `is` of a type not in the set is `false`; `error` of one does not compile. The function is declared `[[nodiscard]]`: dropping the result drops the error with it. A header written with `--emit-headers` declares the same function, includes the headers of its error types, and declares the result type `extern template`, so the C++ that includes several Kairo headers instantiates it once. #### Converting to an exception Because chaining over a tagged union is unidiomatic in C++, a result can be converted to a thrown exception with `::builtin::value_or_throw(p)`: it returns the value on success, and otherwise throws `::builtin::panic_error` for the error type `E` the result holds. ```cpp try { int port = ::builtin::value_or_throw(load_port("port.txt")); serve(port); } catch (const ::builtin::panic_error& e) { log(e.error.path); // the Kairo error value } catch (const ::builtin::panic_error_base& e) { log(e.what()); // any other Kairo error } ``` - `::builtin::panic_error` derives from `::builtin::panic_error_base`, which derives from `std::exception`, so `catch (const ::builtin::panic_error_base&)` catches any Kairo error and `catch (const std::exception&)` catches it too. Its `error` member holds the Kairo error value. - `what()` is the error's [`op panic`](/docs/language/operator-overloading/#op-panic) message (the type's own, or one an `extend` gives it) followed by its type and source location: ` [ at ::]`, for example `missing config key 'port' [ConfigError at app.k:12:9]`. A type with no `op panic` (it is optional) gives just the type and location: `ConfigError at app.k:12:9`. The file is the source file's path as the compiler records it, its full path (`/home/me/app/app.k`). The string is built once, when the exception is constructed, and its copies share it. - The location is found only on ELF targets (Linux, the BSDs) so far; elsewhere `site(p)` has a null `file` and `what()` gives the type without a location. A C++ host linked against a Kairo `--shared` library sees only its own sites: an error raised inside the library has no location. - `value_or_throw` takes the result by value: a temporary result's value or error is moved out, a named one's is copied. An error type that can only be moved works too; catch its `panic_error` by reference. - `panic_error_base`, `panic_error` and `value_or_throw` exist only where the C++ is compiled with exceptions; the value API is always there. The conversion is **generated C++**. It inspects the tag and throws from the C++ side of the boundary. Kairo itself still never throws, and the real entry point is unaffected. C++ callers who want exceptions get them; callers who want values keep the value API. Throwing a Kairo error *out of Kairo* is not a roadmap item; it is excluded by the effect system. The conversion is a translation at the boundary, not a change to how Kairo signals failure. ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [Allocators & Ownership](/docs/language/c-cpp-memory/) - [ABI Contract & Verification](/docs/language/c-cpp-abi/) - [Panic](/docs/language/panic/) - [Attributes](/docs/language/attributes/) --- ## Using Kairo in C++ URL: https://www.kairolang.org/docs/language/c-cpp-exposing/ # Using Kairo in C++ ## Exposing Kairo to C++ Use the **`kcc`** driver, which makes `#include "file.k"` work transparently in C++ translation units. `#include "file.k"` works only in a C++ source file compiled by `kcc`. A header that Kairo itself imports with `ffi import` (or any header it includes) cannot include a `.k` file: the include is skipped with error R070 and the rest of the header is still imported, so the header must declare what it needs itself. ```kairo // my_code.k pub fn my_kairo_function(x: i32) { io::println(f"Hello from Kairo! x = {x}") } pub class MyKairoClass { pub var name: string pub fn MyKairoClass(self, name: string) { self.name = name } pub fn get_name(self) -> string { return self.name } } ``` ```cpp // main.cpp #include "my_code.k" #include int main() { // A Kairo string is ::builtin::string::string; it is built from // `const unsigned char*`, not from a C++ string literal directly. ::builtin::string::string name((const unsigned char*)"C++"); my_code::MyKairoClass obj(name); std::cout << "name = " << obj.get_name().c_str() << std::endl; my_code::my_kairo_function(42); return 0; } ``` ```sh kcc main.cpp -o main ./main ``` ``` name = C++ Hello from Kairo! x = 42 ``` `my_code.k` is not on the command line: `kcc` finds it in `main.cpp`, builds it and links it. Its declarations are in its [module namespace](/docs/language/modules/#module-paths-are-c-namespaces), `my_code`, as they are for a Kairo importer. That namespace is the file's path under the [search directory](/docs/language/modules/#search-directories-and-library-names) that holds it, the same as for a file named on the command line: run from the project root, a `src/my_code.k` would be `src::my_code`, unless `-I src` makes `src` a search directory of its own. ### When a module's name is taken in C++ The first part of a module's namespace sits at C++ global scope. When that name is already something else there, Kairo renames the namespace by one fixed rule: it appends `_`, and keeps appending while the name is still taken. Your Kairo code is unaffected (it still says `main::x` or `import malloc`); only the C++ spelling changes. A name is taken when it is: - a program entry point: `main`, `wmain`, `WinMain`, `wWinMain`, `DllMain` or `_start`; - declared at global scope, as anything but a namespace, by a C or C++ header the build includes (`malloc`, `free` and `exit` come from ``, which the runtime always includes); - another module's own top-level name in the same build. | Kairo module | C++ namespace | |---|---| | `main.k` | `main_` | | `main/x.k` (`main::x`) | `main_::x` | | `malloc.k` | `malloc_` | | `exit.k` | `exit_` | | `abort.k`, when a header also declares `::abort_` | `abort__` | | `printf.k`, when no included header declares `::printf` | `printf` | A C++ file calls such a module through the renamed namespace: ```cpp #include "malloc.k" #include int main() { void* p = ::malloc(16); // the C function int r = malloc_::helper(); // Kairo's malloc.k ::free(p); return r; } ``` The decision is made once per build, from the headers that build includes, so every object and header of the build agrees on it. A module name that only *your* C++ file's headers declare (and no header of the Kairo build) is not renamed; pick another file name for it. Link errors name the C++ symbol (`malloc_::helper()`); Kairo's own diagnostics name the module as you wrote it. ### What crosses an include An included `.k` gives C++ the same interface a Kairo importer sees: - Its `pub` declarations, and its `prot` ones when the C++ file is in the same [module](/docs/language/modules/#visibility-scopes) (under the same nearest `module.k`). A `priv` or `internal` top-level declaration is left out, and so is a `prot` one for a C++ file outside the module, unless a visible `inline` or generic body names it (that body is compiled by the C++ code, so it must see what it calls). C++ has no way to keep a declaration from the rest of its translation unit, so that is the only one that crosses. An unmarked declaration counts as what its default makes it: `priv`, or `prot` under a `module.k`. - Every class member at its own visibility: a `priv` member is `private:`, a `prot` one `protected:` (`public:` when the class's file is in a module, since C++ cannot say "this module"; such a member is then reachable from any C++ file that sees the class), a `pub` one `public:`. An unmarked member that is `priv` by default is `private:` too, except an operator, which stays public so C++ templates that test for it (`a == b`, the panic helpers' `op panic`) see what Kairo sees. Kairo's `priv` reaches every function of the class's file, which C++ says by making the class befriend that file's functions and types, so the module's own `inline` and generic functions still work when the C++ code compiles them. The C++ code itself cannot read a `priv` field or call a `priv` method. Some members are public in C++ whatever their Kairo visibility: copy and move constructors and destructors (so C++ containers can hold the type), and the fields of a struct, of a union, and of a class with no constructor (these are plain aggregates, built with designated initializers, and a struct keeps the C layout and calling convention). Every base is a public base; a `derives priv` (or `prot`) base's members are private (protected) through the derived class, through using-declarations. - The bodies of templates and `inline` functions; every other body stays in the `.k`'s object. - Its types' dependencies, from other modules and from the builtin library, declared once per translation unit however many `.k` files include them. How `kcc` processes `#include "file.k"`, separate compilation, and the manual workflow without `kcc` are covered in [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/#how-kcc-works). --- ## Using Kairo from C++ ### Headers Every module can emit a C++ header, the files given on the command line included; only a file outside every search directory and every library has none. `--emit-headers

` writes one per module at a path mirroring the [module path](/docs/language/modules/#module-paths-are-c-namespaces): `geo::vec` becomes `/geo/vec.hh`. A C++ file includes it the way Kairo would import it: ```cpp #include "geo/vec.hh" // Kairo: import geo::vec ``` A header contains the module's [`pub` declarations](/docs/language/modules/#visibility-on-top-level-declarations) in their canonical namespaces (a header has no including file to check, so it never carries `prot` ones), declarations only: class layouts, function signatures, enum definitions. Function bodies are in the module's object file; you compile the module with Kairo and link the result. A header `#include`s the headers of modules its layouts depend on and forward-declares everything else, so including one module does not drag in the tree. A module that defines nothing (only comments, or only [`pub import` re-exports](/docs/language/imports/#re-export-pattern)) produces no object file and no header. C++ code that would include the header of a re-export-only module includes the headers of the modules it re-exports instead. ### What a Kairo declaration looks like in C++ | Kairo | C++ | |---|---| | `pub struct Vec2 { ... }` in `geo/vec.k` | `geo::vec::Vec2` | | `pub fn dot(a: Vec2, b: Vec2) -> f64` | `double geo::vec::dot(Vec2, Vec2)` | | `pub class Box { ... }` | `template class geo::vec::Box` | | `enum Dir derives u8 { N, S }` | `enum class Dir : std::uint8_t { N, S }` | | `fn m(self)` inside a class | member function | | `fn m(self)` inside `extend Vec2 { }` | static function `m(Vec2* self)` of the companion struct `geo::vec::__kairo_ext_Vec2` | | `x: i32`, `x: f64`, `x: usize` | `std::int32_t`, `double`, `std::size_t` | | `p: *T` | `T*` | | `x: T?` | `::builtin::Nullable` (see [Nullables Across the Boundary](#nullables-across-the-boundary)) | | `null` | `::builtin::null` | | `@inout x: T`, `@move x: T` | `T&`, `T&&` | | `type Name = T` inside a class | `using Name = T;` member, under the same access level | | `@no_unwind fn f()` | `void f() noexcept` | | `f: fn(i32) -> i32` | `::__kairo_fn`, a function or closure value | | `f: unsafe fn(i32) -> i32` | `std::int32_t (*)(std::int32_t)`, a plain function pointer | | `ffi "c" fn apply(f: fn(i32) -> i32, x: i32) -> i32` | `extern "C" std::int32_t apply(std::int32_t (*f)(std::int32_t), std::int32_t x)` | An `ffi "c"` function's `fn` parameters and result are raw function pointers whether or not they are written `unsafe fn`, because C passes and expects a plain function pointer. A Kairo caller can pass a named function or a closure that captures nothing; passing a capturing closure is a compile error. Extension methods are not C++ member functions. Kairo keeps a class's C++ definition identical everywhere it appears, so a method added by [`extend`](/docs/language/extends/), even in the same file, is a static function of a companion struct emitted beside the type, taking the receiver as its first parameter: `geo::vec::__kairo_ext_Vec2::len(&v)`. When the `extend` is in the type's own file, the type befriends the companion, so extension members reach `priv` members in C++ as they do in Kairo. An `extend` in another file puts its companion in that file's namespace, and the type does not befriend it. An operator added by `extend` is also a free C++ operator that forwards to the companion, so C++ code writes `a + b`. Member [type aliases](/docs/language/type-aliases/) are visible to C++: a class's `type promise_type = ...` is the C++ member `promise_type`, so C++ code that looks a member type up by name finds it. Names beginning `__kairo_` are reserved. A rendered class may expose public `__kairo_` members; C++ code must not read or write them. ### Allocation from C++ Every Kairo class, struct and ADT enum in C++-facing output carries class-scope `operator new` / `operator delete` (and the array, aligned, `nothrow` and placement forms) that use Kairo's allocator. `new MyKairoType()` and `delete p` in C++ therefore pair correctly with `@create` and `@destroy` on the Kairo side, and a C++ global `operator new` override never reaches a Kairo object. See [Allocators & Ownership](/docs/language/c-cpp-memory/#class-specific-operator-new-and-operator-delete). ### Generics Kairo [generics](/docs/language/generics/) are C++ templates in the header, bodies included. Instances Kairo already compiled are listed as `extern template`, so linking against the module's objects reuses them; any other instance is instantiated by your C++ compiler like any template. An `#include "file.k"` lists none: the C++ side instantiates every instance it uses, and the linker keeps one copy. A Kairo `impl` bound on a generic function or method is a C++ constraint: each interface is emitted as a C++ concept (`Shape` is `Shape_c`, in the interface's namespace), and the template carries `requires(Shape_c)`, so a C++ call with a type that does not satisfy the bound is rejected at the call. A bound on a generic class is not part of the class template's head, since C++ would check it where the class names itself while still incomplete. Instead each of its constructors asserts the bound, so making one with a type that does not implement the interface is a compile error naming the bound (`'Holder' requires 'T' to implement 'Named'`). A struct with no constructor of its own is not checked. ### Constructing enum variants from C++ An [ADT enum](/docs/language/enums-adt/) is a class in C++, and each of its variants has a static factory function named exactly after the variant: ```kairo // packet.k pub enum Frame { Burst { base: T, count: i32 }, Code { status: i32 }, Idle, } ``` ```cpp #include "packet.k" packet::Frame a = packet::Frame::Burst(20, 4); packet::Frame b = packet::Frame::Code(404); packet::Frame c = packet::Frame::Idle(); ``` - The parameters are the variant's fields, in declaration order and with the fields' names. A variant without a payload has a factory that takes no arguments: write `Frame::Idle()`, with the parentheses. - The factories exist in the C++ view only (a header from `--emit-headers` or an `#include "file.k"`). They are inline, so an unused one costs nothing, and they work at every instance of a generic enum. - Each factory is a member template with a defaulted parameter, so a call reads like an ordinary static function. Taking its address needs empty angle brackets: `&Frame::Burst<>`. - If the variant's name is already taken in the C++ class, the factory gets a `_` appended, repeated until the name is free. A name is taken when it is the enum's own name (that name belongs to the constructors), one of its type parameters, or a member the compiler gives the class. Variants whose own names are free keep them, so in `enum Node { Node { v: i32 }, Node_ { v: i32 } }` the factories are `Node::Node__` and `Node::Node_`. - No factory is generated for a pack-expanded variant of a [variadic enum](/docs/language/enums-adt/#variadic-enums), for a variant with a fixed-size array field, or for the panic result type. [Plain enums](/docs/language/enums-plain/) need no factories: a variant is already the C++ enumerator `Dir::N`. --- ## Tuples Across the Boundary Kairo [tuples](/docs/language/collections/#tuples-t1-t2-) such as `(i32, f32)` are emitted as the struct template `::builtin::TupleN` (`::builtin::Tuple2`), one instance per distinct element-type list. Field order is source order: the fields are `_0`, `_1`, ..., and `.0` lowers to a plain member access. This makes tuples first-class across the boundary: a C++ TU can name the type, take a reference to it, return it, and specialize on it. The type is a **structural** function of its element types, not an ordinal. Two translation units that use `(i32, f32)` produce the same type and the same symbol, regardless of declaration order or which other tuple shapes appear in each TU. This is required for linking and is a departure from C++'s anonymous-type mangling, which is deliberately TU-local. > [!NOTE] > The exact structural encoding is part of the ABI and is specified separately. It is injective across all type constructors that can appear in a tuple, and unambiguous under nesting. --- ## Nullables Across the Boundary A Kairo [nullable](/docs/language/nullables/) `T?` is the C++ class template `::builtin::Nullable`, and Kairo's `null` is the constant `::builtin::null`, the one value of the empty type `::builtin::null_t`. `Nullable` has two constructors, one from `null_t` and one from `T`, so C++ code builds one the same way Kairo's implicit conversions do: ```cpp ::builtin::Nullable a = ::builtin::null; // Kairo: var a: i32? = null ::builtin::Nullable b = 5; // Kairo: var b: i32? = 5 ``` The layout depends on `T`: | Kairo | Storage | |---|---| | `*T?` (any safe pointer, `const` included) | the pointer alone, `sizeof(T*)`; null is `0x0` | | a closed [enum](/docs/language/enums-plain/#closed-and-open-enums) `E?` | the enum alone, `sizeof(E)`; null is a value `E` does not declare | | `bool?` | two bytes, the `bool` and a presence flag; one byte, with `0x02` as null, is planned ([Status](/docs/status/#not-compiled-yet)) | | any other `T?` | the `T` and a presence flag | `(T?)?` is `Nullable>`. --- ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Allocators & Ownership](/docs/language/c-cpp-memory/) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [ABI Contract & Verification](/docs/language/c-cpp-abi/) - [Modules](/docs/language/modules/) - [Generics](/docs/language/generics/) --- ## Allocators & Ownership URL: https://www.kairolang.org/docs/language/c-cpp-memory/ # Allocators & Ownership ## Allocators and Ownership Heap ownership crosses the boundary in both directions, using the mechanism C++ already has for exactly this purpose. ### Class-specific `operator new` and `operator delete` In C++-facing output (an `--emit-headers` `.hh`, or the interface `kcc` produces for `#include "x.k"`), every Kairo class, struct and ADT enum carries class-scope allocation functions bound to Kairo's [global allocator](/docs/language/allocators/#global-allocator). The compiler defines them; Kairo code cannot define or overload them. A Kairo type defines only its constructors and its destructor ([`op finally`](/docs/language/operator-overloading/#finally-operator), which is the C++ destructor, not an allocation function). The module's own object has none: Kairo code frees with `@destroy`, which calls the allocator itself. ```cpp class MyKairoClass { public: static void *operator new(size_t); static void operator delete(void *, size_t); static void *operator new[](size_t); static void operator delete[](void *, size_t); ~MyKairoClass(); // plus the aligned (std::align_val_t), std::nothrow_t and placement forms }; ``` So from C++, the ordinary spelling is the correct one, and it goes through Kairo's allocator, not C++'s: ```cpp MyKairoClass *p = new MyKairoClass("hi"); delete p; // runs Kairo's destructor, then returns memory to Kairo's global allocator ``` This works because Kairo emits the class, and therefore emits the [destructor](/docs/language/classes-lifecycle/#destructors---op-finally). `~MyKairoClass` performs Kairo's destruction semantics; C++'s `delete` sequences destructor-then-deallocate, which is the same pair of operations Kairo spells as [`@destroy p`](/docs/language/classes-lifecycle/#freeing-memory). A block `@create` made may be freed by a C++ `delete`, and a block C++ `new` made may be freed by `@destroy`. The throwing `operator new` forms never return null and never throw: when memory runs out the program stops with `kairo: out of memory` (exit 134), as Kairo's own default out-of-memory hook does. The `std::nothrow_t` forms return null. One limit: a polymorphic type's deleting destructor lives in the module's own object, so a C++ `delete` through a base pointer with a virtual destructor frees with the global `::operator delete`. Pointer parameters and return values stay raw `*T`. There is no wrapper type, no ABI change, and no cost at the call boundary. ### Global `operator new` overrides do not affect Kairo objects A class-specific `operator new` takes precedence over a global replacement. A C++ translation unit that overrides global `new`/`delete` (for a pool, an instrumented heap, a leak tracker) therefore does not touch Kairo allocations. The isolation is structural, not a restriction. ### The operators bind to the *global* allocator, always Kairo's [scoped allocator](/docs/language/allocators/#scoped-allocator) mechanism (`@mem::set_scoped_allocator` is not available yet) works by swapping the allocator the process is currently using. The emitted `operator new` and `operator delete` deliberately **bypass** that indirection and address the global allocator directly. This matters. Consider a C++ `delete` that happens while a Kairo scoped allocator is active: ```kairo @mem::set_scoped_allocator(ArenaAllocator) fn work() { call_into_cxx() // C++ runs `delete p` on a globally-allocated Kairo object } ``` If `operator delete` followed the ambient allocator, that object would be handed to the arena's deallocator instead of the global one. Binding to the global allocator unconditionally makes the pairing correct regardless of what is active at the call site. The invariant that makes this sound: **objects reachable from C++ were allocated by the global allocator.** A pointer allocated through a scoped allocator that escapes the allocator's scope is a hard error under [Tether](/docs/language/tether/), so a scoped-allocated object cannot reach a C++ `delete` in the first place. ### Memory that belongs to C++: `@cxx::new` and `@cxx::delete` `@create` and `@destroy` use Kairo's allocator. Memory that crosses into or comes from C++ code and must follow C++'s own allocation (a type a C++ library allocates and frees itself, a pointer a C++ API takes ownership of) uses the `@cxx::` forms, which lower to plain C++ expressions: | Kairo | C++ it becomes | Result | |---|---|---| | `@cxx::new T(args)` | `new T(args)` | `unsafe *T` | | `@cxx::new [T; n]` | `new T[n]` | `unsafe *T` | | `@cxx::delete p` | `delete p` | | | `@cxx::delete [] p` | `delete[] p` | | ```kairo var p = @cxx::new Widget(4) // C++ new (Widget is a class from a C++ header): unsafe *Widget hand_to_cxx_owner(p) @cxx::delete p // C++ delete, for memory C++ gave back ``` Pair them: `@cxx::new` memory is freed with `@cxx::delete`, never `@destroy`, and `@create` memory with `@destroy`, never `@cxx::delete`. The `@cxx::` forms are for C++ types: a Kairo record's heap storage is `@create` / `@destroy` on the Kairo side and C++'s `new` / `delete` on the C++ side (a `@cxx::new` of a Kairo record does not yet pair with a C++ `delete` of it). ### What is still an error Kairo's own pairing rules and the allocation operators above make `new` / `delete` across the boundary valid. They do not make every deallocation valid: - `free()` on a pointer from [`@create`](/docs/language/pointers/#heap-allocation): wrong deallocator, no destructor. - `@destroy` or `@cxx::delete` on a pointer from `@alloc`: `@alloc` returns untyped storage with no constructed object. - `delete` on an object allocated by a C++ `operator new` override in a TU that predates the Kairo declaration. These are what the [ownership annotations](#ownership-annotations-in-generated-headers) below are for. ### `CxxNewAllocator` For code that wants Kairo's *own* allocations to follow C++'s allocation path, so that a global `operator new` override does apply to them, `core` is to provide `CxxNewAllocator`. Not yet: it does not exist. `core::CxxNewAllocator` is an unknown name today (R021E); only a stub sits in a draft file of the standard library. ```kairo @set_global_allocator(core::CxxNewAllocator) ``` This will be the unusual case, not the default. A global allocator that does exist is a class with the static allocator functions of `builtin::base::alloc` (`alloc`, `free`, `resize`, `realloc`, `alloc_zeroed`). `@set_global_allocator` with such a class works and routes `create` and `destroy` (the functions behind `@create` and `@destroy`) through it. Like any [global allocator](/docs/language/allocators/#global-allocator) it is chosen once per program: one file sets it, and every file and library linked in follows. ### Ownership annotations in generated headers > [!NOTE] > Not yet: no emitted declaration carries these attributes today, and the `kairo_alloc` / `kairo_free` functions below are the intended shape, not names that exist. The same holds for the lifetime annotations further down. Declarations emitted for the C++ side are to carry Clang's ownership attributes, tagged with the Kairo allocator identity: ```cpp void *kairo_alloc(size_t) __attribute__((ownership_returns(kairo_global))); void kairo_free(void *) __attribute__((ownership_takes(kairo_global, 1))); ``` Clang's static analyzer (`MallocChecker`) uses these to flag mismatched allocation and deallocation across the boundary. Because `kcc` controls the compiler invocation, this checking is available as a driver flag rather than requiring a separate `scan-build` step. > [!NOTE] > The allocator identity string is part of the interop contract and is pinned in the ABI specification. Both sides must agree on it. Kairo's own semantic analysis enforces the same rule independently and produces a Kairo-quality diagnostic. The Clang attributes exist so that C++ consumers benefit too. ### Lifetime annotations Emitted declarations are to carry `[[clang::lifetimebound]]` and the `[[gsl::Owner]]` / `[[gsl::Pointer]]` pair where the Kairo side can prove the relationship. Unlike the ownership attributes, these are diagnosed during ordinary compilation via `-Wdangling`, so a lifetime relationship proven on the Kairo side becomes a real compile-time warning on the C++ side. ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [ABI Contract & Verification](/docs/language/c-cpp-abi/) - [Tether](/docs/language/tether/) - [Ownership](/docs/language/ownership/) --- ## kairo, kcc & Cross-compilation URL: https://www.kairolang.org/docs/language/c-cpp-toolchain/ # kairo, kcc & Cross-compilation ## The Toolchain Model Kairo ships two drivers, `kairo` and `kcc`, written in Kairo (the compiler compiles itself). Both embed the **same pinned Clang** (an LLVM 22 fork). Neither invokes a system compiler. A release archive holds `bin/` (`kairo`, `kcc`, `kld`, `kfmt`, `ksys`, `llvm-symbolizer`, `llvm-ar`, `llvm-ranlib`, `llvm-lib`) and `lib/` (including `lib/clang/22`). There are no `clang` or `clang++` binaries: `kairo` and `kcc` run clang in-process and `kld` runs lld in-process. The `lib/` tree holds Clang's resource directory with compiler-rt, and the builtin, std and runtime sources). Archives exist for static musl Linux (x86_64, i686, aarch64, armv7, riscv64), Windows (MinGW; x86_64, i686, aarch64, armv7), FreeBSD (x86_64, aarch64), NetBSD (x86_64) and macOS (x86_64 10.15+, arm64 11+). Only x86_64 Linux is run by the test suite. `/sysroot` holds the host's own prebuilt sysroots; every other target's is built on first use by [ksys](/docs/toolchain/ksys/) from `/share/kairo/sysroot` and cached. ### `kairo`: the Kairo compiler ```sh kairo foo.k # links ./a.out kairo foo.k -o foo # names the output ``` When `foo.k` contains [`ffi "c++" import "header.h"`](/docs/language/imports/#ffi-header-imports), `kairo` runs the pinned Clang's frontend over `header.h` to extract declarations. At the interop boundary, Kairo hands **that same Clang instance** a token stream containing exactly what it would emit if you requested a C++ header for `foo.k`. The compiler that read the header and the compiler that consumes Kairo's declarations are byte-identical, so there is no version skew to reconcile. ### `kcc`: the C++ driver `kcc` is a drop-in replacement for `clang++`, with two additions: - `#include "foo.k"` works. A Kairo file can be included directly into a C++ translation unit. - Optionally, the Kairo standard library can be used in place of the C++ standard library, via a separate header. This is opt-in and off by default. It takes Clang's command line: C, C++, Objective-C(++), `.k`, object and archive inputs, and Clang's options. An option Kairo has its own flag for becomes that flag; any other reaches the C and C++ compiles as given. A few things differ from `clang++`: - **C++23 by default.** With no `-std=`, C++ is compiled as C++23. A lower `-std=` is accepted, down to C++20 for a translation unit that includes a `.k`: the emitted interface needs `constexpr`, `consteval`, `constinit` and `requires`. - **The target and sysroot are Kairo's.** `kcc` is part of the toolchain, so the defaults come from it, not from the host compiler (see [Cross-compilation](#cross-compilation)). - **`-Xkairo `** passes one word to the Kairo side untranslated, for settings only `kairo` has (`-Xkairo --cxx-std=c++26`). - `kcc --help` and `kcc --version` describe `kcc`, not Clang. `-###` prints each compile job and the link without running them. `kcc` is the supported way to compile C++ in a Kairo project. Using the system `clang++` or `g++` will usually work, but forfeits the link-time ABI verification described [below](/docs/language/c-cpp-abi/#link-time-abi-verification). ### Why a pinned Clang The Clang version is identical across Kairo releases and identical across the language boundary. This is the consistency guarantee the whole interop story rests on: - The header you `ffi` in and the object you link against were processed by the same frontend. - A Kairo type's layout and a C++ type's layout are computed by the same code. - ABI-affecting behavior does not drift between the two sides of a call. The trade-off is that Kairo does not use whatever compiler is installed on the machine. That is deliberate. The same applies to the C++ standard library. A program that uses libc++ must link against the toolchain's own libc++, not a copy installed on the system. ### Cross-compilation Both `kairo` and `kcc` are full native cross-compilers. Targets are selected by triple, and system libraries come from **sysroots** that `--target` generates on demand (and caches) rather than from the host machine. Two are never shipped or generated: Apple's SDK and Microsoft's MSVC / Windows SDK. On macOS the installed SDK is used (`xcrun --show-sdk-path`), on Windows the installed MSVC / Windows SDK, and cross-compiling to either from another host needs an SDK you supply with `--sysroot`. A `--target` build is hermetic; a build without one also searches the host's system directories, after the sysroot (see [Host headers and libraries](#host-headers-and-libraries)): ```sh kcc --target=x86_64-pc-windows-msvc foo.cc kairo --target=aarch64-unknown-linux-gnu foo.k ``` Sysroots are pinned to specific library versions (a particular glibc, a particular Windows SDK), so a build is reproducible across machines. A sysroot of your own can be given with `--sysroot=` (without `--target`); its `SYSROOT.toml` describes the layout. How `--target` finds its sysroot: - A `--target` uses the sysroot for it, looked up in order: `/sysroot/` beside the compiler (`` is the directory above the one holding `kairo`), then the [ksys](/docs/toolchain/ksys/) cache, then a build by `ksys` from the shipped input tree (first use only; `--no-sysroot-build` refuses it with `P009E`). - The folder is matched by target, not by spelling. Vendor, OS version, and LLVM's aliases do not matter, but the sub-architecture does. So `x86_64-pc-windows-msvc` finds `x86_64-windows-msvc`, `x86_64-linux-gnu` finds `x86_64-linux-gnu-glibc2.31`, `aarch64-apple-darwin` finds `arm64-apple-macosx`, and `arm64e` does not match `arm64`. - `-m32` / `-m64` look up the architecture they switch to: `--target=x86_64-linux-musl -m32` uses `i686-linux-musl`. - A bundled sysroot takes precedence over `--sysroot`, unless `--sysroot-exact` is given: then `--sysroot` is used exactly as written and no bundled or cached sysroot is substituted. With no matching folder, `--sysroot` is used if given; otherwise the compiler warns ([P008W](/docs/language/diagnostics/)) and there are no system headers. - A matching folder without a loadable `SYSROOT.toml` is an error: [P007E](/docs/language/diagnostics/#p007e-bundled-sysroot-for-the-target-is-malformed) "bundled sysroot for the target is malformed". ### Host headers and libraries A build sees the machine it runs on in one of three ways, decided by the flags: | Mode | Flags | C library | Host headers and libraries | |---|---|---|---| | Default | no `--target`, no `--sysroot` | The bundled sysroot for this host (glibc 2.31 on a glibc Linux host, musl on a musl host) | Searched **after** the sysroot | | Native | `--native` | The host's own | Searched as clang does natively | | Hermetic | `--target=` (or `--sysroot`) | The bundled sysroot for the triple | Never | **Default.** On a glibc Linux host a plain `kairo main.k` builds for `-unknown-linux-gnu` against the bundled glibc 2.31 sysroot, the *glibc floor*. The program then runs on any Linux with glibc 2.31 or newer. On top of the floor, the host's system directories are searched last: - Headers: the bundled libc++, then Clang's builtin headers, then the floor's glibc headers, and only then the host's `/usr/local/include`, `/usr/include/` and `/usr/include` (as `-idirafter`). `` always comes from the floor. Only a header the floor lacks, such as `zlib.h` or `curl/curl.h`, comes from the host. - Libraries: the sysroot's library directory, then the host's `/usr/local/lib`, `/usr/lib/`, `/usr/lib64`, `/usr/lib`, `/lib/`, `/lib64` and `/lib`. `libc` and `libm` always come from the floor. So installed C libraries work without extra flags beyond naming them: ```kairo ffi "c" import "curl/curl.h" fn main() -> i32 { var unsafe *v = curl_version() return 0 } ``` ```sh kairo main.k --pkg-config libcurl -o main ``` `kairo --print-clang-args main.k` shows the header search order, and `kairo --print-dirs main.k` the library search order (the host's directories are listed under `host library search`). **What raises the floor.** A host library was built against the host's glibc, which is usually newer than 2.31. Linking one can make the program need that newer glibc: - A host **shared** library is linked with `--allow-shlib-undefined`, because the floor's `libc.so` lacks the newer symbol versions it uses. After the link, Kairo reads the library's version needs and warns when one is above the floor: `warning [L001W]: 'libcurl.so.4' needs GLIBC_2.43, so this program needs glibc 2.43 or newer to run (the floor is 2.31)`. The program runs on this machine. To run it on an older one, ship it with that library (or one built against an older glibc). - A host **static** archive (`.a`) from a host directory gets a warning too: once it is linked in, nothing can see what it needs from glibc, so it can raise the floor silently. The floor is Linux-only. On macOS and Windows the default build uses the bundled SDK or MinGW-w64 sysroot as before. **Native: `--native`.** Builds against the host's own C library, headers and libraries, in Clang's normal native search order, like Zig's native mode. There is no sysroot. The bundled libc++, libunwind and compiler-rt are still used (linked by path, so the host's `libc` is the one linked). The program needs the host's glibc version, with no floor. `--native` cannot be combined with `--target`: one names this machine, the other a triple built hermetically. `--native` is implemented for Linux hosts so far. **Hermetic: `--target`.** A `--target` build uses the bundled sysroot only. No host directory and no host environment search path is ever consulted, so a cross build gives the same result on every machine. Naming a root with `--sysroot`, or building `--freestanding`, is hermetic too. #### `--pkg-config` `--pkg-config ` (repeatable) runs `pkg-config --cflags --libs ` and applies the result: - `-I`, `-isystem`, `-D` and `-U` go to Clang, for `ffi` headers and C/C++ inputs. - `-L`, `-l`, `-pthread` and `-Wl,...` go to the link. - A `-I` or `-L` naming a host system directory is dropped, because those are already searched after the sysroot. As a `-I` it would come before the sysroot, and `-I/usr/include` ahead of libc++ breaks ``. pkg-config reads `PKG_CONFIG_PATH`, `PKG_CONFIG_LIBDIR` and `PKG_CONFIG_SYSROOT_DIR` itself, and `PKG_CONFIG` names a different program. A missing pkg-config, or a package it does not know, is an error naming the package. With `--target`, `--pkg-config` is an error unless `PKG_CONFIG_SYSROOT_DIR` or `PKG_CONFIG_LIBDIR` is set, because the host's `.pc` files describe the host, not the target. #### Environment variables In the default and native modes, Kairo honors the variables Clang's driver reads, in the same positions: | Variable | Effect | |---|---| | `CPATH` | Like `-I`, after the command line's own `-I` | | `C_INCLUDE_PATH`, `CPLUS_INCLUDE_PATH` | System include directories for C and C++, searched after the sysroot's headers | | `LIBRARY_PATH` | Library directories, after the sysroot's and before the host's defaults | | `NIX_CFLAGS_COMPILE`, `NIX_LDFLAGS` | Their `-isystem` / `-idirafter`, `-L` and `-rpath` words, as on Nix | A `--target` build ignores all of them. #### C++ libraries from the host Kairo links its own libc++. A host C++ library built against GCC's libstdc++ is not ABI-compatible with it wherever `std::` types cross the boundary (`std::string`, containers, exceptions). Host C libraries are fine. For a C++ library, build it with the toolchain (`kcc`) or use its C API. > [!NOTE] > Cross-compiling to a GCC or MSVC target does not mean invoking GCC or MSVC. `kairo` and `kcc` produce object code for those platforms' ABIs directly, using the pinned Clang and the curated sysroot. ### How `kcc` works `kcc` is the pinned Clang driver with a preprocessor hook that intercepts `#include` directives. When the included file has a `.k` extension: 1. **Before anything compiles,** `kcc` scans each C++ input, and the project headers it includes, for `#include "*.k"`, resolving each the way Clang will (the including file's directory, then `-iquote`, then `-I`). An `-I` directory is also a Kairo [search directory](/docs/language/modules/#search-directories-and-library-names), so a `.k` found through it has the same module path as when it is imported. Every `.k` found is part of the build whether or not the command line names it. The scan does not preprocess: a `.k` behind `#if 0` is still built, and an include spelled through a macro is not found (it is an error at the include). 2. **The Kairo compiler analyses the `.k` in the same process** and, at the include, hands Clang a token stream: the file's [`pub` interface](/docs/language/c-cpp-exposing/#what-crosses-an-include) in its [module namespace](/docs/language/modules/#module-paths-are-c-namespaces), plus every template and `inline` body the C++ code compiles itself. No header file is written, and the system and `ffi` headers the interface needs are included ahead of it. Diagnostics in the C++ code point into the `.k`. 3. **In a run that links,** the `.k` is compiled to an object and linked with the C++ objects. Under `-c` it is a header to that run, and gets no object of its own (see [Separate compilation](#separate-compilation)). A `.k` included twice in one translation unit is included once, and two `.k` files that share a module (or the builtin library) share one copy of it. `-E` prints the stream as C++ that compiles on its own. A `.cc` and a `.k` with the same name write `foo.o` and `foo.k.o`. ### Separate compilation `kcc` compiles one file at a time the way Clang does: ```sh kcc -c x.cc # x.cc includes y.k: y.k is analysed for the include, no y.o kcc -c y.k # writes y.o, and nothing for what y.k imports kcc x.o y.o -o main ``` `-c` writes objects only for the files the command line names. What they import is compiled by its own `kcc -c`, as a C++ source would be. The final link needs Kairo's builtin library, the standard library and the runtime, which no `-c` run wrote: `kcc` links them from the toolchain's library, built on first use for the target and code-generation options and cached under `$KAIRO_CACHE_DIR` (default `$XDG_CACHE_HOME/kairo`, then `~/.cache/kairo`, then `%LOCALAPPDATA%\kairo`). It is rebuilt when the compiler or a library source changes, and a library no link has used for 30 days is removed. It is linked like an archive, so only what the objects use is pulled in. Every link, with `kcc` or `kairo`, also caches the runtime's C objects (the allocator and the runtime support code) in the same directory, under `rt/`. An object is reused only when its exact compile line (target, optimization level, sanitizers and every other flag that reaches it) and every runtime source it is built from, the compiler itself included, are unchanged; anything else rebuilds it. `--force-recompile` rebuilds them for one run, and `-v` reports a hit or miss for each. A template instance used on both sides is instantiated by each, and the linker keeps one: the include carries no `extern template`, because the C++ object and the Kairo object may come from different runs. ### Incremental compilation With `--cache-dir ` (`-Xkairo --cache-dir=` through `kcc`), `kairo` reuses the object of every Kairo file whose compiled form has not changed since an earlier run against the same directory. Without it nothing is cached and every run is a full build. ```sh kairo main.k -o main --cache-dir build/cache # first run: every file compiled kairo main.k -o main --cache-dir build/cache # no change: every object reused ``` The unit is one file. Every run still parses and type-checks the whole program; a reused file skips code generation and the C++ compile behind it, which is most of a build. A file's object is keyed by what its compile would be given, worked out after type checking: - Editing the body of an ordinary function recompiles only its own file. - Changing something an importer compiles against recompiles the file and the importers that use it: a signature, a default argument, a generic or `inline` body, a class's layout (private fields included), or a fact the compiler inferred from a body, such as a function's purity. A declaration no importer uses recompiles nobody else. - Editing a C or C++ header the program imports recompiles every Kairo file of the program. - Anything that changes objects recompiles everything: another compiler build, another target, or an option that reaches code generation (`-O`, `-g`, `-D`, `-f` flags, sanitizers). `-A`, a Kairo-only `-W`, `--error-format` and link options (`-l`, `-L`, `--rpath`, `--static`) recompile nothing. For now a `-W` that reaches Clang (`-Wall`, say) recompiles everything too, because a reused object must report the same C++ warnings and those are not stored yet. A reused file still reports its warnings: type checking runs every time, and the compiler's own code-generation warnings are produced again. A file Clang warns about is never stored, so it is compiled, and warns, on every run. Each object carries its cache key in a section the linker drops (`.kairo.cache` on ELF, `__KAIRO,__cache` on Mach-O, `.kcache` on COFF), so the linked program is byte-identical to a clean build's. Without `-g` the key holds no path of the machine, so a cache directory can be copied to another checkout or machine and is used wherever the keys match. An object whose record is missing, damaged or names another key is never used: the file is compiled again and the entry replaced. Builds with different options or targets keep their objects side by side under `/kairo-cache-v/`. On a terminal, a build shows one status line, such as `[codegen 41/338, 297 reused] Sema/Type/CallTyping.k 0:09`, that disappears before any diagnostic prints. `--progress=never` turns it off; `--progress=lines` prints one `@progress phase=sema done=212 total=338 file=...` line per finished file instead, for a script to read. The default, `auto`, shows the line whenever stderr is a terminal (unless `TERM` is `dumb`), and never when output is piped or redirected. `--print-stats` prints each run's counts (`[stats] incremental: 41 reused, 2 compiled, 2 stored`), `-v` names each file that compiled and the part of its key that changed, and `--force-recompile` compiles every file for one run. ### Driver flags | Flag | Meaning | |---|---| | `--progress=auto\|always\|never\|lines` | the status line described above; `auto` (default) only on a terminal | | `--sema-threads=N` | threads that type-check import groups in parallel; 0 (default) follows `--threads`, 1 runs one at a time | | `--codegen-threads=N` | threads of the per-file C++ compiles; 0 (default) follows `--threads`, never more than the file count | | `--interface-pch=auto\|on\|off` | share one precompiled copy of the Kairo interfaces between files; `auto` (default) builds it only for larger programs | | `--cache-dir `, `--force-recompile` | [incremental compilation](#incremental-compilation) | | `-Wconst-self` | opt-in lint: a method that never mutates `self` should be declared `const self` (with a fix-it) | | `--help-hidden` | also list internal and not-yet-implemented flags | Pretty diagnostics print the location as `file:line:col`. ### Manual workflow (without `kcc`) If you prefer a standard C++ build process, compile the Kairo source to an object and write its C++ headers, then link normally. `--emit-headers ` writes one header per module (`gen/my_code.hh`, plus the builtin ones it includes); the C++ file includes `my_code.hh` instead of the `.k`. `--emit-scope=inputs` writes an object for `my_code.k` only, as `clang -c` does, not for every Kairo file the run reaches: ```sh kairo my_code.k -c --emit-scope=inputs -o my_code.o --emit-headers gen kcc -Igen main.cpp my_code.o -o main ``` The final link needs Kairo's builtin library and runtime, which `kcc` supplies. Using a third-party compiler for the link means linking those yourself, and gives up the checks described in [Link-time ABI verification](/docs/language/c-cpp-abi/#link-time-abi-verification). > [!TIP] > `kcc` is the simplest path for mixed codebases. The manual workflow is better when Kairo is a dependency consumed by an existing CMake/Meson/Bazel project that manages its own link step. --- ## Compiler Flags Across the Boundary Kairo's flags and Clang's flags are not the same set. `kcc` translates a Clang option into the Kairo flag when Kairo has one (`-O2`, `-g`, `-fno-exceptions`, `-fstack-protector-strong`, `--target`), and any other option reaches the C and C++ compiles as given, never the link. `-Xkairo ` and `--cxx-flags=` say which side a word is for. ```sh kcc main.cpp -fstack-protector-strong # -> --stack-protector=strong, for both sides kcc main.cpp -fno-strict-aliasing # no Kairo flag: C++ compile only kairo main.k --cxx-flags=-Wshadow # Clang flag for the C/C++ inputs and ffi headers only ``` > [!NOTE] > Not yet: a flag that exists on one side only is not rejected in a mixed translation unit, and neither are layout-affecting flags (`-fshort-enums`, struct packing). They are accepted and applied to the C/C++ side alone, so the two sides can silently disagree on a layout. Rejecting them with a diagnostic naming the flag and the include that made the unit mixed is planned. Until then, do not pass a layout-changing flag to a unit that touches Kairo types. `-fno-rtti` is a Kairo flag too (`-f[no-]rtti`), and `kcc` translates it. An unknown option is an error (`error: unknown argument: '--fno-float-prec'`), as in Clang. ### Exceptions C++ exceptions are on in a Kairo translation unit's C++ on a hosted target, and off on a freestanding one (no OS in the triple, `--freestanding`, kernel mode) unless `-fexceptions` is given; `-fno-exceptions` turns them off. Separately, `-funwind` / `-fno-unwind` (the default) decide whether Kairo functions are `noexcept`: see [Exceptions & Panics](/docs/language/c-cpp-exceptions/#c-exceptions-through-kairo-frames). Use one `-funwind` setting for every Kairo module and `kcc` host in a program. ### Hardening, symbol and code-model flags These use Clang's names. A toggle is `-f` / `-fno-`, and a setting with a value is `--=`. Each one applies to Kairo code and to the C/C++ compiled with it, and `kcc` translates the Clang spelling for you. | Kairo | Clang | Values | |---|---|---| | `--stack-protector=` | `-fstack-protector`, `-fstack-protector-strong`, `-fstack-protector-all` | `none`, `basic`, `strong`, `all` | | `-f[no-]stack-protector` | the same | shorthand for `basic` / `none`; `--stack-protector=` wins | | `--cf-protection=` | `-fcf-protection=` | `none`, `branch`, `return`, `full` (x86 CET) | | `--zero-call-used-regs=` | `-fzero-call-used-regs=` | `skip`, `used-gpr-arg`, `used-gpr`, `used-arg`, `used`, `all-gpr-arg`, `all-gpr`, `all-arg`, `all` | | `--trivial-auto-var-init=` | `-ftrivial-auto-var-init=` | `uninitialized`, `zero`, `pattern` | | `-f[no-]delete-null-pointer-checks` | the same | on by default | | `--tls-model=` | `-ftls-model=` | `global-dynamic`, `local-dynamic`, `initial-exec`, `local-exec` | | `--visibility=` | `-fvisibility=` | `default`, `hidden`, `protected` | | `-f[no-]visibility-inlines-hidden` | the same | off by default | | `-f[no-]plt` | the same | on by default | | `-f[no-]red-zone` | `-m[no-]red-zone` | on where the ABI has one | | `--mcmodel=` | `-mcmodel=` | `tiny`, `small`, `kernel`, `medium`, `large` | Without `--tls-model`, each `thread` global gets a TLS model of its own. Builtin and std globals are `initial-exec`. Your globals are `local-exec` when they link into an executable, and general-dynamic in a `--shared` library or a `-c` object. `--tls-model` sets the model for your globals; builtin and std globals stay `initial-exec`. ### No passthrough with `--` `kairo` has no raw Clang passthrough. After a bare `--`, every word is an input file, so `kairo main.k -- -ftls-model=initial-exec` is an error that names the Kairo spelling. To pass a Clang flag to the C and C++ inputs alone, use `--cxx-flags=` (repeatable). Kairo's own code never sees those flags. A `kcc` link with no Kairo code (no `.k` input, no `#include` of a `.k`, no Kairo object) is linked exactly as clang links it, without the Kairo runtime. ## See also - [C & C++ Interoperability](/docs/language/c-cpp/) - [Calling C and C++ from Kairo](/docs/language/c-cpp-calling/) - [Using Kairo in C++](/docs/language/c-cpp-exposing/) - [Allocators & Ownership](/docs/language/c-cpp-memory/) - [Exceptions & Panics](/docs/language/c-cpp-exceptions/) - [ABI Contract & Verification](/docs/language/c-cpp-abi/) - [Diagnostics](/docs/language/diagnostics/) - [Modules](/docs/language/modules/) --- ## Implicit Conversions URL: https://www.kairolang.org/docs/language/casting-implicit/ # Implicit Conversions Some conversions need no `as`. Explicit conversions are covered in [Casting](/docs/language/casting/). ## Widening [Integer and float widening](/docs/language/conversion-lattice/#2-the-rule-set) is implicit; no `as` required: ```kairo var a: i32 = 42 var b: i64 = a // implicit ``` `as` is permitted but redundant for widening conversions. ## Upcasting (derived to base) [Derived-to-base pointer conversion](/docs/language/classes-inheritance/#inheritance) is implicit; no `as` required: ```kairo class Animal { ... } class Dog derives Animal { ... } var dog = Dog("Rex", "Labrador") var animal: *Animal = &dog // implicit upcast ``` ## See also - [Casting](/docs/language/casting/) - [Conversion Lattice](/docs/language/conversion-lattice/) - [Type System](/docs/language/type-system/#implicit-conversions) - [Primitives](/docs/language/primitives/) - [Pointers](/docs/language/pointers/) - [Classes: Inheritance](/docs/language/classes-inheritance/) - [Implicit `op as`](/docs/language/operator-overloading/#implicit-op-as) --- ## Inheritance and Virtual Dispatch URL: https://www.kairolang.org/docs/language/classes-inheritance/ # Inheritance and Virtual Dispatch Classes inherit from other classes using `derives`, and opt into dynamic dispatch with `virtual`. ## Inheritance Classes inherit from other classes using `derives`: ```kairo class Animal { var name: string fn Animal(self, name: string) { self.name = name } fn speak(self) { std::io::println(f"{self.name} makes a sound") } } class Dog derives Animal { var breed: string fn Dog(self, name: string, breed: string) { Animal::Animal(self, name) // call base constructor self.breed = breed } fn speak(self) { std::io::println(f"{self.name} barks") } } ``` A base initializer is a statement of its own among the **first** statements of the constructor, before anything else runs: it builds the base part of `self` before any field. Its first argument is `self`; the other arguments may not use `self` (the object does not exist yet). Each base is initialized at most once, and only a direct base, or a [virtual base](#diamond-and-virtual-inheritance), can be. Calling a constructor by name anywhere else is an error: to build a value, call the type (`Animal("Rex")`). A base with no default constructor (its constructors all take arguments, or its default constructor is `= delete`) must be initialized by every constructor of a class that derives from it, so such a derived class has to declare a constructor. Declaring only a transfer constructor (`@copy` / `@move`), even a deleted one, removes the implicit default constructor; declare `fn X(self) = default` to keep it. A derived class's own `@copy` or `@move` constructor initializes its base with the base's transfer constructor: `Base::Base(self, other)` transfers the base part of `other`. ### Inheritance visibility By default, inheritance is public. Append `pub`, `prot`, or `priv` after `derives` to control how base members are exposed in the derived class: ```kairo class Derived derives pub Base { ... } // base members keep their visibility class Derived derives prot Base { ... } // all base members become protected class Derived derives priv Base { ... } // all base members become private ``` The narrowing applies to members reached through `Derived`. The conversion from `*Derived` to `*Base` stays available everywhere, and through a `*Base` the members have their own visibility again. (In the generated C++ the base is public and the members are narrowed with `private:` / `protected:` using-declarations, so a C++ program sees the same thing.) ### Multiple inheritance ```kairo class Serializable { fn serialize(self) -> [byte] { ... } } class Printable { fn print(self) { ... } } class Document derives Serializable, Printable { // inherits both serialize() and print() } class Widget derives pub Drawable, prot EventHandler { ... } ``` ### Calling base class methods There is no `super` keyword. Call base methods explicitly using the qualified name: ```kairo class Derived derives Base { fn method(self) { Base::method(self) } } ``` The qualified call is not virtual: `Base::method(self)` runs `Base`'s version even when `method` is `virtual` and overridden further down. A derived method with the same parameters (and the same `const self` or plain `self`) overrides or hides the base's, so `d.method()` on a derived value calls the derived one; a base overload with different parameters stays callable on the derived value (Kairo merges the overload sets, as C++ does with a `using` declaration). A C++ class keeps C++'s lookup: a name it declares hides the base's unless its definition says `using Base::name;`. A derived method meant to replace a hook its generic base calls through `self.dyn()` (the [mixin pattern](/docs/language/generics/#mixins-a-base-that-calls-its-derived-class)) must take the hook's exact parameters. One with the same name and number of parameters but a different parameter type (`*Node?` for `unsafe *Node`) is a second overload, and the base's `self.dyn()->hook(n)` keeps calling the base's own `hook`. The compiler warns (SC278W), with notes at the base's hook and at the call, and a fix-it when only the pointer's safety, nullability or `const` differs. `*T` and `unsafe *T` count as the same parameter here (both are `T*` in C++), so that pair does replace the hook. To keep a deliberate second overload, put `@no_warn(SC278W)` on it. ### Protected members from another file A subclass declared in a different file than its base reaches a `prot` instance member only through an object of its own type or a type deriving from it, and calls a `prot` constructor only as its base initializer: ```kairo class Counter derives Base { fn Counter(self) { Base::Base(self, 2) } // ok: base initializer fn own(self) -> i32 { return self.hits } // ok fn other(self, c: *Counter) -> i32 { return c->hits } // ok fn via_base(self, b: *Base) -> i32 { return b->hits } // error: through a Base fn standalone(self) { var b = Base(5) } // error: a separate Base } ``` Code in the base's own file has no such restriction. ### Destructors and inheritance A class with a non-trivial destructor (its own `op finally` with a body, or any field or base that has one) may only derive from a **polymorphic** class (one with any `virtual` method, or a `derives virtual` base) if that class's destructor is `virtual`. Otherwise deleting the derived object through a `*Base` runs only the base's destructor and leaks the rest. This is a compile error at the derived class. ```kairo class Base { virtual fn name(self) -> string { return "base" } fn op finally(self) { } } class Derived derives Base { // error: 'Base' has no virtual destructor fn op finally(self) { } } ``` A base with no virtual methods is exempt: it is not used through a base pointer for dispatch, so a mixin or plain data base needs no vtable just for its destructor. ```kairo class Counted { var refs: i32 = 0 } // not polymorphic class Node derives Counted { // ok fn op finally(self) { } } ``` ```kairo class Base { virtual fn op finally(self) { } } class Derived derives Base { // ok override fn op finally(self) { } } ``` A destructor is virtual when declared `virtual` or `override`, or when any base's is. As with any other method, virtualness is inherited. A derived class with a trivial destructor is exempt. ### Diamond and virtual inheritance If `B` and `C` both derive from `A`, and `D` derives from both `B` and `C`, then `D` contains two copies of `A`'s subobject. Disambiguate with qualified names: ```kairo class A { fn method(self) { std::io::println("A") } } class B derives A { fn method(self) { std::io::println("B") } } class C derives A { fn method(self) { std::io::println("C") } } class D derives B, C { fn method(self) { B::method(self) C::method(self) } } ``` To share a single `A` subobject, use `derives virtual`. The most-derived class is responsible for initializing the virtual base directly; intermediate classes' calls to the virtual base constructor are ignored: ```kairo class A { var value: i32 fn A(self, v: i32) { self.value = v } } class B derives virtual A { fn B(self, v: i32) { A::A(self, v) } } class C derives virtual A { fn C(self, v: i32) { A::A(self, v) } } class D derives B, C { fn D(self, v: i32) { A::A(self, v) // D initializes the virtual base B::B(self, v) C::C(self, v) } } ``` ### Lifecycle category matching A derived class's [lifecycle category](/docs/language/classes-lifecycle/#lifecycle-categories) must be compatible with its base's: | Base category | Allowed derived categories | |---|---| | COPY | COPY, NON_TRANSFER | | MOVE | MOVE, NON_TRANSFER | | NON_TRANSFER | NON_TRANSFER | A copyable base with a move-only derived class is a compile error slicing a derived instance through a base pointer would otherwise silently copy the base subobject of a class that promised never to be copied. See [Casting](/docs/language/casting/) for upcasting and downcasting. --- ## Virtual Dispatch By default, methods are statically dispatched. To enable dynamic dispatch via a vtable, mark the method `virtual` in the base class: ```kairo class Shape { virtual fn area(const self) -> f64 { return 0.0 } } class Circle derives Shape { var radius: f64 fn Circle(self, radius: f64) { self.radius = radius } override fn area(const self) -> f64 { return 3.14159 * self.radius * self.radius } } var circle = Circle(5.0) var shape: *Shape = &circle shape->area() // 78.539... dynamic dispatch ``` `virtual` creates a vtable slot. `override` in the derived class replaces the entry in that slot. A class only has a vtable pointer (8 bytes at offset 0) if it declares or inherits at least one `virtual` method. Non-polymorphic classes have no vtable overhead. A `virtual` method that may [panic](/docs/language/panic/) must declare its panic set (`virtual fn load(self) panic(IOError) -> Data`), since it is the contract for every override. An `override` may leave its own set inferred, but that set must be a subset of the base method's. See [Declared Panic Sets](/docs/language/panic/#declared-panic-sets). An override returns the virtual method's type, or a pointer to a class derived from the one the virtual returns a pointer to, with no more `const` (a covariant return). A nullable pointer is not covariant; any other mismatch is SC297E. ### Abstract classes (pure virtual) A `virtual` method declared with no body is pure virtual: it must be overridden by any non-abstract derived class: ```kairo class Shape { virtual fn area(const self) -> f64 virtual fn perimeter(const self) -> f64 } class Circle derives Shape { var radius: f64 fn Circle(self, radius: f64) { self.radius = radius } override fn area(const self) -> f64 { return 3.14159 * self.radius * self.radius } override fn perimeter(const self) -> f64 { return 2.0 * 3.14159 * self.radius } } // var s = Shape() // compile error: Shape has pure virtual methods var c = Circle(5.0) // ok: all pure virtuals overridden ``` A class with a pure virtual method is abstract, and so is a derived class that leaves any of its bases' pure methods unoverridden. Creating an object of an abstract class (`Shape()`, `Shape{ }`) is a compile error that points at the method keeping it abstract; a pointer to one (`*Shape`) is fine. In C++ a pure virtual method is `virtual R f() = 0`, so a C++ class can derive a Kairo abstract class and a Kairo class can derive a C++ one. Taking or returning one by value, or holding one in a field, is also an error (SC249E); take a pointer, or a `const` or `@inout` parameter. Kairo methods are `noexcept` in C++ (see [Exceptions](/docs/language/c-cpp-exceptions/#c-exceptions-through-kairo-frames)), so a C++ class overriding a Kairo `virtual fn` must declare its override `noexcept` as well, unless the Kairo method is `@unwind`: ```cpp struct Rect : shape::Shape { // Shape: a Kairo abstract class double area() const noexcept override { return w * h; } }; ``` Only a `virtual` method without a body is pure; a method that is not `virtual` and has no body is a declaration. After `=`, a function takes only an expression, `default` or `delete`: the old spelling `fn area(const self) -> f64 = virtual` is an error whose fix-it rewrites it to `virtual fn area(const self) -> f64`. ### Final `final` prevents further overriding of a method or derivation from a class: ```kairo final class Singleton { /* ... */ } // class Derived derives Singleton { } // compile error class Base { virtual fn process(self) { ... } } class Middle derives Base { final override fn process(self) { ... } // overrides, then locks } class Bottom derives Middle { // override fn process(self) { ... } // compile error: final in Middle } ``` --- ## See also - [Classes](/docs/language/classes/) - [Memory Layout and Allocation](/docs/language/classes/#memory-layout-and-allocation) - [Class Lifecycle](/docs/language/classes-lifecycle/) - [Forward Declarations and Out-of-Line Definitions](/docs/language/classes-out-of-line/) - [Interfaces](/docs/language/interfaces/) - [Casting](/docs/language/casting/) --- ## Class Lifecycle URL: https://www.kairolang.org/docs/language/classes-lifecycle/ # Class Lifecycle How instances of a [class](/docs/language/classes/) are destroyed, and how they are transferred between variables. ## Destructors - op finally A destructor is written `fn op finally(self)`. It is the same idea as a standalone [`finally { }` block](/docs/language/control-flow/#standalone-finally-scope-exit): code that runs when the object's scope ends, on every way out of it. ```kairo class Resource { var handle: unsafe *void fn Resource(self, h: unsafe *void) { self.handle = h } fn op finally(self) { release_handle(self.handle) } } ``` The old spelling `fn op delete(self)` is an error; the diagnostic carries a fix-it that renames it. Destructors can be defaulted or deleted: ```kairo fn op finally(self) = default // compiler-generated, memberwise destroy in reverse declaration order fn op finally(self) = delete // prevent destruction (and therefore stack allocation) ``` A destructor runs automatically at the end of the enclosing scope, in reverse declaration order. Kairo has no `delete` expression: running a destructor and freeing memory are separate steps, covered in [Freeing memory](#freeing-memory) below. ### Running cleanup early **Not implemented yet; planned for 0.3.** `x.finally()` (and its spelling `x.op finally()`) will be an explicit early destructor call: it will end the lifetime of a local `x` before its scope ends, so the destructor runs once, at that point, and not again at scope exit. Until then both spellings are an error (`'finally()' is not implemented yet (planned for 0.3)`, [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)). For now, a local is destroyed when its scope ends, so end the scope early with a block: ```kairo { var r = Resource(open_handle()) // use r } // r's destructor runs here ``` and a heap object is destroyed with `@destroy` (see [Freeing memory](#freeing-memory)). The destructor itself, `fn op finally(self)`, is unchanged. ### Constructors and destructors never panic No constructor (one with parameters, the default constructor, or a transfer constructor) and no destructor can [panic](/docs/language/panic/). Marking one `panic` is a compile error, and so is a panic that would escape one: an unhandled panicking call or `panic` statement in its body, or in a field default it runs. An object is either built whole or not at all, and a destructor runs on every exit from its scope, where nothing could take an error. Handle the error inside with `try`/`catch`, or stop the program with `crash!()`. Construction that can fail belongs in a static factory function, which may panic and returns the object: ```kairo class Conn { var fd: i32 fn Conn(self, fd: i32) { self.fd = fd } static fn open(path: string) panic(IOError) -> Conn { return Conn(open_fd(path)) // open_fd may panic; the constructor never does } } ``` ### Freeing memory `op finally` never frees the object's own storage. Heap memory is allocated with `@create T(args)` and freed with `@destroy p`, both through the [allocator in effect](/docs/language/allocators/). `@destroy p` runs the destructor of `*p` and then returns the memory to the allocator that produced it. There is no `delete` expression in Kairo. ```kairo class MyClass { var data: unsafe *i32 = &null fn MyClass(self) = default fn init(self) { self.data = unsafe std::alloc(sizeof i32 * 10) // 10 i32's allocated } fn op finally(self) { if self.data != &null { unsafe std::free(self.data) self.data = &null } } } var obj = MyClass() // stack allocated the object itself obj.init() // allocate the buffer data points to // do something with obj.data var heap = @create MyClass() heap.init() @destroy heap // runs the destructor, then frees the object through the allocator ``` `@destroy` runs the destructor, which here frees the buffer owned by the `data` member, and then returns the object's own storage to the allocator. (Running a destructor without freeing, `x.finally()`, is planned for 0.3.) Memory that comes from or goes to C++ code uses C++'s own allocation: `@cxx::new T(args)` is a plain C++ `new T(args)` (it returns an `unsafe *T`), and `@cxx::delete p` is `delete p`. See [C++ memory](/docs/language/c-cpp-memory/). --- ## Lifecycle Categories Every class has a lifecycle category that determines how its instances can be transferred between variables. A class's category is what its transfer constructors leave usable. If it can be copied, it is **COPY**. If it can only be moved, it is **MOVE**. If it can be neither, it is **NON_TRANSFER**. Deleting either transfer constructor on its own makes the class NON_TRANSFER: a declared copy constructor, even a deleted one, means no move is generated, and a deleted move constructor removes the copy. The canonical form deletes both, which says so explicitly. ### Attribute syntax `@copy` and `@move` are attributes attached to a constructor. The convention is one attribute per line above the declaration: ```kairo @copy fn Buffer(self, const other: Self) = default ``` Inline placement (`@copy fn Buffer(self, const other: Self) = default`) is permitted but discouraged. See [Attributes](/docs/language/attributes/) for the full attribute syntax. ### The transfer constructor The **transfer constructor** governs how instances of the class are passed by value. It is written in exactly one of two forms, with the marker on the constructor and the parameter otherwise bare: | Form | Meaning | C++ | |---|---|---| | `@copy fn X(self, const other: Self)` | the usual copy | `X(const X&)` | | `@move fn X(self, other: Self)` | move | `X(X&&)` | ```kairo class Buffer { @copy fn Buffer(self, const other: Self) = default } class UniqueFile { @move fn UniqueFile(self, other: Self) = default } ``` `@copy` without `const` (`@copy fn X(self, other: Self)`, C++ `X(X&)`) is allowed, but it cannot copy from a `const` object or from a temporary. `@move` cannot take `const`: a move leaves its source empty. Any other constructor that takes `Self` first and defaults every later parameter is a compile error (SC110E): ```kairo class X { fn X(self, other: Self) { } // error: no marker fn X(self, @move other: Self) { } // error: a mode on the parameter is not a marker fn X(self, other: Self, k: i32 = 0) { } // error: a defaulted extra parameter @move fn X(self, const other: Self) { } // error: @move cannot take const } ``` A constructor that takes `Self` first and then a parameter **without** a default is an ordinary constructor: ```kairo class X { fn X(self, other: Self, extra: i32) { } // ok: not a transfer constructor } ``` A move is written bare at the call site, `X(h)`, with no marker on the argument. A transfer constructor written `= default` copies or moves every field, which initializes each of them. One with a body is a constructor like any other: it must initialize every `const` member and every [field without a default](/docs/language/classes/#fields-without-a-default), and its first whole write of such a field is that field's initialization. A class with no transfer constructor takes the weakest category its bases and fields allow: **COPY** if all of them are COPY, **MOVE** if any is move-only, **NON_TRANSFER** if any cannot be transferred. Its special members are compiler-generated to match. A class cannot define both `@copy` and `@move` transfer constructors pick one: ```kairo class Bad { @copy fn Bad(self, const other: Self) = default @move fn Bad(self, other: Self) = default // compile error (SC057E) } ``` The one exception is both being `= delete`, the canonical **NON_TRANSFER** form. A class also cannot declare two transfer constructors of the same kind, such as `@copy` with and without `const` ([SC057E](/docs/language/diagnostics/#sc057e-more-than-one-transfer-constructor)). ### The four categories | Category | Trigger | Semantics | |---|---|---| | **COPY** | `@copy` ctor (explicit or implicit) | Allows copy; Tether may silently elide a copy into a move when the source is unused after the transfer | | **MOVE** | `@move` ctor | Allows move only; copying is a compile error | | **NON_TRANSFER** | either transfer constructor `= delete` (canonically both) | Stack-only; cannot be assigned, copied, or moved | | **DEFAULT** | no transfer ctor declared | Derived from bases and fields (see above) | A NON_TRANSFER class is the canonical scope guard: ```kairo class ScopeLock { fn ScopeLock(self) = default @copy fn ScopeLock(self, const other: Self) = delete @move fn ScopeLock(self, other: Self) = delete fn op finally(self) { /* ... */ } } ``` ### The Rule of Three The user writes at most three special members: 1. The default constructor (`fn Class(self)`) 2. **One** transfer constructor (`@copy` or `@move`, never both) 3. The destructor (`fn op finally(self)`) Each may have a user body, `= default`, or `= delete`. Anything not written is compiler-generated. A `= default` member is what the compiler would have generated: it is trivial when the same member of every base and field is. A transfer constructor or destructor with a body makes the class non-trivial, and so does a deleted one or a `virtual` destructor. A polymorphic class (a `virtual` method or a virtual base) is never trivially copyable, and neither is a NON_TRANSFER class. ```kairo class Buffer { var data: unsafe *u8 var size: usize fn Buffer(self, size: usize) { self.data = unsafe std::alloc(size) self.size = size } @move fn Buffer(self, other: Self) { self.data = other.data self.size = other.size other.data = &null other.size = 0 } fn op finally(self) { unsafe std::free(self.data) } } ``` ### Assignment is auto-derived `op =` is generated from the transfer constructor the user does not write it. Writing it explicitly is a compile error. | Transfer ctor form | Generated `op =` | |---|---| | none written | member by member, like the compiler-generated transfer constructor | | `= default` | `= default`: member by member | | `= delete` | `= delete` | | `{ body }` | checks for self-assignment, destroys `self`, rebuilds it in place through the transfer constructor, returns `self` | The body case first checks for self-assignment: `x = x` does nothing. Otherwise it destroys `self`, builds a new value in its place by running the transfer constructor on the right-hand side, and returns `self`. Member-by-member assignment needs every base and field to be assignable. If one is not, the class has no `op =`. A polymorphic class whose transfer constructor has a body has no `op =` either. Rebuilding it in place would give the object this class's vtable pointer, which is wrong when the object is really a derived class or is the base part of one. A polymorphic class with a `= default` transfer constructor, or with none, assigns member by member as usual. Assigning a value whose class has no `op =` is a compile error (SC071E). When the reason is a polymorphic class whose transfer constructor has a body, the error adds: "a polymorphic class whose transfer constructor has a body cannot be assigned; construct a new value". This implies a consistency rule: if the transfer ctor has a body and `op finally` is `= delete`d, the class fails to compile the auto-derived `op =` needs to invoke the destructor and cannot. Fix by providing a destructor or by changing the transfer ctor to `= default` / `= delete`. ### Defaulted moves of non-movable members `= default` on a `@move` ctor performs memberwise move: each member is moved through its own `@move` ctor. If a member is COPY-only (no `@move` available), that member is **copied** as part of the move matching C++ semantics. This is silent and almost always what you want; if a member must be moved or nothing, write the transfer ctor body explicitly and let the compiler error on the COPY-only field. The converse is checked too. A defaulted `@copy` constructor requires every base and field to be copyable, and a defaulted `@move` requires every base and field to be movable or copyable. Otherwise it is a compile error ([SC129E](/docs/language/diagnostics/#sc129e-a-defaulted-transfer-constructor-cannot-be-generated)) naming the field. A transfer constructor with a body is exempt; it decides for itself how each field is transferred. ### Implicit-copy-with-custom-destructor warning A class with a custom destructor but no explicit `@copy` or `@move` transfer constructor compiles, but emits a warning. The class is implicitly copyable, and a custom destructor almost always means the class owns a resource silent copies of that resource cause double-free and aliasing bugs. The warning applies only when the class is actually copyable; a class that is move-only or non-transferable because of its fields does not get it. ```kairo class UniqueFile { var handle: unsafe *void fn op finally(self) { close_file(self.handle) } // warning: custom destructor with implicit copy constructor // help: declare as @move: // @move fn UniqueFile(self, other: Self) = default // help: or make it non-transferable: // @copy fn UniqueFile(self, const other: Self) = delete } ``` ### Tether copy elision For COPY classes, [Tether](/docs/language/tether/) may emit a move instead of a copy when it proves the source is unused after the transfer. This is a pure optimization with no observable semantic difference the source is destroyed either way, just earlier when elided. Tether does not elide if the move constructor is deleted. Users do not opt into or out of this optimization. --- ## See also - [Classes](/docs/language/classes/) - [Inheritance and Virtual Dispatch](/docs/language/classes-inheritance/) - [Forward Declarations and Out-of-Line Definitions](/docs/language/classes-out-of-line/) - [Ownership](/docs/language/ownership/) - [Interface Requirements](/docs/language/interfaces-requirements/#lifecycle-attributes-on-constructor-requirements) - [Tether](/docs/language/tether/) - [Attributes](/docs/language/attributes/) - [Diagnostics](/docs/language/diagnostics/) --- ## Forward Declarations and Out-of-Line Definitions URL: https://www.kairolang.org/docs/language/classes-out-of-line/ # Forward Declarations and Out-of-Line Definitions A class (and likewise a [struct](/docs/language/structures/#forward-declarations) or [union](/docs/language/unions/#forward-declarations)) can be forward-declared without a body sufficient for `*Class` uses, not for `sizeof`, member access or holding it by value. The forward declaration must use the same keyword as the definition: ```kairo class Parser class Lexer { var parser: unsafe *Parser // ok: pointer to incomplete type } class Parser { var lexer: Lexer // full definition } ``` Member methods can also be declared inside the class body without a body and defined out-of-line using the `Class::method` qualified-name syntax: ```kairo struct ParseError { var message: string var pos: usize fn op panic (const self) -> string { return f"{self.message} at token {self.pos}" } } class Parser { var tokens: [Token] var pos: usize pub fn Parser(self, tokens: [Token]) pub fn advance(self) -> Token pub fn peek(const self) -> Token priv fn error(self, msg: string) panic } fn Parser::Parser(self, tokens: [Token]) { self.tokens = tokens self.pos = 0 } fn Parser::advance(self) -> Token { var t = self.tokens[self.pos] self.pos += 1 return t } fn Parser::peek(const self) -> Token = self.tokens[self.pos] fn Parser::error(self, msg: string) panic { panic ParseError { message: msg, pos: self.pos } } ``` This pattern keeps the class body small and readable as an API surface, with implementation details defined separately. ## Rules - The qualified definition's signature must exactly match the in-class declaration: parameter types, return type, and all function modifiers (`const`, `unsafe`, `panic`, `eval`, `async`, `inline`, `final`, `virtual`, `override`, `static`). - **Visibility is omitted** from the out-of-line definition it is taken from the in-class declaration. Writing `pub fn Parser::advance` is a compile error. - **Default arguments** must appear on the in-class declaration, not the out-of-line definition. - Parameter names may differ between declaration and definition; the definition's names are used in the body. A member of a C++ class, or a function in a C++ namespace, that an imported header declares can be defined in Kairo the same way (`fn Widget::get(self) -> i32 { ... }`, `static fn Widget::make() -> ...`, `fn ns::f(...)`). The definition is the C++ declaration's: C++ code that calls it runs the Kairo body. Constructors, destructors and members of class templates can't be defined this way yet. ## Generic classes For [generic classes](/docs/language/classes/#generic-classes), the type parameters are re-declared on the out-of-line definition and the class name carries its generic arguments: ```kairo class Vec { var data: unsafe *T var len: usize var cap: usize pub fn push(self, value: T) pub fn get(const self, i: usize) -> T } fn Vec::push(self, value: T) { if self.len == self.cap { self.grow() } self.data[self.len] = value self.len += 1 } fn Vec::get(const self, i: usize) -> T = self.data[i] ``` ## Operators, constructors, destructors [Operator overloads](/docs/language/operator-overloading/), constructors, and destructors follow the same pattern: ```kairo class Vec2 { var x: f64 var y: f64 pub fn Vec2(self, x: f64, y: f64) pub fn op finally(self) pub fn op +(self, other: Vec2) -> Vec2 } fn Vec2::Vec2(self, x: f64, y: f64) { self.x = x self.y = y } fn Vec2::op finally(self) { /* ... */ } fn Vec2::op +(self, other: Vec2) -> Vec2 = Vec2(self.x + other.x, self.y + other.y) ``` ## Nested types For methods on a nested type, chain the qualifiers: ```kairo fn Outer::Inner::method(self) { /* ... */ } ``` --- ## See also - [Classes](/docs/language/classes/) - [Class Lifecycle](/docs/language/classes-lifecycle/) - [Inheritance and Virtual Dispatch](/docs/language/classes-inheritance/) - [Generics](/docs/language/generics/) - [Functions](/docs/language/functions/) - [Operator Overloading](/docs/language/operator-overloading/) --- ## Collections URL: https://www.kairolang.org/docs/language/collections/ # Collections Collections are built-in generic types with literal syntax. There are three sequence types, which differ in who owns the elements: | Type | Name | Owns its elements | Storage | |---|---|---|---| | `[T; N]` | Array | yes | `N` elements inline, where the array is | | `[T;]` | Slice | no | pointer + length over storage owned by something else | | `[T]` | Vector | yes | a heap copy of its elements | Maps and sets are heap-allocated. ## Arrays `[T; N]` A contiguous block of `N` elements stored inline (in the local, the enclosing struct, or the enclosing array). `N` must be a compile-time constant. ```kairo var rgb: [u8; 3] = [255, 128, 0] rgb[0] = 10 // rgb.push(42) // compile error: fixed size ``` An array is **not a value type**. It cannot be copied, assigned, passed by value, or returned. It can be a local, a field, or an element of another array; it can be viewed by a slice, pointed to, and passed as a `const` or [`@inout` parameter](/docs/language/functions-parameter-modes/). Each of the following is a compile error, and each diagnostic names the fix: The same error (SC045E) is reported at a call that passes an array to a generic parameter taken by value (`fn f(a: T)`). A constant index outside `0..N-1` is a compile error (SC291E). A generic function that copies its `T` cannot be called with a fixed array (SC083E at the call). A vector, set or map literal copies its elements; a literal of move-only elements is not supported yet (SC182E). ```kairo var a = [1, 2, 3] // [i32; 3] var b = a // compile error: an array is not copyable b = a // compile error: an array is not assignable fn f(xs: [i32; 3]) { } // compile error: takes an array by value fn g() -> [i32; 3] { } // compile error: returns an array ``` - To copy, copy the elements, or view the source through a slice or a pointer. - To assign, assign the elements, or go through a slice. - To take an array, write `const xs: [i32; 3]` or `@inout xs: [i32; 3]` (both pass by reference), or take a slice `[i32;]`. - To produce one, return a `[T]`, or fill an `@inout` parameter. ```kairo fn sum(const xs: [i32; 3]) -> i32 { return xs[0] + xs[1] + xs[2] } fn zero(@inout xs: [i32; 3]) { xs[0] = 0; xs[1] = 0; xs[2] = 0 } var a = [1, 2, 3] sum(a) // 6 zero(&a) // a is now [0, 0, 0] ``` Indexing an array with a range, `a[i..j]`, gives a slice over those elements: ```kairo var a = [1, 2, 3, 4] var mid = a[1..3] // [i32;] viewing a[1] and a[2] ``` ## Slices `[T;]` A view over contiguous elements: a pointer and a length. A slice does not own the storage it points into and never frees it. ```kairo var s: [i32;] = [1, 2, 3] // the storage lives as long as s s[0] // 1 ``` An array converts to a slice implicitly. The slice is a view of the array, so nothing is copied. A `const` array converts only to `[const T;]`. A vector also converts to a slice implicitly. ```kairo fn total(xs: [i32;]) -> i32 { ... } var a = [1, 2, 3] total(a) // a viewed as [i32;] ``` ## Vectors `[T]` A growable, owning, contiguous array. Layout: `ptr + len + cap` (24 bytes). A vector owns a heap copy of its elements. ```kairo var nums: [i32] = [1, 2, 3] nums.push(4) nums[0] // 1 bounds-checked ``` A slice never becomes a vector implicitly, because that allocates. Write the conversion: ```kairo var s: [i32;] = [1, 2, 3] var v = s as [i32] // copies the elements into a new vector ``` ## List literals `[a, b, c]` is an array, `[T; 3]`, unless the context asks for a slice or a vector: ```kairo var a = [1, 2, 3] // [i32; 3] var s: [i32;] = [1, 2, 3] // slice over storage that lives as long as s var v: [i32] = [1, 2, 3] // vector, owns a copy f([1, 2, 3]) // takes the parameter's type: array, slice, or vector ``` The element type is the target's element type. With no target, it is the join of the element types. An empty `[]` has no element type to infer. Annotate the target as `[T;]` or `[T]`: ```kairo var e = [] // compile error: cannot infer the type of an empty list here var f: [i32] = [] // ok ``` A literal whose element count does not match `[T; N]` is an error. It never falls back to a slice: ```kairo var x: [i32; 4] = [1, 2, 3] // compile error: array literal has 3 elements, but '[i32; 4]' needs 4 ``` ### How long a slice literal's storage lives A list literal that becomes a slice is a view of a temporary array. That array lives: - for the **statement**, when the literal is a function argument; - for the **enclosing scope**, when the literal directly initializes a `var`. So a slice literal is an error anywhere the view would outlive its storage: ```kairo fn make() -> [i32;] { return [1, 2] // compile error: returned from a function } var s: [i32;] = [1] s = [1, 2] // compile error: assigned to a slice struct S { var xs: [i32;] = [1] // compile error: used as a field default } var t = S{ xs: [1, 2] } // compile error: stored in a field ``` The fix is the same in every case: use `[T]` so the elements are owned, or bind the literal to a `var` first and use that. > [!WARNING] > One case is not caught: passing a slice literal to a function that **stores** the slice. The literal's storage ends with the statement, and the stored slice then points at nothing. Until [Tether](/docs/language/tether/) checks this, it is the programmer's responsibility. ### Slices in fields A `[T;]` field is a borrowed view; the type holding it does not own the data. A type that keeps its data declares `[T]` or `[T; N]`: ```kairo struct Packet { var header: [u8; 4] // owned, inline var payload: [u8] // owned, heap var source: [u8;] // borrowed, must outlive the Packet } ``` ### Conversions between the three | From | To | How | |---|---|---| | list literal | `[T; N]`, `[T;]`, `[T]` | implicit, when the target asks for it | | slice `[T;]` | vector `[T]` | explicit only: `s as [T]` (allocates) | | array `[T; N]` | slice `[T;]` | implicit, a view (no copy); a `const` array only to `[const T;]` | | vector `[T]` | slice `[T;]` | implicit, a view (no copy) | | array `[T; N]` | array `[T; N]` | never: arrays are not copyable | ## Maps `{K: V}` A hash map from keys of type `K` to values of type `V`. ```kairo var ages: {string: i32} = {"Alice": 30, "Bob": 25} ages["Charlie"] = 35 ``` ## Sets `{T}` A hash set of unique elements. ```kairo var primes: {i32} = {2, 3, 5, 7, 11} ``` ## Tuples `(T1, T2, ...)` A fixed-size, heterogeneous, ordered group of values. Stored contiguously with padding for alignment. ```kairo var point: (f64, f64) = (1.0, 2.0) var record: (i32, string, bool) = (42, "Answer", true) ``` ## Function Pointers `fn (T1, T2, ...) -> R` [A pointer to a function](/docs/language/functions/#function-pointers) with the given signature. Platform-dependent size. ```kairo fn add(a: i32, b: i32) -> i32 { return a + b } var f: fn (i32, i32) -> i32 = add f(3, 4) // 7 ``` > [!IMPORTANT] > The stdlib API for vectors, maps, and sets is still being finalized. Detailed method documentation will be added in a future update. --- ## See also - [Primitives](/docs/language/primitives/) - [Conversion Lattice](/docs/language/conversion-lattice/#list-literal-arguments) - [Casting](/docs/language/casting/) - [Pointers](/docs/language/pointers/) - [Tether](/docs/language/tether/) - [Type System](/docs/language/type-system/) - [Destructuring](/docs/language/variables/#destructuring) - [Parameter Modes](/docs/language/functions-parameter-modes/) --- ## Kairo Primitive Conversion Lattice URL: https://www.kairolang.org/docs/language/conversion-lattice/ # Kairo Primitive Conversion Lattice Normative specification for implicit and explicit conversions between primitive types. This document is the single source of truth for `-f[no-]implicit-conv`, overload resolution ranking, and binary operator result typing. C++'s own implicit conversions where a value crosses into C++ are `-f[no-]cxx-implicit-conv` ([Calling C and C++](/docs/language/c-cpp-calling/#argument-conversions)); this document does not govern them. --- ## 1. Conversion classes Every ordered pair `(S, T)` of primitive types falls into exactly one class: | Class | Meaning | `as` cast | Implicit | |---|---|---|---| | **I** (identity) | `S` and `T` are the same type | no-op | yes | | **W** (implicit) | value-preserving for every value of `S`; zero or near-zero cost; target-independent | permitted | yes | | **E** (explicit) | representable but may lose value, sign, or precision, or costs a runtime helper | required | no | | **U** (unsafe) | requires an `unsafe` context in addition to `as` | required | no | | **X** (forbidden) | no cast exists; diagnostic suggests a library function | rejected | no | There is no "warn" class. A conversion is either sound-by-construction or it is not; a third state would force the checker to carry a severity through overload resolution, and severities do not compose. Lossy-cast detection on known-constant operands is a lint (section 8), not part of the type relation. **`-fno-implicit-conv` demotes every W to E.** It changes nothing else. Section 7 proves this cannot alter which overload is selected. --- ## 2. The rule set W membership is decided by five rules. Everything not matched by a rule is E if a representation-changing cast is meaningful, X otherwise. **R1 - integer widening.** `uN -> uM` and `iN -> iM` are W when `M > N`. **R2 - sign-crossing.** `uN -> iM` is W when `M > N` (value-preserving: the entire unsigned range fits). `iN -> uM` is **never** W, for any `N`, `M`. Signed-to-unsigned loses negatives at every width; there is no widening that repairs it. **R3 - integer to float.** `S -> fM` is W iff every value of `S` is exactly representable in `fM`, i.e. `bits(S) <= mantissa(fM)` counting the implicit leading bit. This is an *exactness* criterion, not a size criterion: `i32 -> f32` is same-size and lossy, while `i32 -> f64` is smaller-to-larger and exact. | Target | Mantissa bits | Exact integer sources | |---|---|---| | `f16` | 11 | `u8`, `i8` | | `f32` | 24 | `u8`, `i8`, `u16`, `i16` | | `f64` | 53 | `u8`, `i8`, `u16`, `i16`, `u32`, `i32` | **R4 - float widening.** `f16 -> f32`, `f16 -> f64`, `f32 -> f64` are W. All other float-to-float pairs are E. **R5 - extended width is opaque.** No type wider than 64 bits (`u128`-`u512`, `i128`-`i512`, `f128`-`f512`) is ever the *target* of a W conversion, and no extended-width type is ever the *source* of one. Rationale: on targets without wide register support these conversions emit multi-word or software-SIMD sequences. Making implicitness depend on the target would mean the same source compiles differently per triple. Uniform E on all targets keeps the cost visible in the source text and keeps the lattice target-independent. Everything else (`bool`, `char`, `byte`, `usize`, `isize`, `string`, `void`, pointers, aggregates) participates in **no** W conversion in either direction. Reasons in section 4. The single exception is an argument to an [imported C/C++ function](/docs/language/c-cpp-calling/#argument-conversions), where `usize`/`isize` widen by the boundary rule in section 4.1. --- ## 3. Core integer table Rows are source, columns are target. `<=64`-bit fixed-width integers only; wider widths are E by R5. | S \ T | `u8` | `u16` | `u32` | `u64` | `i8` | `i16` | `i32` | `i64` | |---|---|---|---|---|---|---|---|---| | **`u8`** | I | W | W | W | E | W | W | W | | **`u16`** | E | I | W | W | E | E | W | W | | **`u32`** | E | E | I | W | E | E | E | W | | **`u64`** | E | E | E | I | E | E | E | E | | **`i8`** | E | E | E | E | I | W | W | W | | **`i16`** | E | E | E | E | E | I | W | W | | **`i32`** | E | E | E | E | E | E | I | W | | **`i64`** | E | E | E | E | E | E | E | I | Read the shape: the unsigned block is upper-triangular, the signed block is upper-triangular, the unsigned-to-signed quadrant is *strictly* upper-triangular (one width step is required, so `u32 -> i32` is E), and the signed-to-unsigned quadrant is empty. ## 3.1 Float and cross-domain | S \ T | `f16` | `f32` | `f64` | `f128`+ | any int | `bool` | `char` | `byte` | |---|---|---|---|---|---|---|---|---| | `u8`/`i8` | W | W | W | E | see section 3 | E | `u8`: W, `i8`: E | E | | `u16`/`i16` | E | W | W | E | see section 3 | E | `u16`: W, `i16`: E | E | | `u32`/`i32` | E | E | W | E | see section 3 | E | `u32`: W, `i32`: E | E | | `u64`/`i64` | E | E | E | E | see section 3 | E | E | E | | `f16` | I | W | W | E | E | X | X | X | | `f32` | E | I | W | E | E | X | X | X | | `f64` | E | E | I | E | E | X | X | X | | `f128`+ | E | E | E | E/I | E | X | X | X | | `bool` | X | X | X | X | E | I | X | X | | `char` | X | X | X | X | see below | X | I | X | | `byte` | X | X | X | X | E | X | X | I | | `string` | X | X | X | X | X | X | X | X | | `void` | X | X | X | X | X | X | X | X | Float-to-int is E in all cases. The cast truncates toward zero and saturates on out-of-range values; it is never undefined behavior. See [Casting](/docs/language/casting/#float-to-integer). --- ## 4. Non-numeric primitives: rationale **`usize` / `isize`.** No W conversion to or from any fixed-width type, in either direction, including `usize -> u64` on 64-bit targets. This is the one place where a tempting rule breaks portability outright: if `usize -> u64` were W on 64-bit, code would compile on `x86_64` and fail on `wasm32`. `usize` and `isize` also do not W-convert to each other. Literals still work: `var i: usize = 0` is literal inference (section 5), not conversion. **`byte`.** No W conversion to or from `u8`. `byte` is restricted to bitwise operations ([Byte](/docs/language/primitives/#byte)); if `byte -> u8` were implicit then `b + mask` would succeed by converting both operands and the restriction would be decorative. E in both directions. **`char`.** A `char` is a 32-bit Unicode scalar value. It converts implicitly to and from an integer only when the **target is equal or wider**; everything else needs `as`. Signed 32-bit and narrower types never convert implicitly, in either direction. | Direction | W (implicit) | E (`as` required) | |---|---|---| | `char -> int` | `u32`, `u64`, `u128`, `i64`, `i128` | `u8`, `u16`, `i8`, `i16`, `i32`, `usize`, `isize` | | `int -> char` | `u8`, `u16`, `u32` | `i8`, `i16`, `i32`, `i64`, `i128`, `u64`, `u128`, `usize`, `isize` | This is the one place R5 does not apply: `char -> u128` and `char -> i128` are W because the source is a fixed 32-bit value and the widening is exact. Signed targets must be *strictly* wider (`char -> i32` is E, as `u32 -> i32` is). `usize`/`isize` stay E as everywhere else. `u8`/`u16`/`u32 -> char` is W even though a `u32` can hold a surrogate or a value above `0x10FFFF`, which are not scalar values and so never exist as a `char`. The conversion is **unchecked**: it does not trap and does not yield a `char?`. An out-of-range value produces a `char` that is not a scalar value, which can only show up as wrong text, never as a memory-safety violation, so it is a logic error in the program, not undefined behavior. Because `char -> u32` is also W, mixing a `char` and a `u32` in one binary operation (`c + n`, `c == n`) is ambiguous and is an error: write `as` on one side. An **untyped integer literal** takes `char` exactly when its value is a scalar value (`0` to `0xD7FF` or `0xE000` to `0x10FFFF`); `0xD800`, `0x110000` and `-1` are error SC075E. **`bool`.** E in both directions. [Bool](/docs/language/primitives/#bool) already forbids implicit conversion from integers; the reverse is forbidden too. `int -> bool` is E with `!= 0` semantics. **Pointers.** `*T -> unsafe *T` is **U**, not W. It is a safety downgrade and [Tether](/docs/language/tether-bounds/#provenance-and-epochs) loses provenance at that point, so it should be visible. `unsafe *T -> *T` is U and must be a checked or asserted construction, never a silent reinterpretation. `*T -> unsafe *void` is U. Pointer-to-integer and integer-to-pointer are both U. No pointer conversion is ever W. **Aggregates.** Conversions never recurse into structure. `[i32] -> [i64]`, `(i32, i32) -> (i64, i64)`, `{string: i32} -> {string: i64}` are all X. [Function pointers](/docs/language/functions/#function-pointers) are invariant in both parameter and return position: no variance, no exceptions. If you want element-wise conversion it is a library `map`, not a coercion. ### 4.1 The C/C++ boundary An argument to an **imported** C/C++ function may widen to or from `usize`/`isize` without `as`. Nothing else uses this rule: Kairo functions, assignments, `if`/`match` arms and operator operands keep section 4 alone. The rule reads the target only below 32 bits. `usize` and `isize` are taken as [32, 64] bits wide, or [P, 64] on a target whose pointer width P is below 32; a fixed-width integer of N bits is [N, N]. `S -> D` is implicit iff: - same signedness: `max(S) <= min(D)` - unsigned to signed: `max(S) < min(D)` - signed to unsigned: never | Accepted | Refused | |---|---| | `u8`/`u16`/`u32` -> `usize` | `u64` -> `usize` (narrows on 32-bit) | | `i8`/`i16`/`i32` -> `isize` | `i64` -> `isize` (narrows on 32-bit) | | `u8`/`u16` -> `isize` | `u32` -> `isize` (same width on 32-bit) | | `usize` -> `u64`, `isize` -> `i64` | `usize` -> `u32`, `isize` -> `i32` (narrow on 64-bit) | | | `usize` -> `i64` (same width on 64-bit) | | | `i32` -> `usize`, `isize` -> `u64` (signed to unsigned) | Because the rule judges against the narrowest and widest target at once, every 32- and 64-bit target accepts the same set of programs; a 16-bit target accepts a subset. This keeps the property section 4 protects. A conversion accepted by this rule is considered only when section 3 would require `as`, and ranks like any other implicit conversion in overload resolution. Extended-width types (R5), floats and non-numeric types never take it, and `-fno-implicit-conv` turns it off like any other W. The importer reads `size_t`/`uintptr_t` as `usize`, and `ptrdiff_t`/`intptr_t`/`ssize_t` as `isize`. A plain `unsigned long` stays a fixed-width type (`u64` on LP64 targets) and is judged by section 3. --- Literal inference is covered in [Primitives](/docs/language/primitives/#5-literal-inference-a-separate-mechanism). --- ## 6. Binary operators No separate "usual arithmetic conversions." Operator operand unification is defined *in terms of* the W relation, so there is exactly one conversion concept in the language: Given operands of type `A` and `B`, `A != B`: - If `W(A -> B)` and not `W(B -> A)`: result operand type is `B`. - If `W(B -> A)` and not `W(A -> B)`: result operand type is `A`. - Otherwise: **error**, requiring an explicit cast on one side. Consequences: | Expression | Result | Why | |---|---|---| | `i32 + i64` | `i64` | W one way only | | `u32 + i32` | error | neither direction is W (R2 blocks `i32 -> u32`; `u32 -> i32` fails the width test) | | `u32 + i64` | `i64` | R2 | | `i32 + f64` | `f64` | R3 | | `i64 + f64` | error | R3 exactness fails; force the cast | | `usize + i32` | error | section 4 | | `i64 + i128` | error | R5: extended width never silent | | `byte & u8` | error | section 4 | The `u32 + i32` error is deliberate. C's answer is `u32`, which silently converts every negative `i32` into a huge positive number; Kairo refuses rather than guess. Comparison operators use the same unification. Shift operators are the exception: the right operand is unified independently and any integer type is accepted, since the shift amount is not in the value domain of the result. [Compound assignment](/docs/language/operators/#assignment) `a op= b` requires `W(typeof(b) -> typeof(a))` or an exact match. It never converts the left operand. --- ## 7. Overload resolution, and why `-fno-implicit-conv` is a strict subset Conversion sequences have exactly two ranks: 1. **Exact** (I). 2. **Converted** (W). There is deliberately no ordering *within* rank 2. If two candidates are both reachable by W, the call is **ambiguous** and errors, even if one conversion is "narrower" in some intuitive sense. No `i32 -> i64` beats `i32 -> f64` tiebreaking. No promotion-vs-conversion distinction. The tie-breaks in [Function Overloading](/docs/language/functions-overloading/) (reference binding, non-generic over generic, most specialized generic) never order conversions, so "no ordering within rank 2" still holds, and so does the guarantee below. This is the property that makes the flag safe: > Let `C_on` be the candidate selected with W enabled. `-fno-implicit-conv` demotes every W to E, which removes candidates from the viable set but never adds one and never reorders the two ranks. An exact-match winner stays the winner. A rank-2 winner becomes non-viable, so the call errors. Therefore for all programs: the flag either preserves the selection or produces a diagnostic. It can never select a different candidate. ### List literal arguments A [list literal](/docs/language/collections/#list-literals) argument uses the same two ranks: - A `[T; N]` parameter, where `N` equals the literal's element count, is **Exact** when every element is exact for `T`. - A `[T;]` or a `[T]` parameter is **Converted**. The two are unordered against each other, like any other pair of rank-2 candidates. ```kairo fn f(const xs: [i32; 3]) { } fn f(xs: [i32;]) { } fn f(xs: [i32]) { } f([1, 2, 3]) // picks [i32; 3]: Exact beats Converted ``` With only the slice and vector overloads, both are Converted and the call is ambiguous. Annotate the argument to choose: ```kairo fn g(xs: [i32;]) { } fn g(xs: [i32]) { } g([1, 2, 3]) // compile error: call to 'g' is ambiguous g([1, 2, 3] as [i32]) // ok: vector overload var s: [i32;] = [1, 2, 3] g(s) // ok: slice overload ``` Literals other than list literals are unaffected. --- ## 8. Lints (not part of the type relation) - **`lint::lossy-cast`**: an `as` cast where the operand is a known constant that does not survive the round trip. Error by default; this is always a bug. - **`lint::redundant-cast`**: an `as` cast where the pair is I or W. - **`lint::sign-cast`**: any E cast crossing the signedness boundary. Off by default, on under a strict profile. None of these participate in overload resolution or operand unification. --- ## See also - [Casting](/docs/language/casting/) - [Implicit Conversions](/docs/language/casting-implicit/) - [Primitives](/docs/language/primitives/) - [Collections](/docs/language/collections/) - [Functions](/docs/language/functions/) - [Operators](/docs/language/operators/) - [Function Overloading](/docs/language/functions-overloading/) - [Calling C/C++](/docs/language/c-cpp-calling/#argument-conversions) `[T;]` and `[T]` convert implicitly to `[const T;]`, ranked like `*T` to `*const T`; the reverse does not convert, and the conversion does not apply under `?`. --- ## Diagnostics URL: https://www.kairolang.org/docs/language/diagnostics/ # Diagnostics This page lists compiler error messages verbatim so they can be searched. Placeholders are written in braces: `{n}` is a number, `{x}` a parameter name, `{f}` a function name, and `[T; M]` the type as written in your code. --- ## List Literals ### `array literal has {n} element(s), but '[T; M]' needs {m}` A [list literal](/docs/language/collections/#list-literals) initializes a fixed array of a different length. The literal is not silently turned into a slice. ```kairo var x: [i32; 4] = [1, 2, 3] // error: array literal has 3 element(s), but '[i32; 4]' needs 4 ``` **Fix:** give the literal the right number of elements, or change the target to `[T;]` or `[T]`. ### `cannot infer the type of an empty list here; annotate the target as '[T;]' or '[T]'` `[]` has no elements to take a type from and no target to take one from. ```kairo var e = [] // error var f: [i32] = [] // ok ``` **Fix:** annotate the target. --- ## Slice Literal Lifetime A list literal that becomes a slice `[T;]` is a view of a temporary array. These errors report the positions where the view would outlive that array. See [Primitives](/docs/language/collections/#how-long-a-slice-literals-storage-lives). ### `a list literal returned from a function is a view of a temporary array and would outlive it; use '[T]' to own the elements, or bind the literal to a 'var' first` ```kairo fn make() -> [i32;] { return [1, 2] // error } ``` ### `a list literal assigned to a slice is a view of a temporary array and would outlive it; use '[T]' to own the elements, or bind the literal to a 'var' first` ```kairo var s: [i32;] = [1] s = [1, 2] // error ``` ### `a list literal used as a field default is a view of a temporary array and would outlive it; use '[T]' to own the elements, or bind the literal to a 'var' first` ```kairo struct S { var xs: [i32;] = [1] // error } ``` ### `a list literal stored in a field is a view of a temporary array and would outlive it; use '[T]' to own the elements, or bind the literal to a 'var' first` ```kairo var t = S{ xs: [1, 2] } // error ``` **Fix, for all four:** declare the target `[T]` so it owns its elements, or bind the literal to a `var` in a scope that outlives the slice and use that variable. > [!NOTE] > Passing a slice literal to a function that stores the slice is not diagnosed. Until [Tether](/docs/language/tether/) checks it, it is the programmer's responsibility. --- ## Arrays A fixed array `[T; N]` is not a value type. See [Primitives](/docs/language/collections/#arrays-t-n). ### `an array is not copyable; initialize it from a list literal, or view the source through a slice or a pointer` ```kairo var a = [1, 2, 3] var b = a // error ``` ### `an array is not assignable; assign its elements, or go through a slice` ```kairo var a = [1, 2, 3] var b = [4, 5, 6] b = a // error ``` ### `parameter '{x}' takes an array by value; write 'const', '@inout', or take a slice` ```kairo fn f(xs: [i32; 3]) { } // error fn f(const xs: [i32; 3]) { } // ok fn f(@inout xs: [i32; 3]) { } // ok fn f(xs: [i32;]) { } // ok ``` ### `'{f}' returns an array; an array is not returned by value, return '[T]' or fill an '@inout' parameter` ```kairo fn g() -> [i32; 3] { ... } // error fn g() -> [i32] { ... } // ok fn g(@inout out: [i32; 3]) { } // ok ``` --- ## Overload Resolution ### `call to '{f}' is ambiguous: more than one candidate matches at the same rank` Two or more [overloads](/docs/language/functions-overloading/#overload-resolution) are viable and neither is an exact match, so there is nothing to choose between them. Conversions are not ranked against each other. ```kairo fn f(xs: [i32;]) { } fn f(xs: [i32]) { } f([1, 2, 3]) // error: call to 'f' is ambiguous f([1, 2, 3] as [i32]) // ok ``` **Fix:** make the argument's type explicit with `as` or a typed local. See [Primitives](/docs/language/conversion-lattice/#list-literal-arguments). --- ## Where Clauses ### `no fallback overload for '{f}' when where condition fails` Every [`where`](/docs/language/where/#fallback-requirement)-constrained overload needs a fallback: an overload of the same signature with no `where` clause, or conditions the compiler can prove cover every value. A note says what to add. ```kairo fn root(x: f64) -> f64 where x >= 0.0 { return x } // error: no fallback fn root(x: f64) -> f64 { return 0.0 } // ok: the fallback ``` **Fix:** add an overload without a `where` clause. ### `'where' is not allowed on ...` A `where` clause is runtime dispatch among overloads, so it is an error on a type (`'where' is not allowed on a class`, with a fix-it to `requires`), on an interface method, on an `unsafe` overload (unsafe overloads are a separate namespace), and on a closure. A guarded overload also needs a body (`a guarded overload of '{f}' needs a body`). ### `every overload in the 'where' dispatch of '{f}' must have the same {what}` The overloads of one dispatch become one function, so they must agree on return type, `const self`, `inline`, `-> !` and linkage. A note points at the first overload. ### `'where' guard of '{f}' is unreachable` / `overlaps an earlier one` / `never holds` (warnings) The compiler compares conditions that test integer parameters against constants. A condition inside an earlier one never fires (a note points at the earlier one); a condition that partly overlaps an earlier one sends the shared values to the earlier overload; a contradictory one (`x > 5 && x < 3`) never holds. See [Declaration Order](/docs/language/where/#declaration-order-determines-priority). --- ## Default Arguments ### SC106E: a default argument refers to another parameter or `self` A default is evaluated with no access to the call's other arguments, so it cannot name them. ```kairo fn a(x: i32, y: i32 = x) { } // error SC106E fn m(self, y: i32 = self.v) { } // error SC106E ``` **Fix:** add an overload that leaves the parameter out and forwards the value. See [Functions](/docs/language/functions-parameters/#a-default-stands-alone). ### SC107E: a named argument skips a defaulted parameter of an imported C++ function C++ applies an imported function's defaults and can only leave out trailing arguments. A call that names a later parameter while an earlier defaulted one is omitted cannot be expressed. ```kairo // C++: void blit(int x, int y = 0, int scale = 1); blit(4, scale: 2) // error SC107E ``` **Fix:** pass the earlier arguments explicitly: `blit(4, y: 0, scale: 2)`. See [Functions](/docs/language/functions-parameters/#defaults-on-imported-c-functions). --- ## Lifecycle ### SC057E: more than one transfer constructor A class has exactly one transfer constructor. It is an error to declare both a `@copy` and a `@move` transfer constructor, unless both are `= delete` (the non-transferable form), and it is an error to declare two transfer constructors of the same kind, such as `@copy` with and without `const`. ``` '{X}' declares both a '@copy' and a '@move' transfer constructor; pick one (both may be '= delete' together, which makes the class non-transferable) '{X}' declares more than one '@copy' transfer constructor; a class has exactly one transfer constructor ``` ```kairo class Bad { @copy fn Bad(self, const other: Self) = default @move fn Bad(self, other: Self) = default // error SC057E } class TwoCopies { @copy fn TwoCopies(self, const other: Self) = default @copy fn TwoCopies(self, other: Self) = default // error SC057E } ``` **Fix:** keep one transfer constructor. See [Classes](/docs/language/classes-lifecycle/#the-transfer-constructor). ### SC110E: a constructor has the shape of a transfer constructor but is not declared as one A constructor that takes `Self` first and defaults every later parameter is a transfer constructor, and is written only as `@copy fn X(self, const other: Self)` or `@move fn X(self, other: Self)`. ```kairo class A { fn A(self, other: Self) { } // error SC110E: no marker } class B { fn B(self, @move other: Self) { } // error SC110E: a mode on the parameter } class C { fn C(self, other: Self, k: i32 = 0) { } // error SC110E: a defaulted extra parameter } ``` **Fix:** put `@copy` or `@move` on the constructor and write the parameter bare. See [Classes](/docs/language/classes-lifecycle/#the-transfer-constructor). ### SC129E: a defaulted transfer constructor cannot be generated A defaulted `@copy` constructor needs every base and field to be copyable; a defaulted `@move` needs every base and field to be movable or copyable. The error names the field or base that is not. ``` '{X}' cannot have a defaulted copy constructor: field '{f}' of type '{T}' is move-only '{X}' cannot have a defaulted move constructor: field '{f}' of type '{T}' is not transferable '{X}' cannot have a defaulted copy constructor: base '{B}' is not transferable ``` ```kairo class Unique { @move fn Unique(self, other: Self) = default } class CopiesUnique { var u: Unique @copy fn CopiesUnique(self, const other: Self) = default // error SC129E: 'u' is move-only } ``` **Fix:** write the transfer constructor body yourself, change its kind, or `= delete` it. See [Classes](/docs/language/classes-lifecycle/#defaulted-moves-of-non-movable-members). --- ## Enums ### SC128E: an enum discriminant does not evaluate or does not fit A discriminant must be an integer constant expression whose value fits the enum's underlying type. The message says which part failed. ``` an enum discriminant must be an integer constant that fits '{T}'; this one does not evaluate: {reason} an enum discriminant must be an integer constant that fits '{T}'; it is {n}, which does not fit ``` ```kairo enum Small derives u8 { Top = 255, Past, // error SC128E: 'Past' is one past 'Top', so it is 256 } enum Order { A = Late, // error SC128E: 'Late' is declared below this variant Late = 1, } ``` **Fix:** use only literals, operators, `as` to an integer type, and earlier variants, and keep the value in range or widen the underlying type. See [Enums](/docs/language/enums-plain/#discriminant-values). ### SC130E: two variants of an enum have the same value ``` '{V}' has the same value as '{W}' ({n}) ``` ```kairo enum Flags { A = 1, B = 1, // error SC130E } ``` Imported C++ enums are exempt. **Fix:** give each variant a distinct value. See [Enums](/docs/language/enums-plain/#discriminant-values). ### SC001E: a constant cast into a closed enum is no variant's value `as` into a [closed](/docs/language/enums-plain/#closed-and-open-enums) plain enum with a constant that no variant has. The code is a placeholder until the error gets its own. ``` {n} is not a value of '{E}': a closed enum holds only its variants' values ``` ```kairo enum Color derives u8 { Red, Green, Blue } var c = 3 as Color // error SC001E: 3 is not a value of 'Color' ``` The note points at the enum. When the enum is declared in the same file, a fix-it inserts `@open` before its `enum` keyword. **Fix:** cast a value one of the variants has, or declare the enum `@open` if it is meant to hold other values. A non-constant operand is not an error: it is checked when it runs and crashes on a miss. ### SC001E: `@open` on something other than a plain enum ``` '@open' does not apply to an ADT enum: no cast makes its tag, so it is always closed '@open' does not apply to this declaration; only a plain enum can be open ``` The fix-it removes the attribute. ### SC001E: an unknown or misplaced attribute ``` unknown attribute '@fast_call' '@packed' applies only to a class, struct or union '@align' expects one integer literal that is a power of two, at most 268435456: '@align(16)' '@no_warn' 'SC001E' is an error; only a warning can be suppressed ``` No [attribute](/docs/language/attributes/#unknown-and-misplaced-attributes) is accepted and ignored: a name the compiler does not know, a built-in attribute where it does not apply, and a bad argument are errors. A note suggests a close built-in name; the fix-it removes the attribute. ### SC001E: a pack-expanded variant is malformed A [pack-expanded variant](/docs/language/enums-adt/#variadic-enums) `V { e: E }...` must have a payload that names the enum's type pack, must be the enum's last variant, and must be its only one. A pack named in a variant without `...` is the same error. The code is a placeholder until the error gets its own. ``` variant '{V}' is followed by ... but has no payload, so there is nothing to expand variant '{V}' is followed by ..., but its payload names no type pack of '{E}' pack-expanded variant '{V}' must be the last variant of '{E}' '{E}' already has a pack-expanded variant, '{V}'; an enum expands its pack once variant '{V}' names the type pack '{P}', but is one variant; add ... after it to make one variant per element of '{P}' ``` ```kairo enum R { Err { e: E }, // error SC001E: add ... after it Ok { v: T }, } ``` A fix-it removes a `...` that expands nothing, or adds the missing one. **Fix:** follow the variant that holds the pack with `...` and put it last. ### SC001E: no expansion of a pack-expanded variant fits A construction or a pattern names a pack-expanded variant, and its payload type picks no expansion, or several. A pattern must write the type on the binder of the pack field when there is more than one expansion; a fix-it writes the first one's. The note lists the expansions. ``` no '{V}' of '{T}' holds a '{U}' a '{U}' fits more than one '{V}' of '{T}'; the payload's type must pick one '{V}' is one variant per element of a pack in '{T}'; name the payload's type to pick one '{T}' has no '{V}' variant: its pack is empty ``` ```kairo enum Outcome { Ok { value: T }, Err { error: E }... } var o: Outcome = .Err { error: 1 } // error SC001E: an i32 fits both match o { case .Err(var error) { } // error SC001E: name the type, 'var error: i64' default { } } ``` **Fix:** give the payload a value of exactly one element's type, and write `var error: T` in the pattern. ### SC001E: a type pack or a pack parameter where one value or type is expected A type pack (`...T`) stands for several types and a pack parameter (`...xs: T`) for several values, so neither can be used as one. A pack is written expanded as an argument (`Box`, `f(xs...)`), as the type of a `...` parameter, or, for a pack parameter, iterated with `for`. The code is a placeholder until the error gets its own. ``` '{T}' is a type pack and stands for several types; a field cannot have it as its type '{xs}' is a pack of values with different types; pass it on expanded as an argument, or iterate it with a for loop a pack expansion is written only as a call argument, where it passes each element as its own argument only a pack parameter can be expanded ``` ```kairo class <...T> Holder { var xs: T } // error SC001E fn <...T> f(...xs: T) { var y = xs // error SC001E for x in xs { } // fine g(xs...) // fine } ``` **Fix:** expand the pack, or iterate it. ### SC123E: a variant name does not fit the expected type A `.V`, or a pattern head, must name a variant of the enum it is checked against. It covers construction as well as [`match` patterns](/docs/language/pattern-matching/#enum-variant-matching): `.V` with no expected enum type, `.V` against a type that is not an enum, a variant the enum does not have, a variant of another enum, a type that is not the matched type, and a name that is not a variant, a constant or a type. ``` '.{V}' names an enum variant, but nothing here gives it an enum type; write the enum's name before it '.{V}' names an enum variant, but the expected type is '{T}', not an enum '.{V}' names an enum variant, but the matched value is '{T}', not an enum '{E}' has no variant named '{V}' '{E}::{V}' is a variant of another enum; the matched value is '{T}' this pattern matches '{T}', but the matched value is '{U}' '{E}' is an enum; name one of its variants '{x}' is not a variant, a constant or a type, so it cannot be matched against; to bind the value to a new name, write 'var {x}' ``` ```kairo enum Dir { North, South } fn main() -> i32 { var a = .North // error SC123E: nothing gives '.North' an enum type var b: i32 = .North // error SC123E: 'i32' is not an enum var c: Dir = .East // error SC123E: 'Dir' has no variant named 'East' match 3 { case .North { } // error SC123E: the matched value is 'i32', not an enum default { } } return 0 } ``` **Fix:** give `.V` an expected enum type, or write the enum's name before it (`Dir::North`). See [Enums](/docs/language/enums/#shorthand-syntax). ### SC131E: a variant is built with the wrong shape A variant is built from its own payload: every field once, by name, in braces exactly when it has a payload. A field name the payload does not have is SC040E, as for a struct. ``` '{E}::{V}' carries a payload; give its fields in braces after the name '{E}::{V}' carries no payload; write it without braces '{E}::{V}' is missing field '{f}' field '{f}' of '{E}::{V}' is given twice ``` ```kairo enum Shape { Circle { r: i32 }, Rect { w: i32, h: i32 }, Empty } fn main() -> i32 { var a = Shape::Rect { w: 1 } // error SC131E: missing field 'h' var b = Shape::Rect { w: 1, w: 2, h: 3 } // error SC131E: 'w' given twice var c = Shape::Empty { } // error SC131E: no payload, no braces var d = Shape::Circle // error SC131E: a payload needs braces return 0 } ``` **Fix:** ```kairo enum Shape { Circle { r: i32 }, Rect { w: i32, h: i32 }, Empty } fn main() -> i32 { var a = Shape::Rect { h: 2, w: 1 } var c = Shape::Empty var d: Shape = .Circle { r: 3 } return 0 } ``` See [Enums](/docs/language/enums-adt/#construction). ### SC001E: a constructor does not initialize a field that has no default A field with no initializer whose type has no default (`bool`, an enum with payloads, a class with no default constructor, an array of any of these) is initialized by every constructor, like a `const` member: the constructor's first whole write of it is its initialization, and an array field may instead be built element by element, each element written once with a constant index. See [Classes](/docs/language/classes/#fields-without-a-default). The code is a placeholder until the error gets its own. ``` constructor of '{C}' does not initialize field '{f}', and {why} field '{f}' is not initialized on every path through the constructor of '{C}', and {why} '{f}' is written in part before it is initialized, and {why} a defaulted constructor of '{C}' cannot initialize field '{f}', and {why} array field '{f}' is initialized on some paths through the constructor of '{C}' only; an array is not assignable, so its one initialization must be on every path 'self' is used before the constructor has initialized its fields array field '{f}' is built element by element, but element 1 is (elements 1 and 3 are) not initialized on every path through the constructor of '{C}', and {why} element {k} of '{f}' may already be initialized here; each element is initialized exactly once before '{f}' is whole the index of an element write that builds '{f}' must be a constant index {k} is out of range for '{f}', which has {N} elements an element of '{f}' is initialized inside a loop; each element of an array field built element by element is written exactly once, with a constant index '{f}' is read before all of its elements are initialized: elements 1 and 2 are not initialized yet on every path ``` `{why}` says why the type has no default, the same reason a local gets (`'Frame' is an enum with payloads, so no variant is its default`). The note points at the field. Element by element, the messages name the elements still missing, the earlier write of a duplicate, or where the array started being built; a write into an element (`self.toks[0].n = 1`) or into an array of arrays does not build anything, and a note says so. ```kairo enum Frame { Burst { base: i32, count: i32 }, Idle } class Batch { var frames: [Frame; 3] fn Batch(self, c: bool) { // error SC001E: elements 1 and 2 are not initialized on every path self.frames[0] = .Idle if c { self.frames[1] = .Idle } } } ``` **Fix:** build the field on every path before any method call, whole (`self.frames = [.Idle, .Idle, .Idle]`) or one write per element; or give it an initializer at its declaration. An array field's one whole write in a constructor is its initialization, so a second one, one inside a loop, or one after an element was already built, is SC071E (`an array is not assignable; 'frames' may already be initialized here`). --- ## Panic These are the [panic](/docs/language/panic/) effect checks: every error a call or a `panic` may produce is handled with `try`/`catch` or propagated by a `panic` function. Messages name every type involved; a set is listed in a fixed order. ### SC001E: `unhandled panic: '{f}' may panic with '{E}', and '{g}' is not marked 'panic'` A call to a panicking function, or a `panic` statement, in a function with no `panic` specifier, where no enclosing `try` catches the types listed. Two fix-its: mark the function `panic` to propagate, or wrap the call in `try ... catch => crash!()` to handle it there. The same check applies to a closure (`... and the closure is not marked 'panic'`). ```kairo fn parse_port(s: string) panic -> i32 { ... } fn bad() -> i32 { return parse_port("8080") // error SC001E } ``` **Fix:** mark `bad` `panic`, or handle the error: `return try parse_port("8080") catch => 8080`. ### SC001E: `'{E}' is not in the declared panic set of '{f}'` A function (or closure) with a [declared set](/docs/language/panic/#declared-panic-sets) `panic(E1, E2)` panics with, or propagates, a type outside it. The note points at the callee the type comes from; the fix-it adds the type to the list. ```kairo fn load(path: string) panic(IOError) -> i32 { return parse_port(read_file(path)) // error: 'RangeError' is not in the declared panic set of 'load' } ``` ### SC001E: `'main' cannot panic` / `a panic cannot reach 'main'` `main` can never be `panic` (fix-it: remove it), and an error that would reach `main` unhandled is an error at the call that propagates it, with a fix-it handling it there or stopping the program with [`crash!()`](/docs/language/panic/#main-and-crash). A script's top-level code follows the same rule (`a panic cannot reach a script's top level`). ### SC001E: `'{f}' cannot be both 'panic' and '-> !'` A `panic` function returns its error to the caller; a `-> !` function never returns. Fix-it: remove `panic`. ### SC001E: `{what} cannot panic: it runs where no call is written, so nothing could handle the error` An `@implicit` conversion and `op panic` are called by the language where no call is written, so an error from them could never be caught. Fix-it: remove `panic`. ### SC001E: `a constructor cannot panic` / `a destructor cannot panic` No constructor (one with parameters, the default constructor, a transfer constructor) and no destructor (`op finally`) can [panic](/docs/language/classes-lifecycle/#constructors-and-destructors-never-panic): an object is built whole or not at all, and a destructor runs on every exit, where nothing could take an error. Marking one `panic` is `a constructor cannot panic: an object is either built whole or not at all` (or the destructor's reason), with a fix-it removing `panic`. A panic that would escape one's body is `a constructor cannot panic: '{f}' may panic with '{E}', which is not handled`, with fix-its handling it there or stopping the program with `crash!()`. For a constructor, a note says that construction which can fail belongs in a static factory function. ```kairo class Conn { var fd: i32 fn Conn(self, n: i32) { self.fd = open_fd(n) } // error: a constructor cannot panic static fn open(n: i32) panic -> Conn { return Conn(open_fd(n)) } // fine } ``` ### SC001E: `type '{T}' cannot be panicked: {why}` An error is returned and propagated by value, so a type a `panic` raises, a declared set names, or a `catch` names (`cannot be caught`) must be movable, complete, and a value: not a reference, not `void`. The reason says which rule failed, and a note points at the type. ```kairo class Pinned { fn Pinned(self) {} @move fn Pinned(self, other: Pinned) = delete } fn f() panic -> i32 { panic Pinned() } // error: it is not movable ``` ### SC001E: `a global's initializer cannot panic` / `cannot hold a 'try'` A global's (or static field's) initializer runs at file scope: there is no function for an error to propagate to, and no place for a `try`. Initialize it in a function instead. A field's default and a parameter's default may call a panicking function only inside a `try` that handles everything (`a field's default cannot panic: ...`). ### SC001E: `the panic set of ... must be declared` A bare `panic` where the set is a contract or has no body to infer from: a [function type](/docs/language/panic/#where-a-declared-set-is-required) (`the panic set of a 'fn' type must be declared`), an interface requirement, a `virtual` method of a base class, or a closure (`a closure's panic set must be declared`). Where there is a body, the fix-it writes the set it was inferred to be (or removes `panic` when nothing panics); otherwise a note says there is no body to infer from. ```kairo var retry = fn () panic -> string { return read_file("x") } // error: write 'panic(IOError)' ``` ### SC001E: `'{E}' is not in the panic set of '{Base::m}', which this overrides` / `implements` An [override](/docs/language/panic/#subsets)'s set must be a subset of the base method's, and a conforming method's a subset of the interface requirement's. The fix-it adds the type to the base's or the requirement's declared set. Overriding a method that does not panic with one that does is `an override cannot panic when '{Base::m}', which it overrides, does not`. A generic base's or interface's set is read at the arguments the class derives it at or conforms to (`class D derives Base` holds `run` to `Base::run`'s `panic(T, A)` as `panic(B, A)`), and then no fix-it is offered: the base's own list names its parameters. ### SC001E: `'{f}' is used as a value, but its panic set is inferred` A function value's type carries its panic set (`fn() panic(IOError) -> i32`), and a set inferred from the body is not known when the value's type is given. Declare it; the fix-it writes the inferred set. Converting between function types follows the [subset rule](/docs/language/panic/#subsets): a function whose set is not a subset of the target's is a type mismatch (`cannot convert 'fn () panic(E, F) -> i32' to 'fn () panic(E) -> i32'`). ### SC001W: `the panic set of public function '{f}' is inferred ({E}); declare it ...` Only when building a library (`--shared`): a `pub` function's inferred set is API surface that changes when the body does. The fix-it writes the set. ### SC001W: `this arm never runs: '{T}' is not in the panic set of its 'try' (...)` A `catch e: T` whose `T` the `try` body cannot panic with. A warning, not an error, so that a library removing an error from a function's set does not break callers that still catch it. The fix-it removes the arm. Arms match [exact types](/docs/language/panic/#arms-match-exact-types): `catch e: Base` does not catch a `Derived`. A C++ type outside the set is a [C++ exception](/docs/language/c-cpp-exceptions/#exceptions) arm and is never reported. ### SC001W: `'finally' runs when the enclosing block exits, like any 'finally', not when the 'try' before it finishes` A `finally` written directly after a `try`/`catch`, on the line of its closing brace (`} finally {`) or the next, is the ordinary [scope-exit `finally`](/docs/language/panic/#finally): it runs when the enclosing block is left, after whatever follows it in the block, and a `return`, `break` or uncaught panic leaving the `try` never reaches it, so it does not run on that path. A note points at the closing brace where it runs, another at the `try`. There is no fix-it, since no edit keeps the meaning and silences it. To clean up as soon as the `try` is done and on every way out of it, register the `finally` first, in a block of its own: `{ finally { ... } try { ... } catch { ... } }`. ### SC001W: `'{p as *D}' crashes the program when the object is not a '{D}'; use '{p as *D}?' and test the result for cleaner handling` Every [asserting downcast](/docs/language/casting/#downcasting-base-to-derived) warns: on the wrong dynamic type it crashes the program (it is not a panic and cannot be caught). The fix-it appends `?`, turning it into the checked downcast, which yields null on a miss. ### SC001E: `a second 'catch' arm for '{T}'` / `no 'catch' arm may follow a bare 'catch'` Two arms for the same type, or any arm after a bare `catch` (which has already handled everything), are errors with a fix-it removing the arm. In the expression form an arm after the default is a syntax error (S054E). ### SC001E: `two 'catch' arms of one 'try' catch '{T}' in '{f}': the first takes every '{T}', and the second never runs` In a [generic function](/docs/language/panic/#generic-functions), two arms that name different types in the body (`catch e: T` beside `catch e: Missing`) catch the same type at some instantiation (`T = Missing`). Reported where that instantiation is used, with notes at both arms and, when a generic body reached the instantiation, one note per call in the chain. Catch the parameter's type in its own function, or bound the parameter so the two cannot meet. ### SC001E: `the panic set of '{f}' grows without bound: it calls itself (or a function that calls it) at ever-larger type arguments` A [generic function](/docs/language/panic/#generic-functions) whose inferred set includes what a recursive call at a larger type raises (`f(Box { v: x })` inside `f` lets `Box` through, which lets `Box>` through, and so on). Declare the set, and catch what the recursive call adds outside it. ### SC001E: `'catch' of the C++ exception '{T}' in a build without C++ exceptions (-fno-exceptions, or a target with no OS)` A `catch e: T` arm whose `T` is a C++ type outside the `try` body's panic set [catches a C++ exception](/docs/language/c-cpp-exceptions/#c-to-kairo), which needs C++ exceptions. They are off with `-fno-exceptions`, and by default for a target with no OS (or `--freestanding`). A note points at the C++ type; the fix-it removes the arm. The code is a placeholder until the error gets its own. **Fix:** remove the arm, or build with `-fexceptions`. ### SC001E: `'op panic' takes 'const self'` / `'op panic' must return 'string'` [`op panic`](/docs/language/operator-overloading/#op-panic) is optional, but when a type defines it, it is `fn op panic (const self) -> string`. Fix-its insert `const` and write `string`. An operand besides `self` is SC055E (`'op panic' takes no operand besides the receiver`). ### S055E: `an explicit panic set names at least one error type` `panic()` with nothing inside, in a function header, a closure or a function type. A bare `panic` already means an inferred set. Fix-it: remove the parentheses. ### SC001E: `'{A}' and '{B}' cannot be in one panic set: both have type id 0x{id}` Every error type has a 32-bit type id, the tag its errors are stored with, computed from the type's full name so every file agrees on it. Two types whose ids are equal cannot be in one panic set: their errors would be indistinguishable. This is astronomically rare; it is reported where the set is formed, with a note at each type. The code is a placeholder until the error gets its own. One case is not rare: two builtins that are the same C++ type on the target. `usize` is C++'s `size_t`, which is `u64` on most 64-bit targets (and `u32` on 32-bit ones); `isize` likewise is `i64` or `i32`. On such a target the pair has one type id, and the message says so instead: `'usize' and 'u64' cannot be in one panic set: on this target both are the C++ type 'unsigned long', so their tags are one`. Where `size_t` is a type of its own (Darwin), the two can share a set. **Fix:** rename one of the two types, or keep them in different sets (handle one of them before the other propagates). For a builtin pair, panic with one of the two, or wrap one in a struct. ### OPT001R: `'{Panic}' is {n} bytes, so a function returning it returns through memory, not in two registers` A remark, not a warning. A panicking function's result is returned in two registers while it is at most 16 bytes: the tag and site word, plus a payload of at most 8 bytes. One wider error type (or a wider return type) makes every function with that set return through memory: correct, just slower. The remark names the widest payload. The code is a placeholder until the remark gets its own. **Fix:** nothing is required. To keep the fast path, panic with a small error (an id, or a pointer to the details). --- ## Imports ### R068E: plain import reaches a file beside the importer `'{util}' is not in any library or search directory; it is the file beside this one, which a plain import no longer reaches: write 'self::{util}'` A plain `import util` looks only in the libraries and search directories ([Resolution Semantics](/docs/language/imports/#resolution-semantics)). None of them holds `util`, but the importing file's directory does, which older compilers searched first. The import still resolves to that file, with this error and a fix-it that inserts `self::`. ```kairo // app/main.k, with app/util.k beside it ``` **Fix:** apply the fix-it, or write `module::util` for a file at the module root. --- ### R069E: `cannot import 'module::{x}': this file is in no module` `import module::x` resolves from the importing file's [module root](/docs/language/imports/#module-imports), the nearest directory at or above it that holds a `module.k`, and there is none. A note (R069N) says what is missing. **Fix:** add a `module.k` (an empty one is enough) to the directory that should be the module root, or write `import self::x` for a file beside this one. --- ### R005E: `ambiguous module '{x}': both '{x.k}' and '{x/module.k}' are that module` The one place the import looks holds both a file `x.k` and a library entry `x/module.k`, and each would be module `x`. The file answers, so the import does not also fail, but the layout is an error. **Fix:** rename or remove one of the two. --- ### S089E: `'import module foo' was removed` `import module foo` (with a space) forced the library form of a module. Each import form looks in one place where a file and a library entry with one name are already an error, so the form is gone. A fix-it deletes `module`, and the line is then read as a plain `import foo`. **Fix:** apply the fix-it and pick the form for where `foo` is: `import foo` (a library or search directory), `import self::foo` (beside this file) or `import module::foo` (from the module root). --- ### S090E: `the destructor is spelled 'fn op finally(self)'; 'op delete' is no longer a destructor` Since 0.2.0 the [destructor](/docs/language/classes-lifecycle/#destructors---op-finally) is `fn op finally(self)`. The old `fn op delete(self)` (and `x.op delete()` in an expression) is an error with a fix-it that renames `delete` to `finally`. **Fix:** apply the fix-it. --- ### S091E: `Kairo has no 'delete' expression` Running a destructor and freeing memory are separate steps. Memory from `@create` is freed with `@destroy p` (the fix-it), which runs the destructor and returns the block to the allocator it came from. Memory C++ allocated is freed with `@cxx::delete p`, or `@cxx::delete [] p` for an array (the fix-it for `delete [] p`). `x.finally()` (run a destructor early without freeing) is planned for 0.3 and is an error until then. See [Freeing memory](/docs/language/classes-lifecycle/#freeing-memory). **Fix:** apply the fix-it, or use `@cxx::delete` for C++ memory. --- ### SC149E: `a class cannot declare its own allocator ('op new')` A `static fn op new` / `static fn op delete` pair would give a class its own allocator, which breaks the pairing every `@create` / `@destroy` and every C++ `delete` of a Kairo object relies on. Kairo does not allow it. **Fix:** remove the operator; allocate from a pool through the [allocator interface](/docs/language/allocators/) (`create_in`), a scoped allocator, or `@set_global_allocator`. --- ### R016E: `ambiguous import: '{name}' names more than one non-function symbol` One imported name refers to more than one thing that is not a function, for example two types imported from two modules. Functions merge into one overload set; other declarations cannot. ```kairo ``` When a Kairo import is involved, the error is reported at the import. When every candidate comes from C or C++ headers, it is reported where the name is used, as C++ does, and a note points at each candidate and says what it is (variable, typedef, struct, ...). Importing such headers is not an error by itself. A header struct and a variable or function with the same name are not ambiguous: the name means the variable or function, and the struct can be named with `ffi "c" struct T`. See [Tags and ordinary names](/docs/language/c-cpp-calling/#tags-and-ordinary-names). **Fix:** import one of the conflicting names under an alias (`import Foo::{Bar as FooBar}`), or import a header under an alias (`ffi "c++" import "a.h" as a`) and qualify the name. --- ### R001W: import cycle `import cycle: {a.k -> b.k -> a.k}; a cycle hinders maintainability: no module on it can be read, built or tested without the others` (for a file that imports itself: `'{s.k}' imports itself; ...`) Modules import each other in a cycle: `a` imports `b` and `b` imports `a`, a longer chain, or a file that imports itself ([Circular Dependencies](/docs/language/modules/#circular-dependencies)). The cycle compiles; the warning sits on the import that closes it, a note points at each import on the cycle, and a last note suggests a third module. For a self-import, a fix-it removes the import instead: a file sees its own declarations without importing itself. The code is a placeholder until the warning gets its own. ```kairo // a.k // b.k ``` Under `-fno-import-cycles` the same diagnostic is the error **R001E** (`...; import cycles are disabled (-fno-import-cycles)`), and the build stops after parsing. `-Werror` promotes the warning; `-w` silences it. **Fix:** move what both modules need into a third module that each imports. --- ## Access ### SC001E: `{kind} '{m}' of '{T}' is private` / `... is protected` Using a `priv` member outside the file that declares its class, or a `prot` member outside that file and outside a subclass. Operators count: `a + b` uses `op +`. The fix-it makes the member `pub`. ### SC001E: `protected {kind} '{m}' of '{B}' is reached here through a '{X}', not through '{D}' or a class deriving from it` A subclass `D` in another file used an instance `prot` member of its base through an object that is not a `D` (a `*B`, or a sibling subclass): ```kairo class Counter derives Base { fn via_base(self, b: *Base) -> i32 { return b->hits } // error SC001E } ``` Reach it through `self` or another `Counter`, or make the member `pub`. ### SC001E: `this constructor of '{B}' is protected: a class deriving from '{B}' calls it only as a base initializer, not to build a separate '{B}'` A subclass in another file built a standalone object with a `prot` constructor (`var b = Base(5)`). Only `Base::Base(self, ...)` at the start of the subclass's constructor may call it. ### SC001E: `'{X}' does not conform to '{I}': its '{m}' is not public, and its file declares no 'impl {I}'` A `priv` or `prot` member satisfies an interface requirement only when its type's own file declares the conformance. Declare `impl I` on the type (or `extend X impl I` in its file), or make the member `pub` (the fix-it). ### I003E: `the emitted C++ refuses an access Kairo accepted ...` An internal error: Kairo admitted a member access and the generated C++ refused it. It names clang's own message. Please report it with the source; meanwhile making the member `pub` works around it. --- ## Members ### SC001E: `'&null' cannot be stored in '{T}': a safe pointer is never null` `&null` where a value lands in a safe pointer `*T`: a variable's or field's initializer, an assignment, an argument, a default argument, a `return`, a struct literal's field, an `if` arm or the fallback of `??`. A `*T` always points at something ([Pointers](/docs/language/pointers/)). The code is a placeholder until the error gets its own. ```kairo var p: *i32 = &null // error SC001E fn give() -> *i32 { return &null } // error SC001E ``` The note points at the declared type of the variable, field, parameter or return and names both ways out; the fix-it makes that type nullable (`*i32?`). A call through a `fn` value has no declaration to point at, and gets the note alone. Comparing a `*T` with `&null` is not this error. **Fix:** declare the pointer `*T?` if it may be absent (its null is `null`, and `&null` converts to it), or `unsafe *T` for a raw pointer that may hold the null address. ### SC001E: `'{f}' is a named function declared in a body, and cannot use '{x}' from the function around it` A function declared inside another function's body (a local `fn`, or a method of a local class) uses a local, a parameter, `self` or a `static` local of an enclosing function. A named function captures nothing ([Closures vs Inner Functions](/docs/language/closures/#closures-vs-inner-functions)). Each use is reported once, by the innermost function that makes it. The code is a placeholder until the error gets its own. ```kairo fn outer() -> i32 { var x = 10 fn inner(y: i32) -> i32 { return y + x } // error SC001E return inner(1) } ``` The note points at the binding. **Fix:** pass the value as a parameter, or use a closure. ### SC001W: `nested type '{N}' of '{T}' is named without a qualifier; write 'Self::{N}' so it reads as a member` A nested type, type alias (`type alias '{N}'`) or associated type (`associated type '{N}'`) of the enclosing type, named bare inside its body. It is legal, the one exception to [Members always need a qualifier](/docs/language/classes/#members-always-need-a-qualifier), but nothing at the use says the name is a member. Warned in type and expression position, in a class, struct, union or interface body, an `extend` block, an out-of-line `fn Type::method` and a closure in any of those. The code is a placeholder until the warning gets its own. ```kairo class Tree { struct Node { var value: i32 } fn root(self) -> i32 { var n = Node { value: 0 } // warning SC001W: write 'Self::Node' return n.value } } ``` The note points at the declaration, and a fix-it inserts `Self::`. Only the innermost type counts: inside a nested type, its own name and the members of the type around it are not warned. Nested modules are not warned. **Fix:** write `Self::Node`. ### SC001E: `'{f}' is a static requirement; it takes no 'self' and is called through the type, not a value` A static [interface requirement](/docs/language/interfaces-requirements/) (one with no `self`) called through a value: `y.make(2)` on `y: T` with ``. The same error reads `static extension member` for a static method added by an [`extend`](/docs/language/extends/) block. A requirement dispatches on the type, so a value names nothing to call it on. A plain class's `static` method called through a value is not an error. The code is a placeholder until the error gets its own. ```kairo interface I { fn make(x: i32) -> i32 } fn f(y: T) -> i32 { return y.make(2) // error SC001E: write 'T::make(2)' } ``` The note points at the declaration, and a fix-it replaces the receiver with its type: `T::make(2)`. **Fix:** call it through the type. ## Generics ### R051E / R025E: `'{op}' on '{T}' needs a bound that declares '{requirement}'` A generic body uses an operator, a conversion or an interpolation on a value of a type parameter that nothing grants. The body is [checked once against its bounds](/docs/language/generics/#type-parameter-constraints), so the error is at the use, in the generic, whatever the generic is later used with. R051E when the parameter has no bound at all (a note points at it: `'T' is declared with no bound`); R025E, ending `; none of the bounds of 'T' does`, when it has bounds and none declares the requirement. The forms: `'==' on 'T' needs a bound that declares 'op =='` (`!=` names `op !=` or `op ==`, a relational `op <=>`, `+` `op +=`, `+=` `op +`), `'===' on 'T?' compares the values with 'op ==', so it needs a bound on 'T' that declares 'op =='`, `'as string' on 'T' needs a bound that declares 'op as' returning 'string'`, and `formatting a 'T' needs a bound that declares 'fn repr(self) -> string' or 'op as' returning 'string'`. ```kairo fn eq(a: T, b: T) -> bool = a == b // error R051E interface Same { fn op ==(const self, other: Self) -> bool } fn eq2(a: T, b: T) -> bool = a == b // ok: the bound's 'op ==' ``` A null test on a `T` (`t?`, `t == null`) is the ordinary "is not nullable" error: a `T` is never null. **Fix:** bound the parameter with an interface that declares the operator, or take the value at its concrete type. The same pair reports a type parameter passed to a bounded generic without the bound: `'{f}' needs '{T}' to implement '{I}'`, at the call, with a note at the callee's bound. R051E carries a fix-it adding `impl {I}` to the parameter. A bound that derives `{I}` meets it, and a forwarded pack (`print_all(args...)`) is held to the same rule per element. ```kairo fn one(x: T) -> string = x as string fn fwd(x: T) -> string = one(x) // error R051E fn fwd2(x: T) -> string = one(x) // ok ``` ### SC001E: `a value of type '{T}' can only be matched by a binding, '_' or 'default' (with a 'where' guard)` A `match` pattern other than a binding or `_` on a value of a type parameter. No bound gives `T` variants, fields or values a literal could equal; a note points at the parameter. The code is a placeholder until the error gets its own. **Fix:** bind the value and test it in a `where` guard through a bound's requirement, or match on a type whose variants are known (a generic ADT `Rep` is fine). ### SC001E: `'{X}' does not conform to '{I}'`, in an instance a generic reached A bound is checked where it meets a concrete argument, including in an instance that only another generic's body asks for: `outer` calling `inner(Wrap { item: a })` instantiates `inner>`, and its `U impl Named` bound is checked with `U = Wrap`. The error is at the use that started the chain, the one written in your code. Notes name the bound and the missing requirement, then one note per step of the chain, innermost first, at the call in the generic's body that needed the instance: ```kairo pub fn inner(a: U) -> i32 { return a.name_len() } pub fn outer(a: T) -> i32 { return inner(Wrap { item: a }) // note: in instantiation of 'inner>' required here } fn main() -> i32 { return outer(Metric { base: 3 }) // error SC001E: 'Wrap' does not conform to 'Named' } ``` A chain longer than five steps shows the innermost three, a note counting the steps left out, and the outermost two. `--cmax-generic-backtrace=N` changes the five; `0` shows every step. An instance that fails is reported once, at the first use that needs it. The code is a placeholder until the error gets its own. **Fix:** make the argument conform (an extension can add the missing member to `Wrap`), or bound the outer generic so the call cannot be made with it. ### SC001E: `cannot decide whether a partial specialization of '{X}' applies to these arguments` A [partial specialization selected by `requires`](/docs/language/requires/#partial-specializations-selected-by-requires) matches an instantiation by its pattern, but its clause needs something the compiler does not compute while choosing (the `sizeof` of a struct, an `eval` function). It is not chosen, and the use is an error; a note points at the partial. Two partials that both apply with neither more specialized are `ambiguous partial specializations of '{X}' for these arguments`. The codes are placeholders until each gets its own. **Fix:** select by the pattern instead, or test a builtin type's size. ### SC001E: `every overload in the 'where' dispatch of '{f}' must have the same {what}; C++ sees them as one function` Besides the return type and `const self`, a [`where` group of generic functions](/docs/language/where/#fallback-requirement) must agree on its type parameters' names and its bounds (`generic parameter names`, `bounds`). A second overload with no `where` clause is R029E, a redefinition. ### SC001E: `instantiation depth exceeds {n}: ...` Each instance a generic body reaches can reach more. A chain that never ends, such as a function that calls itself with its argument wrapped once more, is reported once it is longer than `--cmax-generic-depth` (128 by default), at the use that started it. The message names the first three and the last three instances of the chain, and a note points at the call that would have gone one step deeper. ```kairo pub fn f(x: T) -> i32 { return f(Wrap { item: x }) // note: 'f...>>' is required here, instantiation 129 of the chain } fn main() -> i32 { return f(1) // error SC001E: instantiation depth exceeds 128: 'f' -> 'f>' -> ... } ``` A pointer to the class itself at a bigger argument (`var p: *L>` in `L`) is reported the same way today, although following a pointer instantiates nothing. The code is a placeholder until the error gets its own. **Fix:** end the recursion at a fixed type (dispatch on a value instead of a type, or stop wrapping), or raise the limit with `--cmax-generic-depth=N` when the chain is finite and just long. ## Compile-Time Values The errors of [array lengths and generic value arguments](/docs/language/generics/#computed-lengths-and-arguments) that are computed at compile time. The codes are placeholders until each gets its own. ### SC001E: `an array length can call only 'eval' functions; '{f}' is not 'eval'` A length or value argument is computed at compile time, so a function it calls must be `eval`. A note points at the function; when it is yours, the fix-it adds `eval`. (`a generic value argument can call ...` is the same for an argument.) ### SC001E: `'{T}' cannot be the type of a generic value parameter: {why}` An [eval class](/docs/language/generics/#eval-classes-as-value-parameters) used as a value parameter's type must be structural: `{why}` names the first field that is not `pub`, is `mutable` or points to mutable memory (through nested fields: `its field 'inner' is a 'Hidden', and its field 'secret' is not 'pub'`), or the first of its constructors that is not `eval`, or a destructor. A note points at it. ### SC132E: a declaration-scope `eval if` depends on a type parameter An [`eval if`](/docs/language/eval/#eval-if) outside a function body chooses which declarations exist. A generic is emitted as one C++ template for every instance, and C++ has no `if constexpr` at class scope, so a generic's members cannot differ from one instance to another. A condition that reads a type parameter (`is_trivially_copyable!(T)`, `sizeof T`) would need exactly that. ```kairo class Holder { eval if is_trivially_copyable!(T) { // error SC132E: depends on T var fast: T } else { var slow: *T } } ``` A condition inside a generic that names no parameter (`is_trivially_copyable!(Plain)`, `sizeof usize < 8`) is decided once, after types are resolved. The note (SC132N) spells the partial specialization to write instead. **Fix:** select a type: declare each member set as a partial specialization chosen by a `requires` clause (`class Holder requires `). In a function body an `eval if` on a type parameter is `if constexpr` and needs no change. --- ## Not Yet Supported ### SC116E: a feature is not yet supported The construct is part of the language but the current compiler does not handle it yet. The message names it: ``` {what} is not yet supported ``` It is reported for: - `for ... in` over a Kairo `string` (`iterating a string is not yet supported`); vectors, sets, maps, slices, arrays and ranges work - `label!` and `jump!` in user code - `x.finally()` and `x.op finally()`, the explicit early destructor call (`'finally()' is not implemented yet (planned for 0.3)`); a local is destroyed at the end of its scope and a heap object with `@destroy` - matching a string against a pattern that isn't a string literal or a constant initialized with one - matching a record value against a literal-style pattern - an initializer on an `eval` array-typed field (`eval E: [i32; 2] = [1, 2]`) - in a constructor that initializes a `const` field or a field without a default: a constructor with an expression body; `try`, `finally`, an `inline` block, `label!` or `jump!` before the last such initialization; a `static` or array local declared before it and used after it - a vector, set, map or f-string in an `eval` context (`a vector in an eval context is not yet supported`); a string literal is fine - an array length computed by C++ from an `eval` constant of the field's own class (`an array length computed by C++ from 'J', an 'eval' constant of the field's own class, is not supported`): inside its own body the class is incomplete. A note points at the constant; the fix-it moves it to module scope - an array length or generic value argument that calls an `eval fn` (or reads an `eval` constant computed by one) in a declaration's type, a field or a signature (`... is not yet supported in a declaration's type; write it inside a function body, or make the constant fold`); inside a function body it is accepted - a generic value parameter whose type is neither an integer nor an eval class (``) - a generic record's field default that reads another field - an attribute applied to an expression other than `@create T(args)` and `@destroy p`, which compile (`the expression attribute '@likely' is not yet supported`); the initializer form `@create T{...}` is rejected too - `@unreachable`, and a user-defined attribute macro (`the attribute macro '@trace' is not yet supported: attribute macros are not expanded yet`) - building or matching a [pack-expanded variant](/docs/language/enums-adt/#variadic-enums) at a type that depends on a generic parameter, and a pack-expanded variant's field whose type is built from the pack (`e: *E`) - naming the panic result type `Panic` in source (`a panic result type cannot be named yet`): a panicking call's result is handled with `try` or propagated, not stored - keeping a panic result in a variable (`a stored panic result is not yet supported`), such as `var copy = e` for a bare `catch e`'s binding (re-panicking it with `panic e` is fine), and a function type whose panic set names a generic parameter - a `for` loop over a panicking `op in`, a call of a panicking `op []` that returns a pointer (`a call of a panicking place operator ('op []' returning a pointer) is not yet supported`), a cast through a panicking `op as` (`a call of a panicking 'op as' is not yet supported`), and `===` through a panicking `op ==`. Any other panicking operator is called like a function, its derived forms (`!=` from `==`, `<` from `<=>`, `+=` from `+`) included - a method that implements two interface requirements, or overrides a method and implements a requirement, whose panic sets differ (`a method meeting both 'Source::read' and 'Stream::read', whose panic sets differ, is not yet supported`), with a note at each. Equal sets, written in any order, are fine - a panicking interface requirement whose result names `Self` (`fn add(const self, o: Self) panic(E) -> Self`: `a panicking interface requirement whose result names 'Self' ('add') is not yet supported`); a requirement with a concrete result works, through a bound too - a generic `panic` closure, a `panic` generator or `async` function or closure, and a `panic` statement or a call that may panic inside such a body (bounded and unbounded generics are [supported](/docs/language/panic/#generic-functions)) - a call whose callee's panic set names a generic parameter the call does not bind (no bound declares the requirement it calls) - a `fn`, class, struct, union or enum declared in a function body that uses a generic parameter of the function or class around it (`'echo' is declared in a body and uses 'T', a generic parameter of 'wraps'; that is not yet supported`); a note points at the parameter. One that is generic in its own right, or names no outer parameter, compiles - an `extend` in a function body - [`where` dispatch](/docs/language/where/) on a generic function with a pack parameter, a `virtual` or `override` method, an `extend` member, an operator, a constructor, an out-of-line definition, a forward declaration, a generator, an `async` function, a variadic function, or an overload with a default argument (`'where' dispatch on a generic function with a pack parameter is not yet supported`) It means "not yet supported", not "invalid": the code is correct Kairo that the current compiler cannot build. ```kairo struct P { var x: i32 var y: i32 } fn by_name(p: P) -> i32 { var {x, y} = p // error SC116E return x + y } ``` > [!NOTE] > For struct destructuring, read the fields one by one: `var x = p.x`. **Fix:** rewrite around the construct for now. See [Status](/docs/status/). --- ## Scripts The errors of [script mode](/docs/language/modules/#scripts): a file with top-level statements and no `fn main`. ### `script variable '{x}' is read before the line that gives it a value has run` A top-level variable whose initializer is not a constant gets its value at its own line. Reading it in the top-level code above that line, or in its own initializer, reads a value that does not exist yet. A note points at the line. ```kairo fn load() -> i32 { return 1 } println(f"{count}") // error: read before its line var count = load() ``` **Fix:** move the read below the line, or give the variable a constant initializer. ### `'{f}' reads script variable '{x}' before the line that gives it a value has run` A top-level call, made above `x`'s line, of a function in the file that reads `x` on every path. Notes point at the read and at the line. A function that reads it only on some path, or through another function, is not reported: that read is checked when it runs, and stops the program with `script variable '{x}' used before its line ran ({file}:{line})`. **Fix:** call the function after the line. ### `this 'jump!' crosses the line that gives script variable '{x}' its value` A top-level `jump!` whose path passes over a line whose initializer runs there: forward, the initializer would be skipped while the reads after the label assume it ran; back, it would run again. Notes point at the line and at the label. (A `jump!` written by the user is also [SC116E](#sc116e-a-feature-is-not-yet-supported) for now.) ### `a file with 'fn main' cannot also have top-level statements; 'main' is where the program starts` The statements would never run. A note points at `main`. **Fix:** move them into `main`, or delete `main` to make the file a script. ### `a top-level statement runs only in the program's root file; this file is imported as a module` Only the file the program starts from runs top-level statements. An imported module, or a `.k` file included from C++, runs none. **Fix:** move the statement into a function, or into the file the program starts from. ### `two script files in one program: '{a}' and '{b}' each run top-level statements as 'main'` Every command-line input may be a script, and each script is a `main`, so two in one link are two programs. Reported at the second script's first statement, with a note at the first's. Compiling them with `-c` and no link is not an error. ### `a top-level 'return' gives the program's exit status, an integer; this value is a '{T}'` A top-level `return` returns from the script's `main`: bare it returns `0`, and a value must be an integer. ### `'{x}' redefined` A name defined twice in one scope; at the top level that includes two bindings of one name, whatever keyword declares each (`static count` and `var count`). A note points at the first. When both are file-scope bindings, a fix-it renames the second to the first free `{x}2`, `{x}3`, ...; a duplicate field or local gets the error and the note only. --- ## Control Flow ### SC003W: unreachable code Message: `unreachable code; the statement above always transfers control out of this block` A statement can never run because the one before it in the same block always leaves: a `return`, `break`, `continue`, `panic` or `jump!`; a call to a function that returns `!`; an `if` with an `else` whose every branch leaves; an exhaustive `match` whose every arm leaves; or an infinite `loop` / `while true` that no `break` exits. ```kairo fn stop() -> ! { loop { } } fn f(c: bool) -> i32 { if c { return 1 } else { return 2 } return 3 // warning SC003W } fn g() -> i32 { stop() return 0 // warning SC003W } ``` One warning covers the whole dead run of statements, up to the end of the block or the next `label!` (a `jump!` target makes what follows it reachable again). A note points at the statement that leaves. A `return` inside a closure ends only the closure, so code after the closure is not affected. A `match` arm that can never match is reported separately, as SC121E. The top level of a [script](/docs/language/modules/#scripts) is a block too: code after a top-level `return` is reported. A declaration between the statements (a function, a type, a binding with a constant initializer) is never dead code and is left out of the warning and its fix-it; the dead code after it gets a warning of its own. **Fix:** delete the dead statements (the fix-it does), or move them above the statement that leaves. See [Control Flow](/docs/language/control-flow/). --- ## Const Lint (opt-in) These warnings are off by default. Turn them on with `-Wconst-self`. Each comes with a fix-it, so a whole tree can be updated in one pass. ### SC273W: a method never mutates `self` Message: `method '{f}' never mutates 'self'; declare it 'const self'` The method takes `self`, but nothing in its body changes the object. Every use of `self` reads a field, calls a `const self` method, or passes the object somewhere it is only read. A call to another method of the same file that this warning also finds counts as a read: the methods are decided together. ```kairo class Counter { var n: i32 = 0 fn get(self) -> i32 { return self.n } // warning SC273W fn twice(self) -> i32 { return self.get() * 2 } // warning SC273W: get() only reads fn bump(self) { self.n += 1 } // no warning: writes self.n } ``` No warning for a method that writes a field, calls a method that is not `const self` and is not found const-able itself, takes `&self`, or uses `self` inside a closure. Also none for a constructor, `op finally`, an assignment operator, a `virtual` or `override` method (or any method of a class with a polymorphic base), a method of a type or extension that implements an interface, a generic method or a method of a generic type, and an out-of-line definition. **Fix:** write `const self` (the fix-it inserts `const`). ### SC274W: an `@inout` parameter is never mutated Message: `'@inout' parameter '{x}' is never mutated; declare it 'const'` `@inout` tells callers the function may change the argument, so each caller has to pass a mutable place. This body only reads it. `const` passes the argument without a copy too, and a caller may then pass a constant or a temporary. ```kairo fn total(@inout xs: [i32]) -> i32 { // warning SC274W var s = 0 for x in xs { s += x } return s } ``` A by-value parameter of a record type that is never mutated is SC224W, which is on by default. **Fix:** replace `@inout` with `const` (the fix-it does), then drop the `&` at each call: `total(&v)` becomes `total(v)`. The fix-it edits only the declaration, so the calls report an error until they are changed. --- ## Generators ### SC290E: a destructor cannot be `eval` `eval fn op finally` is rejected: a compile-time object is never destroyed, and C++ has no constant-evaluated destructor to map it to. ### SC291E: a constant index past a fixed array's extent `index {k} is out of range for '[T; N]', which has N elements`. A constant index into a fixed array is checked at compile time; valid indices are `0..N-1`. ### SC292E: a kind bound is not met `'T' is not a class, so it cannot be 'T'`. A generic parameter bounded `: class`, `: struct`, `: enum` or `: union` was given an argument of another kind. The note points at the bound. SC249E also covers a by-value parameter, return or field of an abstract class, and SC227E a by-value parameter of a record that is only forward-declared. ### SC111E: `yield` where nothing can yield `yield` is allowed only in a function declared `-> yield T`. It is an error outside a function, inside a closure, or in a function with any other return type. ```kairo fn count() -> i32 { yield 1 // error SC111E return 0 } ``` **Fix:** declare the function `-> yield T`, or remove the `yield`. See [Generators](/docs/language/functions-generators/#generators). ### SC112E: this kind of function cannot be a generator `main`, constructors, destructors (`op finally`), `eval` functions, C-variadic functions, and functions returning `!` cannot be declared `-> yield T`. ```kairo fn main() -> yield i32 { } // error SC112E ``` **Fix:** move the sequence into a separate `-> yield T` function and call it from here. --- ## Portability ### P003E: a primitive type is not available on the target `f80` exists only where the target ABI's `long double` is x87 extended precision. The error names the target and what its `long double` is. **Fix:** use `f64` where `long double` is binary64, or `f128` where it is binary128. See [Primitives](/docs/language/primitives/#f80-follows-the-targets-long-double). ### P007E: bundled sysroot for the target is malformed A `--target` matched a folder under `/sysroot/`, but the folder is not a directory, has no `SYSROOT.toml`, or the manifest does not parse. A note says which. **Fix:** restore the manifest by re-extracting the sysroot, or remove the folder to fall back to `--sysroot`. See [Cross-compilation](/docs/language/c-cpp-toolchain/#cross-compilation). --- ## Value Arms The value forms of `if`, `match`, and `try`. See [Control Flow](/docs/language/control-flow/#if-as-an-expression-ternary-equivalent). ### S073E: braced value arm in an 'if', 'try' or 'match' expression Messages: - `value arms are written '=> expr'; '{ }' arms are statement-only` #### value arms are written '=> expr' the expression forms of `if`, `try` and `match` give each arm its value with `=>`. a `{ }` after a control keyword is always a statement block, so braces cannot hold an arm's value. `=>` introduces exactly one value expression. ##### example ```kairo var z = if a == b { 2 } else { 0 } // error var n = try { parse(s) } catch { 0 } // error var k = match s { case 2 { x + y } default { 0 } } // error ``` ##### how to fix replace each `{` with `=>` and drop its `}`; the fix-it does this when the braces hold a single expression: ```kairo var z = if a == b => 2 else => 0 var n = try parse(s) catch => 0 var k = match s { case 2 => x + y default => 0 } ``` an arm that needs several statements belongs in the statement form (`if c { ... }`, a statement-form `match`), or in a `({ ... })` statement expression. to `try` a brace expression such as a set literal, parenthesize it: `try ({1, 2}) catch => {}`. ### S074E: expected '=>' before a value arm Messages: - `expected '=>' after condition` - `expected '=>' after 'else'` - `expected '=>' after pattern` - `expected '=>' after catch arm` #### expected '=>' in the expression forms of `if`, `try` and `match`, the condition, the `else`, the case pattern and the catch arm are each followed by `=>` and then the arm's value. ##### example ```kairo var z = if c 1 else => 2 // missing '=>' after the condition var z = if c => 1 else 2 // missing '=>' after 'else' ``` ##### how to fix insert `=>` where the fix-it points: `var z = if c => 1 else => 2`. ### S075E: match arms mix '=>' and '{ }' forms Messages: - `match arms mix '=>' and '{ }' forms` #### match arms mix '=>' and '{ }' forms a `match` in statement position is either a statement (every arm is a `{ }` block) or a value (every arm is `=> expr`). an arm of each kind in one `match` is neither. ##### example ```kairo match s { case 1 { f() } default => g() // the other arms are blocks } ``` ##### how to fix pick one form for every arm: `default { g() }` for a statement match, or `case 1 => f()` for a value match. ### S076E: match arms separated by a comma Messages: - `match arms are not separated by ','` #### match arms are not separated by ',' the arms of a `match` follow each other directly; a value arm ends where its expression does. a `,` after an arm (the Rust spelling) is not part of the grammar. ##### example ```kairo var k = match s { case 1 => a, // error default => b } ``` ##### how to fix delete the comma. ### S077E: nested 'if' or 'try' expression must be parenthesized Messages: - `an 'if' expression here must be parenthesized` - `a 'try' expression here must be parenthesized` #### nested 'if' or 'try' expression must be parenthesized the last arm of an `if` or `try` expression runs to the end of the surrounding expression. where such an expression sits in front of more of the enclosing construct, it is ambiguous to the reader which construct the following `else`, `=>` or `catch` belongs to, so it must be parenthesized. the positions are: - the `then` arm, or an `else if` arm, of an `if` expression - the condition of an `if` or `else if` - a [`where` guard](/docs/language/pattern-matching/#where-guards) - the operand of a `try` expression, or any catch arm except the last - a `match` scrutinee ##### example ```kairo var z = if a => if b => 1 else => 2 else => 3 // error var n = try try f() catch => 1 catch => 2 // error ``` ##### how to fix parenthesize the inner expression: ```kairo var z = if a => (if b => 1 else => 2) else => 3 var n = try (try f() catch => 1) catch => 2 ``` an inner `try` takes every `catch` that follows it, so in `try try f() ...` the outer `try` is left without arms and the intended split cannot be recovered; no fix-it is offered there. parenthesize the inner `try` together with its own arms. an `if` or `try` needs no parentheses as the final `else` arm, the final catch arm, a match arm value, a whole initializer, a call argument or a return value. ### S078W: 'if' or 'try' expression as an operator's operand Messages: - `this 'if' expression extends to the end of the expression` - `this 'try' expression extends to the end of the expression` #### this 'if'/'try' expression extends to the end of the expression the last arm of an `if` or `try` expression takes everything up to the end of the surrounding expression. as the right operand of a binary operator, or the operand of a prefix operator, that is easy to misread: ```kairo var z = x + if c => 1 else => 2 + 5 // x + (if c => 1 else => (2 + 5)) ``` the parse is well-defined; the warning is only about readability. assignment operators and variable initializers are exempt, since their right side runs to the end of the expression anyway. ##### how to fix parenthesize the `if` or `try`: `x + (if c => 1 else => 2) + 5`. ### S079W: '=>' between 'else' and 'if' is redundant Messages: - `write 'else if'` #### write 'else if' `else => if c => a else => b` and `else if c => a else => b` parse to the same thing, an `if` expression whose final arm is another `if`. only `else if` is idiomatic. ##### how to fix delete the `=>`; the fix-it does this. to keep a nested `if` as the final arm on purpose, parenthesize it: `else => (if c => a else => b)`. ## Calling Conventions The rules these enforce are in [Calling conventions](/docs/language/functions-declarations/#calling-conventions). A forward declaration or out-of-line definition whose convention differs from the other declaration is R039E (redeclared with a different qualifier), with the convention named in the error and the note. ### SC133E: two calling conventions on one function ``` '@preserve_most' and '@preserve_all' cannot both be on one function; a function has one calling convention ``` ```kairo @preserve_most @preserve_all // error SC133E priv fn slow_path(n: usize) { } ``` **Fix:** keep one: `@preserve_all` when callers keep floating-point or vector values live across the call, `@preserve_most` when they keep only integers. The fix-it removes the second. ### SC134E: a calling convention on a function that cannot have one ``` a calling convention cannot be set on {kind} ``` `{kind}` is a constructor, a destructor, an operator, `'main'`, a generator, an `'async'` function, a closure or an `'eval fn'`. Code Kairo does not write calls each of these (C++ object lifetime, the C runtime, the coroutine machinery, a lambda's call operator, the constant evaluator), and it always calls with the C convention. ```kairo priv class Buffer { @preserve_most // error SC134E: a constructor fn Buffer(self) { } } ``` **Fix:** move the slow work into a `priv` free function that carries the convention, and call it from here. ### SC135E: an override disagrees with the convention of the method it overrides ``` '{m}' has {convention}, but the method it overrides has {convention} ``` A call through a base reference uses the base method's convention, whichever override it reaches, so every method of one override set needs the same convention (or none). ```kairo priv class Base { @preserve_most virtual fn tick(self) { } } priv class Derived derives Base { override fn tick(self) { } // error SC135E } ``` **Fix:** write the same convention on every method of the set, or on none. ### SC136E: a calling convention cannot cross the C/C++ boundary ``` '@preserve_most' cannot cross the C/C++ boundary: GCC cannot call it ``` GCC has no spelling for these conventions. An `ffi "c"` / `ffi "c++"` declaration, or any function that is not `priv`, written or by default (an unmarked function is `priv` when no `module.k` is above its file, and `prot` under one), is in the module's emitted C++ header and its `#include "x.k"` interface, where code GCC compiled could call it. ```kairo @preserve_most pub fn grow(n: usize) { } // error SC136E: not priv @preserve_most priv fn grow_slow(n: usize) { } // fine ``` **Fix:** make the function `priv`, or give the public entry point the default convention and have it call a `priv` function that carries one. ### SC137E: the calling convention is not available on the target ``` '@preserve_most' is not available on {triple} ``` LLVM implements the three conventions on x86-64 and AArch64 only (any operating system). Elsewhere clang would drop the attribute with a warning and call with the C convention, so Kairo makes it an error. **Fix:** remove the attribute, or keep the declaration that carries it in code built only for x86-64 and AArch64. --- ## See also - [Panic](/docs/language/panic/) - [Collections](/docs/language/collections/) - [Function Overloading](/docs/language/functions-overloading/) - [Default Parameters](/docs/language/functions-parameters/#default-parameters) - [Class Lifecycle](/docs/language/classes-lifecycle/) - [Plain Enums](/docs/language/enums-plain/) - [Generators](/docs/language/functions-generators/) - [Pattern Matching](/docs/language/pattern-matching/) --- ## ADT Enums URL: https://www.kairolang.org/docs/language/enums-adt/ # ADT Enums Variants can carry structured data. Each payload is defined as a set of named fields inside braces: ```kairo enum ParseResult { Success { value: T, bytes_consumed: i32 }, Error { message: string, position: i32 }, EndOfInput, } ``` Variants without a payload (`EndOfInput` above) are plain discriminants. Variants with a payload carry an anonymous struct alongside the discriminant. A single enum can freely mix both. ## Construction There are three construction forms: | Form | Use | |---|---| | `Enum::V { f: e }` | Payload variant, fully qualified | | `.V { f: e }` | Payload variant, enum type inferred from context | | `.V` (or `Enum::V`) | Variant with no payload | A payload variant written without braces, braces on a variant without a payload, a missing field, or a field given twice is [SC131E](/docs/language/diagnostics/#sc131e-a-variant-is-built-with-the-wrong-shape). `Enum::V { field: value }` builds a payload variant anywhere; `.V { field: value }` and `.V` work where the expected type is known. A nullary variant takes no braces. ADT variants are constructed with the variant name followed by brace-delimited field assignment, matching [struct](/docs/language/structures/) aggregate initialization: ```kairo enum ParseResult { Success { value: T, bytes_consumed: i32 }, Error { message: string, position: i32 }, EndOfInput, } fn main() -> i32 { var result = ParseResult::Success { value: 3.14, bytes_consumed: 4 } var err = ParseResult::Error { message: "unexpected token", position: 12 } var eof = ParseResult::EndOfInput // the enum type is known from the declaration, so the shorthand works var inferred: ParseResult = .Success { value: 3.14, bytes_consumed: 4 } return 0 } ``` Field names are required. The order of fields in the initializer does not need to match the declaration order. ## Destructuring with `match` Use `match` to dispatch on variants and extract payload fields. Destructured fields use `var` or `const` to control mutability of the bound variable: ```kairo enum ParseResult { Success { value: T, bytes_consumed: i32 }, Error { message: string, position: i32 }, EndOfInput, } fn report(result: ParseResult) -> string { match result { case .Success(var value, var bytes_consumed) { return f"parsed {value} from {bytes_consumed} bytes" } case .Error(const message, const position) { // message = "other" // compile error: message is const return f"error at {position}: {message}" } case .EndOfInput { return "nothing left to parse" } } } ``` > [!NOTE] > The current compiler does not report assigning to a `const` pattern binding yet. See [Status](/docs/status/#not-diagnosed). Field names in the destructuring pattern must match the names in the variant declaration. You can omit fields you do not need the compiler does not require exhaustive field extraction: ```kairo enum ParseResult { Success { value: T, bytes_consumed: i32 }, Error { message: string, position: i32 }, EndOfInput, } fn error_message(result: ParseResult) -> string { match result { case .Error(const message) { // only message is bound, position is ignored return message } default { return "" } } } ``` See [Control Flow](/docs/language/pattern-matching/) for the full `match` syntax, including guards (`where`), ranges, and expression form. ## `match` as an expression ```kairo enum ParseResult { Success { value: T, bytes_consumed: i32 }, Error { message: string, position: i32 }, EndOfInput, } fn describe(result: ParseResult) -> string { return match result { case .Success(var value, var bytes_consumed) => f"parsed {value} ({bytes_consumed} bytes)" case .Error(var message, var position) => f"error at {position}: {message}" case .EndOfInput => "end of input" } } ``` ADT enums work in expression-form `match`. Each arm is `case pattern => value`, and every arm must produce the same type. See [Control Flow](/docs/language/pattern-matching/#match-as-an-expression) for the full expression-form rules. ## Memory layout An ADT enum stores a discriminant tag plus storage sized to the largest variant's payload. The tag is the enum's `derives` type when it names one, otherwise the smallest unsigned integer that holds a tag per variant: `u8` up to 256 variants, `u16` beyond. A variant with no payload consumes no extra storage beyond the tag. A `derives` type too narrow for the variants is an error. ``` ParseResult layout: [tag: u8] [payload: max(sizeof Success, sizeof Error)] [padding] ``` When every payload field is a primitive, a pointer, or a plain enum, the tag sits inside each payload instead of in front of it, so the payload's padding absorbs it: `enum Pair { Two { a: u8, b: u16 }, One { c: u8 }, Zero }` is 4 bytes, not 6. An enum with exactly one variant that carries a payload, that payload a single field, and at least one variant without a payload, may need no tag at all. If the field has bit patterns it never holds, each payload-free variant is stored as one of them: - a pointer is never null, so `null` stands for the variant: `(*Foo)?` is the size of a pointer, and is passed and returned like one; - a [closed](/docs/language/enums-plain/#closed-and-open-enums) plain enum whose values are `0` to `N-1` never holds a value past its last variant: `Color?` is one byte for an `enum Color derives u8 { Red, Green, Blue }`, with `null` stored as 3; - an enum with payloads never holds a tag past its last variant: `Inst?` is the size of `Inst`. An [`@open`](/docs/language/enums-plain/#closed-and-open-enums) plain enum has no spare patterns: `as` can give it any value of its underlying type, so `Color?` keeps a tag (two bytes for an `@open enum Color derives u8`). Neither does a plain enum with explicit values that leave gaps, nor an imported C or C++ enum. The field must also copy and destroy as plain bytes. Nesting keeps working: `(Color?)?` is still one byte, stored as 4, since `Color?` leaves values to spare, while `((*Foo)?)?` needs a tag, since the pointer's only spare pattern is taken. No program can observe the difference except through `sizeof`. The compiler generates a [destructor](/docs/language/classes-lifecycle/#destructors---op-finally) that switches on the tag to destroy the active variant's fields. Copy and move operations follow the same pattern. ## Lifecycle category An enum whose variants carry payloads follows the struct rule for lifecycle: its [category](/docs/language/classes-lifecycle/#lifecycle-categories) is the weakest of its payload fields' categories (COPY, then MOVE, then NON_TRANSFER), and it is trivially copyable or destructible only when every payload is. A plain enum is COPY. --- ## Generic Enums Enums with payloads can be [generic](/docs/language/generics/). Type parameters are declared in angle brackets before the enum name: ```kairo enum LookupResult { Found { key: K, value: V }, NotFound { key: K }, Error { message: string }, } fn main() -> i32 { var r = LookupResult::Found { key: "count", value: 42 } return 0 } ``` Constrain type parameters with `impl` or `derives` bounds: ```kairo interface Serializable { fn serialize(const self) -> [byte] } enum CacheEntry { Valid { data: T, expires: i64 }, Expired { last_data: T }, Empty, } ``` See [Requires Clauses](/docs/language/requires/) for the full constraint system. ### Variadic enums An enum can take a type pack (`...E`, as in [generic variadic functions](/docs/language/functions-parameters/#generic-variadic-functions)) and declare a **pack-expanded variant**: a variant written once and followed by `...`, which expands to one variant per element of the pack. ```kairo enum Outcome { Ok { value: T }, Err { error: E }..., // one Err variant per element of E } type Parsed = Outcome // variants: Ok { value: i32 }, Err { error: string }, Err { error: f64 } type Plain = Outcome // an empty pack: only Ok ``` - A pack-expanded variant's payload names the pack (`E`) as a field's whole type, and each expansion has that element as its payload type. - The expansions share the variant's name and are told apart by their payload type: a pattern or construction that names `Err` picks the expansion whose payload type matches. - Equal types in a pack give one variant, not two: `Outcome` has one `Err { error: string }`, and is the same type as `Outcome`. - A variant that is not followed by `...` is an ordinary variant, the same in every instantiation. It cannot name the pack. - An enum has at most one pack-expanded variant, and it is the last one. A construction picks the expansion whose payload type is the value's type exactly, or, failing that, the one expansion the value converts to: ```kairo var a: Parsed = .Err { error: "bad digit" } // Err { error: string } var b: Parsed = .Err { error: 0.5 } // Err { error: f64 } var c: Parsed = .Err { error: 1 } // Err { error: f64 }: an i32 matches neither exactly, and converts only to f64 var d: Parsed = .Err { error: true } // error: no Err holds a bool ``` A value that converts to more than one expansion is an error too: in `Outcome`, an `i32` fits both `Err { error: i64 }` and `Err { error: f64 }`, so the payload's type must pick one. A pattern picks one by the type written on the binder of the pack field. With a single expansion the type may be left out. Each expansion is its own case for [exhaustiveness](/docs/language/pattern-matching/#exhaustiveness): ```kairo fn describe(p: Parsed) -> string = match p { case .Ok(var value) => f"{value}" case .Err(var error: string) => error case .Err(var error: f64) => "out of range" } ``` A generic function can take and return a variadic enum, and its pack is deduced from the argument (`fn <...E> relay(o: Outcome) -> Outcome`). Building or matching a pack-expanded variant at a type that still depends on a generic parameter is not supported yet ([SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)). The builtin result type of a [panicking function](/docs/language/panic/) is declared this way, with the function's panic set as the pack. --- ## Casting ADT enums cannot be cast to integers directly they carry payloads that have no integer representation. Cast the tag explicitly if you need the discriminant value. See [Casting](/docs/language/casting/#enum-casts) for the full casting model. ## See also - [Enums](/docs/language/enums/) - [Plain Enums](/docs/language/enums-plain/) - [Pattern Matching](/docs/language/pattern-matching/) - [Generics](/docs/language/generics/) - [Structures](/docs/language/structures/) - [Unions](/docs/language/unions/) - [Requires Clauses](/docs/language/requires/) - [Casting](/docs/language/casting/#adt-enums) --- ## Plain Enums URL: https://www.kairolang.org/docs/language/enums-plain/ # Plain Enums A plain enum is a set of named integer constants: ```kairo enum Direction { North, East, South, West, } fn main() -> i32 { var dir = Direction::North return 0 } ``` Variants are comma-separated and scoped to the enum name. The trailing comma is optional. Plain enums (no payloads) cannot be [generic](/docs/language/generics/) there is nothing for a type parameter to parameterize. ## Discriminant values Variants are assigned sequential integers starting from 0 by default. Explicit values can be assigned with `=`: ```kairo enum HttpStatus { Ok = 200, NotFound = 404, InternalError = 500, ServiceUnavailable, // 501 } ``` A discriminant is an integer constant expression evaluated by the compiler: literals, `+ - * | & ^ << >>`, unary `-` and `~`, parentheses, `as` to an integer type, and earlier variants of the same enum. Inside a discriminant, an earlier variant has the enum's [underlying type](#underlying-type), so `Exec = Read << 2` and `RW = Read | Write` work. `~` works in the underlying type: `All = ~0` in a `u32` enum is `0xFFFFFFFF`. A variant without a discriminant is the previous value plus one, or 0 if it is first. A value that doesn't evaluate or doesn't fit the underlying type is [SC128E](/docs/language/diagnostics/#sc128e-an-enum-discriminant-does-not-evaluate-or-does-not-fit). Two variants with the same value is [SC130E](/docs/language/diagnostics/#sc130e-two-variants-of-an-enum-have-the-same-value); imported C++ enums are exempt. Compound expressions are valid for bit flags: ```kairo enum FileMode derives u8 { Read = 1 << 0, // 1 Write = 1 << 1, // 2 Execute = 1 << 2, // 4 RW = (Read | Write), // 3 All = (Read | Write | Execute), // 7 } fn main() -> i32 { var perms: FileMode = .RW if (perms as u8 & FileMode::Read as u8) != 0 { // has read permission } return 0 } ``` [Bitwise operators](/docs/language/operators/#bitwise) are not defined on the enum type itself, so test a flag on the underlying integer: cast both sides with `as` and compare the result with `0`. A combination no variant names (`Read | Execute`, 5 above) is not a value of a [closed](#closed-and-open-enums) enum, so casting it back with `as` fails. A flags enum that is meant to hold any combination is declared `@open`. --- ## Underlying Type The default underlying type is `u32`. The compiler promotes to a wider unsigned integer if the number of variants exceeds what `u32` can represent, though a warning is emitted for enums exceeding 2^32 variants. Specify an explicit underlying type with `derives` followed by an integer type: ```kairo enum Opcode derives u8 { Nop = 0x00, Load = 0x01, Store = 0x02, Halt = 0xFF, } ``` Only integer types (`u8`, `u16`, `u32`, `u64`, `i8`, `i16`, `i32`, `i64`, `usize`, `isize`) are permitted. The compiler errors if any discriminant does not fit in the specified type. > [!NOTE] > `derives` on an enum specifies the underlying integer type. This is distinct from `derives` on a [class](/docs/language/classes-inheritance/#inheritance), which declares inheritance. --- ## No Associated Data in Variants (Plain Enums Only) For plain enums without the `{ field: Type }` payload syntax, variants are strictly integer constants. If you need per-variant data, use an [ADT enum](/docs/language/enums-adt/#adt-enums). For untagged memory overlays where you manage the active member yourself, use [Unions](/docs/language/unions/). --- ## Casting Plain enum values can be [cast](/docs/language/casting/#plain-enums) to their underlying integer type and back: ```kairo enum Direction { North, East, South, West } fn main() -> i32 { var dir = Direction::North var raw = dir as u32 // 0 var back = raw as Direction // Direction::North return 0 } ``` Casting back is checked, unless the enum is `@open`: see the next section. --- ## Closed and open enums A plain enum is **closed** by default: it only ever holds one of its variants' values. Every way to make a value of it keeps that true: - `n as E` with a **constant** `n` that is no variant's value is a compile error, [SC001E](/docs/language/diagnostics/#sc001e-a-constant-cast-into-a-closed-enum-is-no-variants-value), with a fix-it that declares the enum `@open`. - `n as E` with any other `n` is checked when it runs. A value that is no variant's **crashes** the program, like a failed bounds check: it prints the cast and where it is, then aborts. It is not a [`panic`](/docs/language/panic/): no `try` catches it. The check compares the integer before the cast, so when the compiler can see the value it costs nothing: `v >= 3` for an enum whose values are `0`, `1`, `2`, and one compare per variant when the values are explicit. Because a closed enum never holds anything else, the compiler can use the values past its variants: `Color?` is one byte, `null` stored as a value no `Color` has (see [ADT memory layout](/docs/language/enums-adt/#memory-layout)), and a `match` that covers every variant needs no fallback for an undeclared value. The `@open` attribute declares an **open** enum, one that may hold any value of its underlying type, as a C++ enum does (clang's `enum_extensibility(open)`): ```kairo @open enum Signal derives u8 { Hup = 1, Int = 2, Kill = 9, } fn main() -> i32 { var s = 15 as Signal // fine: Signal is open, 15 is a value it may hold return 0 } ``` An open enum gets no `as` check, no niche (`Signal?` keeps a tag), and a complete `match` over it traps on an undeclared value below `-O3`. Use it for flags whose combinations are values, for codes another program may extend, and for anything filled in by C or C++. - `@open` applies to a plain enum only. On an enum with payloads, a struct, a function or anything else it is an error with a fix-it that removes it. Written on a [forward declaration](#forward-declarations) or the definition, it opens the enum. - An enum [imported from C or C++](/docs/language/c-cpp/) is always open: clang owns its values. - An enum with no variants holds no value at all unless it is `@open`; declare one that is a raw word, like the builtin `Byte`, `@open`. `unsafe` code can still put an undeclared value into a closed enum without `as`: a reinterpreting pointer cast (`&n as unsafe *Color`), a [union](/docs/language/unions/), or C or C++ code writing through a pointer it was handed. That is undefined behavior: the value may read back as `null` through a `Color?`, and a `match` may take any arm. Declare the enum `@open` when other code writes it. --- ## Forward Declarations Enums can be forward-declared when the underlying type is specified: ```kairo enum Opcode derives u8 // forward declaration: size is known fn is_halt(code: Opcode) -> bool { return code == .Halt } enum Opcode derives u8 { Nop = 0x00, Load = 0x01, Store = 0x02, Halt = 0xFF, } ``` Without an explicit underlying type, forward declaration is not permitted the compiler needs the size, which depends on the variant count and payload sizes. ## See also - [Enums](/docs/language/enums/) - [ADT Enums](/docs/language/enums-adt/) - [Unions](/docs/language/unions/) - [Casting](/docs/language/casting/) - [Extends](/docs/language/extends/#enums) - [Pattern Matching](/docs/language/pattern-matching/#enum-variant-matching) --- ## Function Declarations URL: https://www.kairolang.org/docs/language/functions-declarations/ # Function Declarations This page covers function modifiers, visibility, ABI and linkage, and forward declarations. ## Function Modifiers Modifiers appear after the parameter list and before the return type arrow. Multiple modifiers can be combined, subject to the compatibility rules below. `inline` and `eval` may also be written before `fn` (`pub inline fn twice(x: i32) -> i32`); both positions mean the same thing. ```kairo fn compute(x: i32) inline -> i32 { return x * x } fn dangerous() unsafe -> void { /* ... */ } fn compile_time() eval -> i32 { return 42 } fn may_fail() panic -> i32 { /* ... */ } fn background() async -> Data { /* ... */ } ``` ### Modifier reference | Modifier | Free functions | Methods | Description | |---|---|---|---| | `const` | `fn f(...) const` (after the parameters) | `const self` | A method does not modify `self` (see [Variables](/docs/language/variables/#the-const-binding-rule)); a free const function reads only its inputs (see [Const functions](#const-functions)) | | `volatile` | Yes | Yes | Prevents certain compiler optimizations; for hardware interaction | | `unsafe` | Yes | Yes | [Separate overload namespace](/docs/language/unsafe/#unsafe-function-overloads) for alternative implementations | | `eval` | Yes | Yes | Must be evaluable at compile time. See [Eval](/docs/language/eval/) | | `async` | Yes | Yes | Asynchronous execution. See [Concurrency](/docs/language/concurrency/) | | `panic` | Yes | Yes | May panic; callers must handle. `panic(E1, E2)` declares the set. See [Panic](/docs/language/panic/) | | `inline` | Yes | Yes | Puts the body in the interface. See [`inline`](#inline) | | `final` | | Yes | Prevents override in subclasses. See [Classes](/docs/language/classes-inheritance/#final) | ### `inline` `inline` puts the body in the interface: importers compile it themselves. Use it for small functions on hot paths, and for functions the C++ compiler calls on your behalf ([coroutine promises and awaiters](/docs/language/concurrency/#custom-awaitables)). ```kairo pub inline fn twice(x: i32) -> i32 { return x * 2 } ``` Every module that can see the declaration gets the definition and compiles it, so the optimizer can inline the call there. In C++ terms it is an `inline` function: one shared definition that the linker merges across objects. It is not a request to force inlining. - An `inline` function must have a body, in the same file as its declaration (an in-class declaration may be defined out of line in that file). An `inline` declaration with no body is an error. - Every declaration of the function must agree on `inline`. - Unused `inline` bodies cost parse time only: no code is generated for one nothing calls. ### Const functions A free function marked `const` after its parameters, `fn f(...) const`, reads strictly its inputs: no global memory, nothing through a pointer. It is a function in the mathematical sense, like `sin` or `abs`, and the compiler may merge two calls with the same arguments, hoist a call out of a loop, or drop one whose result is unused. In the generated C++ it is `[[gnu::const]]`. A function that keeps this promise without writing `const` is found and treated the same way by default ([function hints](/docs/language/attributes/#function-hints); `-fno-infer-purity` turns it off). ```kairo fn lerp(a: f64, b: f64, t: f64) const -> f64 { return a + (b - a) * t } ``` Because the optimizer acts on the promise without looking, the compiler checks it. A const function must return a value (on a function without a result the promise means nothing, and the compiler offers to remove it), must not be `-> !` or `@unwind`, and its result type must not own memory (a `string`, a vector, a record holding one). In its body these are errors: - reading or writing a global or `static` variable (an [`eval`](/docs/language/eval/) constant is a compile-time value, not memory, and is allowed); - dereferencing a pointer: `*p`, `p->field`, or indexing a pointer with `p[i]`; - reading a parameter passed by reference: `@inout`, `@move`, or a `const` parameter of a class or struct type. A by-value parameter is a copy and may be read, fields included; - calling a function that is not itself const, an `eval fn` or a side-effect-free compiler intrinsic (a hint such as `__builtin_expect`; not `__builtin_trap` or the memory and atomic intrinsics). A user operator is a call too, including the two you do not write as one: the `@implicit op as` an implicit conversion runs, and the `op ==` a `match` pattern runs when it compares a value against a constant. A call through a function value or an interface requirement is always an error; - making a value that owns memory: a `string` (a string literal or an f-string included), a vector or a map, a local of such a type, or a by-value copy of one passed to another function; - anything that can stop the program instead of returning: `assert`, `unwrap!`, an asserting downcast, `crash!()`; - a `for ... in` loop over anything but a range (`0..n`) or a fixed-size array: the iterator calls it makes are not checked; - `delete`, inline C++, `spawn`, `thread` and `await`. [`panic`](/docs/language/panic/) is allowed: it returns an error value, it does not unwind. Each error carries a note on the function's head: `'lerp' is const: it may read only its own inputs`. A const function is a free function. A method says the weaker thing, that it does not change its object, with `const self`; a trailing `const` on a method is an error. The leading spelling `const fn f()` is an error too, with a fix-it: `const` before a name reads as a binding. ```kairo class Vec2 { var x: f64 var y: f64 fn len(const self) -> f64 { /* a const method: reads self, changes nothing */ } // fn len2(self) const -> f64 { ... } // error: write 'fn len2(const self)' } ``` A function that may read globals or pointed-to memory, but writes nothing, is [`@pure`](/docs/language/attributes/#function-hints) instead. ### Modifier compatibility Not all modifiers can be combined: | Combination | Valid | Reason | |---|---|---| | `const` + `volatile` | ok: | | | `const` + `unsafe` | | `unsafe:` implies a separate overload with different invariants | | `const` + `eval` | | `eval:` implies compile-time evaluation `const self` is meaningless | | `const` + `async` | ok: | | | `unsafe` + any other | ok: | `unsafe:` creates a separate overload the other modifiers apply to both versions as appropriate | | `eval` + `unsafe` | ok: | `eval` and `unsafe` are orthogonal modifiers | | `eval` + any other (except `unsafe`) | | `eval` implies compile-time evaluation incompatible with runtime modifiers | | `async` + `const` | ok: | | | `async` + `volatile` | ok: | | --- ## Visibility A top-level function with no visibility written is `priv` to its file, or `prot` to its module when a `module.k` sits at or above the file. Write `pub` on what other modules may use. | Keyword | Scope of a top-level function | |---|---| | `pub` | Any module that imports this module | | `priv` | Current file only | | `prot` | Current file and sibling files in the same library subtree | ```kairo pub fn api() { /* ... */ } fn helper() { /* ... */ } // priv, or prot under a module.k priv fn internal_helper() { /* ... */ } prot fn library_helper() { /* ... */ } ``` See [Modules](/docs/language/modules/#visibility-on-top-level-declarations) for how visibility interacts with imports. Methods follow the member rules in [Classes](/docs/language/classes/#default-visibility). --- ## ABI and Linkage ABI modifiers control name mangling, dispatch mechanism, and symbol visibility at the object code level. | Modifier | Description | |---|---| | `ffi "c"` | C linkage no name mangling. See [C/C++ Interop](/docs/language/c-cpp/) | | `ffi "c++"` | C++ linkage Itanium or MSVC mangling. See [C/C++ Interop](/docs/language/c-cpp/) | | `static` | Internal linkage; no vtable dispatch. Cannot be `virtual` or `override` | | `virtual` | Dynamic dispatch via vtable. See [Classes](/docs/language/classes-inheritance/#virtual-dispatch) | | `override` | Overrides a `virtual` method from a [base class](/docs/language/classes-inheritance/#inheritance); implies `virtual` | `static`, `virtual`, and `override` are mutually exclusive with each other. `ffi` can be combined with any of them. ```kairo class Shape { virtual fn area(const self) -> f64 { return 0.0 } } class Circle derives Shape { var radius: f64 override fn area(const self) -> f64 { return 3.14159 * self.radius * self.radius } } class Math { static fn sqrt(x: f64) -> f64 { /* ... */ } } Math::sqrt(16.0) // called without an instance ``` --- ## Forward Declarations A function can be declared without a body a signature followed by no block: ```kairo fn parse_expression(tokens: [Token]) -> Expr fn parse_statement(tokens: [Token]) -> Stmt ``` Within a single module, forward declarations are rarely needed. Kairo hoists all top-level declarations before type checking, so mutual recursion works without them: ```kairo fn is_even(n: u32) -> bool = if n == 0 => true else => is_odd(n - 1) fn is_odd(n: u32) -> bool = if n == 0 => false else => is_even(n - 1) ``` Forward declarations are used when the definition lives elsewhere: - **FFI imports** the body is provided by a C or C++ library. See [C/C++ Interop](/docs/language/c-cpp/). - **Separate translation units** the declaration is visible to callers; the definition is linked in from another `.k` file. - **Out-of-line class methods** declared in the class body, defined outside it using the `Class::method` qualified-name syntax: ```kairo class Parser { var pos: usize fn advance(self) -> Token fn peek(const self) -> Token } fn Parser::advance(self) -> Token { var t = self.tokens[self.pos] self.pos += 1 return t } fn Parser::peek(const self) -> Token = self.tokens[self.pos] ``` See [Classes](/docs/language/classes-out-of-line/#forward-declarations-and-out-of-line-definitions) for the full rules. ### Signature matching When a definition follows a forward declaration, the two must match exactly: - Parameter types, return type, and all function modifiers (`const`, `unsafe`, `panic`, `eval`, `async`, `inline`, `final`, `volatile`) - Visibility (`pub`, `priv`, `prot`) - ABI linkage (`ffi "c"`, `ffi "c++"`, `static`, `virtual`, `override`) - Calling convention (`@preserve_most`, `@preserve_all`, `@preserve_none`, or none); see [Calling conventions](#calling-conventions) Parameter names may differ; the definition's names are used in the body. So may the names of generic parameters: `fn g(x: T) -> i32` and a later `fn g(x: U) -> i32 { ... }` are one function. Their bounds may not: a declaration and its definition must name the same bounds for each generic parameter. (Two generic functions that both have bodies and differ only in their bounds are two overloads.) Defaults are not part of the match: each parameter's default may be written on any one declaration, and it applies to every call (see [Defaults apply to the whole function](/docs/language/functions-parameters/#defaults-apply-to-the-whole-function)). A mismatch in any other element is a compile error. ## Calling conventions A calling convention decides which registers a call may clobber. Every function uses the platform's C convention unless it carries one of three attributes, each an LLVM calling convention: | Attribute | LLVM | clang | |---|---|---| | `@preserve_most` | `preserve_mostcc` | `[[clang::preserve_most]]` | | `@preserve_all` | `preserve_allcc` | `[[clang::preserve_all]]` | | `@preserve_none` | `preserve_nonecc` | `[[clang::preserve_none]]` | `@preserve_most` and `@preserve_all` pass arguments and return values exactly as the C convention does; only the set of registers the callee must save changes. `@preserve_none` also passes arguments in more registers than C does, which only matters to code that is not Kairo (and none can call it; see below). ```kairo @preserve_most priv fn grow_slow(v: *Buffer, need: usize) { /* rare: reallocate and copy */ } fn push(v: *Buffer, x: u8) { if v->len == v->cap { grow_slow(v, 1) } // the hot caller keeps its registers v->data[v->len] = x v->len += 1 } ``` ### Who saves what | | x86-64 | AArch64 | |---|---|---| | C convention (callee saves) | `rbx`, `rbp`, `r12`-`r15` (Windows adds `rdi`, `rsi`, `xmm6`-`xmm15`) | `x19`-`x28`, `x29`, `x30`, low 64 bits of `v8`-`v15` | | `@preserve_most` | every general-purpose register except `r11` and the return registers; floating-point and vector registers stay caller-saved | every general-purpose register except `x0`-`x8` and `x16`-`x18` (adds `x9`-`x15` to C's set); floating-point and vector registers as in C | | `@preserve_all` | as `@preserve_most`, plus every XMM/YMM register | as `@preserve_most`, plus the floating-point and SIMD registers | | `@preserve_none` | nothing but `rsp` and `rbp` | nothing but the frame pointer, link register and `sp` | ### When to use each - **`@preserve_most`**: a rarely taken slow path (growing a buffer, refilling a cache, reporting an error) called from hot integer code. The hot caller keeps its values in the registers they are already in instead of saving them around the call; the slow path pays for the saves instead. - **`@preserve_all`**: the same, when the hot caller also keeps floating-point or SIMD values live across the call. - **`@preserve_none`**: tail-call-heavy dispatch, such as an interpreter's opcode handlers, where each handler jumps to the next and nothing needs to survive a call. None of them changes inlining: the optimizer may still inline the function, and the convention then applies only to the calls that remain. ### Rules - **One per function.** Two different conventions on one function is an error naming both ([SC133E](/docs/language/diagnostics/#sc133e)). - **Every declaration agrees.** A forward declaration and its definition, or an in-class declaration and its out-of-line definition, carry the same convention ([Signature matching](#signature-matching)). A convention alone never makes two declarations distinct overloads: the same signature with a different convention is a redeclaration error. - **Not on functions called by code Kairo does not write**: a constructor, a destructor (`op finally`), any operator, `main`, a generator, an `async` function, a closure or an `eval fn` ([SC134E](/docs/language/diagnostics/#sc134e)). - **One convention per override set.** A `virtual` or `override` method may carry a convention only if every method it overrides or is overridden by carries the same one ([SC135E](/docs/language/diagnostics/#sc135e)). - **Not across the C/C++ boundary.** GCC has no spelling for these conventions, so a function C or C++ can see may not carry one: an `ffi "c"` / `ffi "c++"` declaration, or any function that is not `priv`, written or by default (an unmarked function is `priv` when no `module.k` is above its file; under one it is `prot` and is in the header). Such a function is in the module's emitted C++ header and its `#include "x.k"` interface. A `priv` or local function is fine ([SC136E](/docs/language/diagnostics/#sc136e)). - **x86-64 and AArch64 only**, on any operating system. On any other target the attribute is an error, never silently ignored ([SC137E](/docs/language/diagnostics/#sc137e)). ### In a function type The convention is part of a function's type: `fn(usize, usize) @preserve_most -> unsafe *u8` (the attribute after the parameter list, before the modifiers and `->`). A function with a convention converts only to a `fn` type with the same convention, in either direction; converting to or from the default convention is a type mismatch. Because closures cannot have a convention, a value of such a type always holds a named function, and it is a plain function pointer, called directly. An interface requirement may carry a convention, and a conforming method must match it exactly. ### Stability across LLVM versions LLVM documents these conventions as not stable across releases. Every object that defines or calls a function with one records which conventions it uses and the LLVM major that compiled it in its [ABI note](/docs/language/c-cpp-abi/#link-time-abi-verification), and `kld` refuses to link two such objects built by different LLVM majors: ``` error: '@preserve_most' is used by a.o (LLVM 22) and b.o (LLVM 23); this calling convention is not stable across LLVM versions; rebuild both ``` Objects that use none of the conventions are never compared. ## See also - [Functions](/docs/language/functions/) - [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Function Overloading](/docs/language/functions-overloading/) - [Generators](/docs/language/functions-generators/) - [Modules](/docs/language/modules/) - [Classes](/docs/language/classes/) - [C/C++ Interop](/docs/language/c-cpp/) - [Eval](/docs/language/eval/) - [Panic](/docs/language/panic/) --- ## Generators URL: https://www.kairolang.org/docs/language/functions-generators/ # Generators A function is a **generator** when its return type is written `-> yield T`. Calling it does not run the body; it returns a sequence that runs the body a step at a time as values are asked for, most often by a [`for` loop](/docs/language/control-flow/#for-range-and-iterator). ```kairo fn generate_numbers() -> yield i32 { for i in 0..10 { yield i } } for n in generate_numbers() { std::io::println(n) } ``` Only the written return type makes a generator. A spelled-out `-> Yield` is an ordinary function that returns a `Yield` value, and a `yield` in the body does not turn a function into a generator. In a generator's body: - `yield e` produces the next value. `e` must convert to `T`. - Yielding a slice literal is an error: its backing array ends at the suspension, before the caller sees the value. - A bare `return` ends the sequence early. `return e` is an error, since a generator has no return value. - Falling off the end of the body also ends the sequence. There is no missing-return error. - A generator with no `yield` at all is valid and produces nothing. ```kairo fn first_positive(xs: [i32;]) -> yield i32 { for x in xs { if x > 0 { yield x return // ok: ends the sequence } } } // ok: falling off the end also ends it ``` `yield` is an error ([SC111E](/docs/language/diagnostics/#sc111e-yield-where-nothing-can-yield)): - outside a function; - inside a [closure](/docs/language/closures/) (closures cannot yield yet); - in a function not declared `-> yield T`. These functions cannot be generators ([SC112E](/docs/language/diagnostics/#sc112e-this-kind-of-function-cannot-be-a-generator)): `main`, constructors, destructors (`op finally`), `eval` functions, C-variadic functions, and functions returning `!`. ## Generator lifetimes A generator can do one thing an ordinary function cannot: its suspended body keeps references to `self` and to [`@inout` arguments](/docs/language/functions-parameter-modes/) after the call that created it has returned. - A loop like `for x in xs.gen()` keeps `xs` alive for the whole loop, so it is safe. - A generator stored in a variable can outlive what it refers to, and then dangles. Do not keep a generator longer than the object it was created from. ```kairo var it = make_list().gen() // the list is destroyed at the end of this statement for x in it { } // it reads a destroyed list ``` > [!NOTE] > The current compiler does not report a generator that outlives what it refers to. See [Implementation Status](/docs/status/#not-diagnosed). ## Special return types These return type modifiers interact with Kairo's concurrency and type system. Each is covered in detail on its respective page: | Return type | Description | Details | |---|---|---| | `yield T` | Generator: produces a sequence of `T` values | [Generators](#generators) | | `atomic T` | Atomic wrapper thread-safe operations | [Concurrency](/docs/language/concurrency/) | Yielding a const place (a field in a `const self` generator) yields a copy; a move-only value cannot be yielded from a const place (SC182E). ## See also - [Functions](/docs/language/functions/) - [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Function Overloading](/docs/language/functions-overloading/) - [Function Declarations](/docs/language/functions-declarations/) - [Control Flow](/docs/language/control-flow/) - [Concurrency](/docs/language/concurrency/) - [Closures](/docs/language/closures/) - [Diagnostics](/docs/language/diagnostics/) --- ## Function Overloading URL: https://www.kairolang.org/docs/language/functions-overloading/ # Function Overloading Functions can be overloaded by parameter types, matching C++ overload resolution rules: ```kairo fn add(a: i32, b: i32) -> i32 = a + b fn add(a: f64, b: f64) -> f64 = a + b fn add(a: string, b: string) -> string = a + b ``` Parameter modes also participate in overloading. See [Overloading on mode](#overloading-on-mode). A candidate either matches an argument exactly or through a conversion, and there is no ordering among conversions: if two candidates both need one, the call is ambiguous (`call to 'f' is ambiguous: more than one candidate matches at the same rank`). Before a tie at the same rank is declared ambiguous, four tie-breaks run, in C++'s order: 1. **Reference binding.** An rvalue argument prefers a `T&&` parameter to `const T&`; a non-const lvalue prefers `T&` to `const T&`; a non-const receiver prefers the non-const method. 2. **Float literal.** An untyped float literal is a double, as in C++: against candidates that differ by float type it prefers `f64`, so `cxx::std::sqrt(16.0)` calls the `double` overload and `f(1.5)` picks `fn f(x: f64)` over `fn f(x: f32)`. A lone `f32` parameter still takes the literal. Integer literals are not ordered this way (C++ converts an integer to every float type alike), and neither are typed arguments. 3. **Non-generic over generic.** A non-generic candidate beats a generic one. 4. **Most specialized generic.** Among generic candidates still tied, the most specialized wins: `fn f(a: Box, b: Box)` beats `fn f(a: Box, b: Box)` for `f(x, y)` with two `Box`. These tie-breaks never order conversions. For a list literal argument, a `[T; N]` parameter with the same element count is an exact match, while `[T;]` and `[T]` parameters both need a conversion: ```kairo fn f(const xs: [i32; 3]) { } fn f(xs: [i32;]) { } fn f(xs: [i32]) { } f([1, 2, 3]) // [i32; 3] fn g(xs: [i32;]) { } fn g(xs: [i32]) { } g([1, 2, 3]) // compile error: call to 'g' is ambiguous g([1, 2, 3] as [i32]) // ok ``` See [Primitives](/docs/language/conversion-lattice/#list-literal-arguments) for the ranking rules. ## Unsafe overloads The `unsafe` modifier creates a separate overload in its own namespace. Safe and unsafe versions of the same function coexist the caller explicitly selects which one to invoke: ```kairo fn add(a: i32, b: i32) -> i32 { return a + b } fn add(a: i32, b: i32) unsafe -> i32 { return a << 1 + b << 1 // faster but semantically different } var x = add(10, 20) // calls the safe version var y = unsafe add(10, 20) // calls the unsafe overload ``` > [!NOTE] > `unsafe` overloads are not "unsafe memory" Tether still guarantees memory safety. The `unsafe` qualifier signals that the function may not uphold other invariants that the safe version does. See [Unsafe](/docs/language/unsafe/) for the full unsafe model. ## Const overloading restriction `const` and non-`const` methods with the same name and parameter types cannot coexist, use distinct names like `get()` and `get_mut()`. This restriction applies to named methods declared in Kairo source. An imported C++ class may have such a pair, and both members can be defined out of line (see [Overloading on mode](#overloading-on-mode)). **Place operators are exempt**, because they cannot be renamed: a place-returning operator (`[]`, `->`) may declare both a `self` overload (returning `*T`) and a `const self` overload (returning `*const T`), dispatched by receiver const-ness. See [Operators](/docs/language/operator-overloading/#const-overloading-operators). ```kairo class Foo { fn bar(const self) -> i32 { return 42 } fn bar(self) -> i32 { return 24 } // compile error: cannot overload const fn bar(const self, a: i32) -> i32 { return a } // ok: different parameter list ok fn op [](const self, index: i32) -> *const i32 { /* ... */ } // ok: place operator fn op [](self, index: i32) -> *i32 { /* ... */ } // ok: const-ness dispatch fn op +(self, o: Foo) -> Foo { /* ... */ } fn op +(const self, o: Foo) -> Foo { /* ... */ } // compile error: not a place operator } ``` ## Overload resolution Mode resolution follows C++ ([over.ics.rank]), so an imported overload set picks the same function in Kairo as it does in C++: | Argument | `x: T` | `@inout x: T` | `@move x: T` | | -------------------------- | ------ | ------------------- | ------------------- | | non-`const` lvalue | viable | **viable, preferred** | not viable | | `const` lvalue | viable | not viable | not viable | | rvalue (prvalue or xvalue) | viable | not viable | **viable, preferred** | ```kairo // std::vector::push_back(const int&) and push_back(int&&) var v: std::vector var n: i32 = 7 v.push_back(n) // lvalue -> push_back(const int&) v.push_back(1) // prvalue -> push_back(int&&) ``` ## Overloading on mode [Modes](/docs/language/functions-parameter-modes/) are part of a function's signature. `x: T`, `@inout x: T`, and `@move x: T` are three distinct overloads. A C++ class that declares `set(const int&)`, `set(int&)`, and `set(int&&)` gets three separate out-of-line definitions: ```kairo // cxx.hh: // class Widget { // void set(const int&); // void set(int&); // void set(int&&); // int at(size_t) const; // int& at(size_t); // }; ffi "c++" import "cxx.hh" fn Widget::set(x: i32) { } // const int& fn Widget::set(@inout x: i32) { } // int& fn Widget::set(@move x: i32) { } // int&& fn Widget::at(const self, i: usize) -> i32 { /* ... */ } // int at(size_t) const fn Widget::at(self, i: usize) -> *i32 { /* ... */ } // int& at(size_t) ``` The `at` pair shows the one exception to the [const overloading restriction](#const-overloading-restriction): when an imported declaration has a `const`/non-`const` pair, as standard containers do for `at`, `front`, `back`, `begin`, `end`, and `data`, receiver const-ness is part of the signature and both members can be defined out of line. C++ can't overload `f(T)` against `f(const T&)`, and in Kairo both are spelled `x: T`, so that ambiguity never arises in Kairo code. If an imported header declares both, the compiler reports an error at the import, naming the header, not at each call. Overriding an imported [virtual](/docs/language/classes-inheritance/#virtual-dispatch) uses the same spelling: ```kairo // cxx.hh: class Base { virtual void foo(int& x); }; class Derived derives Base { override fn foo(@inout x: i32) { x = 42 } } var d = Derived{} var n: i32 = 0 d.foo(&n) // n is 42 ``` ## See also - [Functions](/docs/language/functions/) - [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/) - [Operator Overloading](/docs/language/operator-overloading/) - [Where Clauses](/docs/language/where/) - [Unsafe](/docs/language/unsafe/) - [Generics](/docs/language/generics/) --- ## Parameter Passing Modes URL: https://www.kairolang.org/docs/language/functions-parameter-modes/ # Parameter passing modes A parameter can be declared in one of three modes. Together they cover every parameter form C++ can declare, so any C++ signature has an exact Kairo spelling. | Kairo | C++ | Callee may | Caller afterwards | | ------------- | ----------------- | -------------------- | ---------------------------- | | `x: T` | `T` or `const T&` | read | unchanged | | `@inout x: T` | `T&` | read, write | sees the callee's writes | | `@move x: T` | `T&&` | read, write, consume | cannot use the argument | ```kairo fn read(x: i32) -> i32 { return x + 1 } // T / const T& fn bump(@inout x: i32) { x += 1 } // int& fn consume(@move b: Buffer) -> usize { /* ... */ } // Buffer&& fn use() { var n: i32 = 5 read(n) // 6, n unchanged bump(&n) // n is now 6 read(n) // 7 var b = Buffer{} consume(b) // no marker; ownership moves b.size() // compile error: use after move } ``` ## Modes are not types `@inout` and `@move` are only allowed on parameters of a `fn` declaration. They cannot appear on locals, fields, return types, generic arguments, tuple elements, or in any other type position. No type `@inout T` exists, and a mode cannot be stored or returned. ```kairo var y: @inout i32 // compile error: '@inout' is a parameter mode, not a type var @inout y: i32 // compile error ``` ## How `x: T` is passed For a plain `x: T` parameter of a Kairo function, the compiler picks between passing by value and passing by `const T&`. Scalars, pointers, `fn` values and trivially copyable records go by value. A record that is not trivially copyable (a `string`, a vector, a map, a class with a copy constructor) goes by `const T&` when the function never mutates the parameter: no assignment to it or a field of it, no non-`const` method call on it, no `&x`, no `@inout` or `@move` argument, no `return x`, no use in a closure. A parameter the body does mutate gets its own copy, as before, and a `@move` class always goes by value, since taking ownership is the point. This is why Kairo has no separate mode for `const T&`. When the compiler passes a parameter by reference this way, it warns that the parameter is never mutated and offers a fix-it that adds `const`: ```kairo fn length(s: string) -> usize { return s.length() } // ^ warning: parameter 's' is never mutated; declare it 'const' fn length(const s: string) -> usize { return s.length() } // same code, no warning ``` A `const` parameter is a reference to the caller's object for the whole call. If the function changes that object some other way while the call runs, through `self` or a pointer, the parameter sees the change. A by-value copy would not. Some functions keep the by-value signature because something else fixes it, and the compiler neither infers the reference nor warns for them: `virtual` and `override` methods (and every method of a class with a polymorphic base), interface members, `ffi "c"` / `ffi "c++"` functions and functions with a calling convention, generic functions and members of generic types, generators and `async` functions, `-> !` and `@cold_path` functions, and `main`. The warning is not reported for the builtin and standard libraries. For a function declared in an [imported C++ header](/docs/language/c-cpp-calling/), the compiler doesn't choose. The parameter is passed exactly as the header declares it. A [fixed array](/docs/language/collections/#arrays-t-n) `[T; N]` is the exception: it is not a value type, so a plain `xs: [T; N]` parameter is an error. Take it as `const` or `@inout`, both of which pass by reference, or take a slice: ```kairo fn f(xs: [i32; 3]) { } // compile error: parameter 'xs' takes an array by value; // write 'const', '@inout', or take a slice fn f(const xs: [i32; 3]) { } // ok: read-only, by reference fn f(@inout xs: [i32; 3]) { } // ok: read-write, by reference fn f(xs: [i32;]) { } // ok: a view of any length ``` ## Call-site syntax | Parameter | Call | | ------------- | -------- | | `x: T` | `f(a)` | | `@inout x: T` | `f(&a)` | | `@move x: T` | `f(a)` | | receiver | `a.f()` | In argument position, `&x` says the call may mutate `x`. Which of two things it is depends on the parameter it is passed to: | Parameter | Argument | Meaning | | --------- | -------- | ------- | | `@inout x: T` | `f(&a)` | the `@inout` marker: `a` is passed by reference, no pointer is made | | `p: *T` | `f(&a)` | address-of: a safe, non-null pointer to `a` | | `p: *const T` | `f(&a)` | address-of, read through a const pointer | | `p: unsafe *T` | `f(unsafe &a)` | an unsafe pointer to `a`, outside the borrow rules | The marker is required, so every mutation of a caller's variable is visible where the call is made. A `const` `@inout`-free parameter and a `@move` parameter take no marker. `&` is rejected anywhere it means neither: ```kairo read(&n) // compile error: parameter 'x' of 'read' is not @inout bump(n) // compile error: '@inout' argument requires '&' const k: i32 = 5 bump(&k) // compile error: '@inout' requires a non-const lvalue bump(&10) // compile error: '@inout' requires an lvalue ``` `@move` takes no marker. The compiler already rejects any later use of the argument, so a marker would add nothing. The receiver is never marked. `fn f(self)` is a non-`const` method and `fn f(const self)` is a `const` method (`void f() const`). Both are called as `a.f()`: ```kairo class Counter { priv var n: i32 fn get(const self) -> i32 { return self.n } // int get() const fn tick(self) { self.n += 1 } // void tick() } var c = Counter{ n: 0 } c.tick() var v = c.get() ``` Overload resolution by mode and overloading on mode are covered in [Function Overloading](/docs/language/functions-overloading/#overload-resolution). ## Reference returns from C++ Modes don't exist in return position. A C++ function that returns a reference is written, on the Kairo side, with one of three return spellings: | C++ return | Kairo return | Value category of a call | | ---------- | ------------ | ------------------------ | | `T&` | `ffi::ref` | lvalue | | `const T&` | `ffi::ref` | lvalue | | `T&&` | `ffi::mref` | xvalue | These are not types: nothing in Kairo can hold a reference, so a variable, parameter, field, alias or generic argument can't be one, and `typeof(f())` is `T`. They appear only as the whole return type of a Kairo definition of a function C++ declares (an out-of-line `fn Widget::at`, or a `fn ns::f` for a function in a C++ namespace) and of an override of a C++ virtual method. The return type must match the C++ declaration exactly; the compiler's fix-it gives the right spelling. The body returns the place itself, with no `&` (`return self.items[i]`); returning a temporary or a local is an error, because the caller would hold a reference to nothing. ```kairo ffi "c++" import "widget.h" // int& at(size_t); int at(size_t) const; fn Widget::at(self, i: usize) -> ffi::ref { return self.items[i] } fn Widget::at(const self, i: usize) -> i32 { return self.items[i] } class D derives Base { // virtual const std::string& name() const; pub var label: cxx::std::string override fn name(const self) -> ffi::ref { return self.label } } ``` [Calling an imported function that returns a reference](/docs/language/c-cpp-calling/#calls-that-return-a-reference) needs no spelling at all: the call is a place. Because a `T&&` return is an xvalue, `f(g())` where `g` returns `T&&` selects `f`'s `@move` overload, as it does in C++. The call itself is usable as the referenced value, the same way `v[0]` is: as an operand, and as the target of an assignment or compound assignment. ```kairo ffi "c++" import ; var v: cxx::std::vector v.push_back(1) v.at(0) = 3 // assigns through the returned int& v.at(0) += 2 // 5 var x = v.at(0) + 1 // 6 ``` The same holds for `*p` and for operators that return a reference, such as `cout << x`. ## `@move` is checked `@move` is checked against the parameter's type, not just recorded: - **[Move-only class](/docs/language/classes-lifecycle/#the-four-categories):** `@move` is redundant, since passing already consumes the argument (see [Ownership](/docs/language/ownership/#function-parameters)), but it's allowed and checked. - **Copy-only class:** `@move` is a compile error. - **Generic `T`:** `@move` is the only way to declare that the function consumes its argument. The body can then consume `x` whatever `T` turns out to be. In every case the call counts as the consuming use, and any later use of the argument in the caller is a [use-after-move error](/docs/language/ownership/#moved-from-state). ## Imported-only forms Some C++ forms can be imported and called from Kairo but can't be declared in Kairo source, including as out-of-line definitions: - `const T&&` parameters. They bind rvalues without consuming them, and C++ uses them almost only as deletion targets. - Functions returning a reference. Kairo has no `std::move`, because whether a transfer moves is decided by the type, not by the expression, so it never needs to return one. Kairo also deliberately has no call-site marker for `@move` and no separate mode for `const T&`. ## See also - [Functions](/docs/language/functions/) - [Default, Named, and Variadic Parameters](/docs/language/functions-parameters/) - [Function Overloading](/docs/language/functions-overloading/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/) - [Ownership](/docs/language/ownership/) - [Pointers](/docs/language/pointers/) - [C/C++ Interop](/docs/language/c-cpp/) --- ## Default, Named, and Variadic Parameters URL: https://www.kairolang.org/docs/language/functions-parameters/ # Default, Named, and Variadic Parameters Parameters can have default values, arguments can be passed by name at the call site, and the `...` prefix on a parameter name accepts any number of arguments of the same type. ## Default parameters Parameters can have default values. When a caller omits a defaulted argument, the default is used: ```kairo fn greet(name: string = "world") { std::io::println(f"Hello, {name}!") } greet() // "Hello, world!" greet("Alice") // "Hello, Alice!" ``` A default is evaluated once per call that omits that argument. Any parameter may have a default, not only trailing ones; a defaulted parameter that comes before a required one is skipped by naming the later argument (see [Named arguments](#named-arguments)). ### A default stands alone A default argument may not mention another parameter or `self`. It is evaluated with no access to the call's other arguments: ```kairo fn a(x: i32, y: i32 = x) { } // compile error (SC106E) fn m(self, y: i32 = self.v) { } // compile error (SC106E) ``` When a default depends on another argument, use an [overload](/docs/language/functions-overloading/) instead: ```kairo fn a(x: i32, y: i32) { } fn a(x: i32) { a(x, x) } ``` A default also may not be a [slice literal](/docs/language/collections/#how-long-a-slice-literals-storage-lives) (`[T;]`), since the slice would view a temporary. Use an owning `[T]`: ```kairo fn f(xs: [i32;] = [1, 2]) { } // compile error fn f(xs: [i32] = [1, 2]) { } // ok ``` ### Defaults apply to the whole function Defaults belong to the function, not to a point in the file. A default added by a later declaration applies to every call, including calls written above that declaration. This differs from C++, where a default is only visible after the declaration that introduces it. Each parameter may be given a default on any one declaration of the function. Defaults from different declarations accumulate: ```kairo fn f0(i: i32, j: i32, k: i32 = 3) -> i32 fn f0(i: i32, j: i32 = 2, k: i32) -> i32 fn f0(i: i32 = 1, j: i32, k: i32) -> i32 f0() // same as f0(1, 2, 3) f0(7) // same as f0(7, 2, 3) ``` Out-of-line class methods have one more restriction: their defaults go on the in-class declaration. See [Classes](/docs/language/classes-out-of-line/#rules). ### Evaluation order Explicit arguments are evaluated left to right in the order they are written at the call site, whichever parameter each one names. Defaults for omitted arguments are evaluated after every explicit argument, in parameter order: ```kairo fn g(a: i32 = stamp(1), b: i32) -> i32 g(b: stamp(4)) // stamp(4) runs first, then the default stamp(1) fn h(a: i32, b: i32) -> i32 h(b: stamp(1), a: stamp(2)) // stamp(1) runs first: written order, not parameter order ``` ### Defaults on imported C++ functions An imported C++ function keeps its C++ defaults, and C++ applies them. C++ can only leave out trailing arguments, so naming a later parameter while an earlier defaulted one is omitted is an error ([SC107E](/docs/language/diagnostics/#sc107e-a-named-argument-skips-a-defaulted-parameter-of-an-imported-c-function)): ```cpp // lib.hh void blit(int x, int y = 0, int scale = 1); ``` ```kairo blit(4, scale: 2) // compile error (SC107E): 'y' would be skipped blit(4, y: 0, scale: 2) // ok blit(4) // ok: trailing defaults left to C++ ``` Pass the earlier arguments explicitly. ## Named arguments Arguments can be passed by name at the call site. Positional arguments must come before named arguments, matching C++ conventions: ```kairo fn create_user(name: string, age: i32 = 18, country: string = "USA") -> User { return User { name, age, country } } create_user("Alice") // age=18, country="USA" create_user("Bob", 25) // country="USA" create_user(name: "Eve", country: "UK") // age=18 create_user("Grace", 22) // country="USA" create_user(name: "Frank", age: 30, country: "CA") // all explicit ``` Naming does not need defaults. Any parameter can be named, so a call can list its arguments in any order; they are still evaluated left to right as written (see [Evaluation order](#evaluation-order)). A name that matches no parameter is an error: ```kairo fn sub(a: i32, b: i32) -> i32 { return a - b } sub(b: 1, a: 3) // 2: matched by name, not position sub(x: 1, a: 3) // error [SC019E]: no parameter named 'x' ``` --- ## Variadic Functions The `...` prefix on a parameter name accepts any number of arguments of the same type. Inside the body, `...xs: T` is a [slice](/docs/language/collections/#slices-t) `[T;]` over the run of arguments. The slice is passed by value and is valid for the duration of the call; it views the arguments, so do not store it or return it. ```kairo fn sum(...xs: i32) -> i32 { var total = 0 for i in 0..xs.len { total += xs.data[i] } return total } sum(1, 2, 3) // 6 sum(10, 20, 30, 40) // 100 sum() // 0: an empty pack is a zero-length slice ``` Parameters after a pack are keyword-only, since every positional argument goes into the pack: ```kairo fn join(...parts: string, sep: string = " ") -> string { /* ... */ } join("a", "b", "c") // "a b c" join("a", "b", sep: ", ") // "a, b" ``` ### Generic variadic functions Combine `...` with [generic](/docs/language/generics/) type packs to accept arguments of different types: ```kairo interface Named { fn op as(const self) -> string } fn <...T impl Named> print_all(...args: T) { for arg in args { std::io::println(arg as string) } } print_all(Tag(1), Mark(), Tag(2)) // prints each on a new line (Tag, Mark impl Named) ``` The parameter is a pack: one value per argument, each with its own type, and `T` stands for that list of types. A pack is not a value on its own: the body iterates it with `for` (the loop body runs once per element, at that element's type) or forwards it with `...` (below). An element is checked like any other [generic](/docs/language/generics/#type-parameter-constraints) parameter: the body may use only what the pack's bounds grant, and every element must satisfy them. In the example above, `arg as string` is `Named`'s `op as`; without the `impl Named` bound it is an error in the body. The element types are deduced from the arguments; writing them as generic arguments (`print_all(...)`) is not supported yet. A type pack is only ever written expanded (`Box`) or as the type of a `...` parameter: a field, variable, return value or ordinary parameter cannot have a pack as its type. ### Pack expansion and forwarding A pack expands with a **postfix** `...` in expression position. Declaration is prefix (`...args`), use is postfix (`args...`). The most common case is forwarding a pack to another call: ```kairo fn <...T impl Named> log_all(...args: T) { print_all(args...) // forwards every element as a separate argument } ``` A forwarded pack must meet the bounds of the pack it is forwarded to, through its own: `log_all` needs `impl Named` because `print_all` does. Without it, `print_all(args...)` is an error in `log_all` (R051E), as passing an unbounded `T` to a bounded generic is (see [Generics](/docs/language/generics/#type-parameter-constraints)). Each element is passed by its own type's transfer rules, as any argument is (see [Ownership](/docs/language/ownership/#function-parameters)): a COPY element is copied and stays live, a MOVE element is moved. So a body may expand the same pack more than once when its elements are COPY; the last expansion may move instead of copying, since nothing reads the elements after it. A pack parameter takes no passing mode yet: `@inout ...args: T` and `@move ...args: T` are compile errors ("'@inout' on pack parameter 'args' is not supported yet"). An expansion is written only as a call argument, and only of a pack parameter. The same postfix form appears in type position for pack-typed signatures (`-> Outcome`, `derives Base`). The split mirrors the [token-macro splat](/docs/language/macros/#variadic-macros-and-pack-expansion): `...` before a name declares a pack, `...` after an expression expands one. ## See also - [Functions](/docs/language/functions/) - [Parameter Passing Modes](/docs/language/functions-parameter-modes/) - [Function Overloading](/docs/language/functions-overloading/) - [Generators](/docs/language/functions-generators/) - [Function Declarations](/docs/language/functions-declarations/) - [Generics](/docs/language/generics/) - [Macros](/docs/language/macros/) - [C/C++ Interop](/docs/language/c-cpp/) --- ## Generics URL: https://www.kairolang.org/docs/language/generics/ # Generics How type parameters of [generic classes](/docs/language/classes/#generic-classes) and functions are constrained. ## Type parameter constraints A generic body may use only what its bounds grant. The body is checked once, where it is defined, against its bounds, never per instantiation. Calling a method no bound declares, copying a `T` without a copy bound, or declaring `var x: T` without a constructor bound is a compile error in the generic itself. So is an operator or a conversion on a `T` (`a == b`, `a + b`, `a as string`) that no bound declares, a null test on a `T` (only a `T?` can be null), and a `match` pattern other than a binding or `_` on a `T`. So is passing a `T` (or forwarding a pack) to a generic whose bound it does not carry: in `fn fwd(x: T) = one(x)` with `fn one(x: T)`, `fwd`'s `T` must be bounded by `Named` or by an interface that derives it (R051E when `T` has no bound, with a fix-it adding it; R025E when its bounds do not include one). A bound that declares the operator (`fn op ==(const self, other: Self) -> bool`) makes it a call through the bound, and a `derives` bound whose base declares it makes it a call of the base's operator. See [Generic Bodies](/docs/language/interfaces/#generic-bodies). An f-string is the exception: a hole on a value whose type only the instantiation knows (a `T`, or a member reached through one) is formatted per instance, with the same rules as a concrete value (builtin types, strings, pointers, plain enums, `repr()`, an `op as` to `string`). An instance whose type has no way to format is an error at that instance. A format spec on such a hole (`f"{x:>4}"`) is not supported yet. ```kairo fn show(x: T) -> string { return f"value: {x}" } // formatted per instance show(42) // "value: 42" show("hi") // "value: hi" ``` A generic type at a dependent argument is not opaque: a `match` on a `Rep` names `Rep`'s variants, and `==` on two `Rep` compares their variants, as for any [ADT](/docs/language/enums-adt/). **Implicit capabilities.** Every type parameter may be destroyed and moved without saying so. Instantiating with a type whose `op finally` is `= delete`, or whose category is NON_TRANSFER, is an error at the instantiation site. It names the generic's implicit requirement, not a line inside its body. (Opt-out syntax: TBD.) Two kinds of bounds exist: **Kind bounds** restrict `T` to a specific category of type declaration: ```kairo fn process(item: T) { ... } fn serialize(item: T) { ... } fn stringify(item: T) { ... } fn inspect(item: T) { ... } ``` An argument of another kind is an error (SC292E) where the generic is used. A bound may be a rooted path, `fn `, naming the interface from the file's root. **Interface bounds** restrict `T` to types that satisfy a given [interface](/docs/language/interfaces/). The standard library will provide interfaces describing [lifecycle capabilities](/docs/language/classes-lifecycle/#lifecycle-categories), allowing constraints like "T must be copyable" or "T must be movable" to be written as interface bounds. The exact names and shapes of these interfaces are still being finalized in `std` write your own if you need them now: ```kairo interface Copyable { @copy fn Copyable(self, const other: Self) } interface Defaultable { fn Defaultable(self) } fn store(item: T) -> T { ... } ``` See [Requires Clauses](/docs/language/requires/) for the full constraint system. ### Mixins: a base that calls its derived class A generic base can call methods of the class that derives it (the C++ CRTP pattern) when its parameter is bounded by both `derives` on the base itself and an interface that declares those methods. The `derives` bound lets the base cast `&self` down to `*X` statically, with no vtable; the `impl` bound is what lets the body call `weight()` on it: ```kairo interface Weighted { fn weight(const self) -> i32 } class impl Weighted> Counter { fn dyn(self) -> *X { return &self as *X } // static downcast, no vtable fn bump(self) -> i32 { return self.dyn()->weight() } } class Node derives Counter impl Weighted { fn weight(const self) -> i32 { return 5 } } ``` Without the `impl Weighted` bound, `self.dyn()->weight()` is an error in the base: the body may use only what its bounds grant. See [Casting: the CRTP downcast](/docs/language/casting/#downcasting-base-to-derived) for the cast's rules. ## Value parameters A generic parameter can be a compile-time **value** instead of a type: `eval N: T`. Its argument must be [evaluable at compile time](/docs/language/eval/), a literal, an `eval` constant, or arithmetic over them, and inside the generic `N` is a constant of type `T`, usable as an array length: ```kairo eval CAPACITY = 16 class Ring { var items: [T; N] fn capacity(const self) -> usize { return N } } fn scaled() -> usize { return N * 2 } var r = Ring() // the same type as Ring<16, i32> var s = scaled<4>() // 8 ``` A function's value parameter is given explicitly (`scaled<4>()`) or deduced from an array argument's length (`fn sum(const a: [i32; N])` called with a `[i32; 3]`). A `const` binding is not evaluable at compile time, so it cannot be a value argument; `const N: T` is not a parameter spelling either (write `eval N: T`). ### Computed lengths and arguments An array length or value argument can be computed from value parameters, `eval` constants and calls of `eval` functions: ```kairo eval fn twice(x: usize) -> usize { return x * 2 } class Buf { var data: [i32; N + 1] // one spare slot } fn make() -> Buf { return Buf() } fn table() { var t: [i32; twice(3)] // six elements } ``` Once the parameters have values the length is a number again: `Buf<3>`'s `data` is a `[i32; 4]`, the same type as any other `[i32; 4]`. A length the compiler does not compute itself, because it calls an `eval fn` or reads an `eval` constant that does, is identified by how it is written: `[i32; twice(3)]` is one type wherever it is written, but it is not `[i32; 6]`, even though `twice(3)` is 6 (as in C++, where a dependent expression is compared by its form). A computed length is not deduced: `fn f(a: [i32; N + 1])` needs `N` from somewhere else, such as `f<3>(a)`. A computed length or argument works in any type: a local's, a field's, a parameter's or return type, a file-scope variable's (`var a: [i32; twice(2)]` as a field). The functions and constants it reads are compiled ahead of the declaration that uses them. What cannot work is a cycle: a field of `R` whose length calls an `eval fn` that itself needs `R` complete (`sizeof R`, a local `R`, a method of `R`) is an error, since `R` does not exist yet where its own field is laid out. ### Eval classes as value parameters A value parameter can also have the type of an [eval class](/docs/language/eval/#eval-in-classes), when every field is `pub`, no field points to mutable memory, and every constructor is `eval`: ```kairo struct Config { pub var size: i32 pub var label: string eval fn Config(self, size: i32, label: string) { self.size = size self.label = label } } eval SMALL = Config(4, "small") class Widget { fn size(const self) -> i32 { return C.size } } var w = Widget() ``` The argument is an `eval` binding of the class or a call of its `eval` constructor (`Grid`, `Widget`, string literals included). Two arguments with the same value are the same type: `Widget` is `Widget`, because `SMALL` is that same constructor call over the same literals. A binding computed by an `eval fn` is compared by its name instead, as a computed length is. A class that breaks a rule is an error naming the first field or constructor at fault. --- ## See also - [Generic Classes](/docs/language/classes/#generic-classes) - [Interfaces](/docs/language/interfaces/) - [Interface Requirements](/docs/language/interfaces-requirements/) - [Requires Clauses](/docs/language/requires/) - [Where Clauses](/docs/language/where/) - [Generic Functions](/docs/language/functions/#generic-functions) - [Generic Structs](/docs/language/structures/#generic-structs) - [Class Lifecycle](/docs/language/classes-lifecycle/#lifecycle-categories) A vector, set or map type can head a static path: `[i32]::with_capacity(8)` is `Vector::with_capacity(8)`, and likewise `{T}::f()` and `{K: V}::f()`. --- ## Imports URL: https://www.kairolang.org/docs/language/imports/ # Imports The `import` statement brings names from other modules and external libraries into the current scope. Imports are how you access code defined in other files and C/C++ headers. See [Modules](/docs/language/modules/) for how files organize into module namespaces and how the module system resolves import paths. ## Import Forms ```kairo ``` The first word after `import` says where the path is looked for: nothing (a library or search directory), `self::` (the importing file's directory) or `module::` (the importing file's [module root](#module-imports)). Every other part of an import combines with either anchor: `import self::json::{parse, Value}`, `import module::util as u`, `import self::shapes::*`. ## Resolution Semantics Each import form looks in **exactly one place**: | Form | Looks in | |------|----------| | `import Foo` | the libraries and search directories: every [named library](/docs/language/modules/#naming-a-library), the working directory, every `-I` directory, `std` and `builtin` | | `import self::Foo` | the importing file's own directory | | `import module::Foo` | the importing file's [module root](#module-imports): the nearest directory, at or above it, that holds a `module.k` | In that one place, `Foo` is the file `Foo.k` or the [library entry](/docs/language/modules/#library-entry-files) `Foo/module.k`. If both exist there, the import is an error (R005E) naming the two; rename or remove one. A plain import never looks beside the importing file. Because the working directory is a search directory, a project compiled from its top directory (`kairo main.k`) reaches its top-level files with plain imports (`import router`), but a file in a subdirectory reaches the file next to it only as `import self::helpers`. A path that starts with a [library's name](/docs/language/modules/#naming-a-library) (`import geo::shapes`) resolves inside that library, and a file inside a library also reaches the library's files by their path in it (`import shapes`, from anywhere in the library). Since an anchored import never consults the search directories, adding a file to a library or an `-I` directory can never change what `import self::x` or `import module::x` means, and a file beside the importer can never change what a plain `import x` means. Two different files answering one plain import from two search directories are an error at the import (R017E); the compiler never picks one. ### Resolution with `::` `import Foo::bar` resolves the longest leading part of the path that names a module, then looks up the rest inside it: 1. Resolve `Foo::bar` as a module (`Foo/bar.k` or `Foo/bar/module.k`); if there is none, 2. resolve `Foo` (`Foo.k` or `Foo/module.k`) and look for the symbol `bar` inside it. The anchor applies to the whole path: `import self::Foo::bar` looks for `Foo/bar.k` beside the importing file, then for the symbol `bar` in the `Foo.k` beside it. ```kairo // Given, beside this file: // math.k contains `fn add(...)` // vector/module.k library entry ``` ### Sibling imports ```kairo // app/main.k, with app/util.k and app/net/socket.k beside it ``` `self::` names the importing file's directory: the file `x.k` or the library `x/module.k` next to it, and anything below it. It is the form for files that belong together but are not a library of their own. ### Module imports ```kairo // project/module.k is empty: project/ is a module // project/net/http/client.k ``` `module::` starts at the importing file's **module root**: the nearest directory, at or above the file, that holds a `module.k`. It is the same directory that decides who shares `prot` declarations ([Visibility Scopes](/docs/language/modules/#visibility-scopes)), so a file reaches any file of its own module the same way from any depth. The `module.k` may be empty. A file with no `module.k` above it belongs to no module, and `import module::x` there is an error (R069E) that says so; add a `module.k`, or use `self::` for a file beside it. ### Migrating from sibling-first imports Older compilers looked for a plain `import Foo` beside the importing file first. A plain import that no library or search directory answers, but that finds `Foo` beside the importing file, still resolves to that file, but reports an error (R068E) with a fix-it that inserts `self::`: ``` app/main.k:1:8: error [R068E]: 'util' is not in any library or search directory; it is the file beside this one, which a plain import no longer reaches: write 'self::util' ``` The fallback exists only so one stale line does not cascade into unresolved-name errors. When a library or search directory does hold `Foo`, the plain import resolves there and the file beside the importer is ignored. ### Removed: `import module Foo` `import module Foo` (with a space) forced the library form, `Foo/module.k`. It is removed: now that `Foo.k` and `Foo/module.k` in one place are an error, nothing is left to force. Writing it is an error (S089E) with a fix-it that deletes `module`; then choose the form for where `Foo` is (`import Foo`, `import self::Foo` or `import module::Foo`). Do not confuse it with `import module::Foo`, written with `::`, which anchors at the module root. ## Visibility on Imports Imports default to **`priv`** (private). A private import brings names into the current file but does not re-export them to consumers of this module: ```kairo priv import std::collections // default, only visible in this file pub import std::collections // re-exported to consumers prot import std::platform // visible to sibling files in same library ``` An import makes a name reachable, not visible: a name the imported file declares `priv` (or leaves unmarked outside a module), or `prot` in another [module](/docs/language/modules/#visibility-scopes), is an error where it is used (R047E for a bare name from `import m::*`, SC242E for `m::name`), with a fix-it that makes the declaration `pub`. ### Re-export Pattern Use `pub import` explicitly in library entry files to curate the public API: A re-export also carries the `extend` blocks of the file it names; a private import does not. A macro is imported by its `!` name: `import Foo::mac!`, or in a list `import Foo::{mac!, f}`. Without the `!` the name is a declaration, not the macro. A file may be named like a primitive type (`f8.k`, `i32.k`): import it like any other. Since `i32::` names the type, a plain `import self::i32` must give the module another name with `as`, or import its contents with `::*`. ```kairo // network/module.k pub import self::tcp // consumers of "network" can access tcp pub import self::udp // consumers of "network" can access udp priv import self::dns // implementation detail, not re-exported ``` Consumers see only the public surface: ```kairo network::tcp::connect("example.com", 80) // ok network::udp::send_packet(data) // ok // network::dns::lookup(...) // compile error: not exported ``` ### Why Private by Default Default-private prevents transitive dependency leakage. If `network.k` imports an internal utility module, consumers of `network` don't accidentally see that utility in their namespace. Public re-export is an explicit, intentional choice by the module author. ## Selective Imports Selective imports bring specific items from a module: ```kairo ``` Each item can have its own alias: ```kairo ``` Items can reference nested paths relative to the base: ```kairo ``` Here `HashMap` resolves as `std::collections::HashMap` and `LinkedList` resolves as `std::collections::list::LinkedList`. A wildcard inside a selective list is valid but unusual: ```kairo ``` ## Wildcard Imports ```kairo ``` Brings all public symbols from `math` into the current scope. Use sparingly, it obscures where names come from and can cause collisions. **Prefer selective imports.** ## Aliased Imports ```kairo m::Vector3(1.0, 2.0, 3.0) ``` The alias replaces the module name in the current scope. The original name (`math`) is **not** available, only `m`. ## FFI Header Imports Each `ffi` import names one header; write one line per header. The language string and the import, declaration or block it applies to must be on the same line. A list (`import {"a.h", "b.h"}`) is an error. C and C++ headers are imported via the [`ffi` keyword](/docs/language/c-cpp-calling/#the-ffi-keyword): ```kairo ffi "c++" import "graphics.hh" ffi "c" import "legacy_api.h" ``` All declarations from the header are imported into the current namespace. Use `as` to namespace the import: ```kairo ffi "c++" import "graphics.hh" as gfx gfx::create_window(800, 600) gfx::RenderContext() ``` ### C++ `std` Namespace If a C++ header defines names in the `std` namespace, those collide with Kairo's `std` module. The C++ standard library is accessible through `cxx::std`: ```kairo std::io::println("Kairo") cout << "C++" << endl ``` FFI imports of headers that define names in `std` are automatically redirected to `cxx::std`: ```kairo ffi "c++" import "iostream" // imported into cxx::std, not std ``` A name a header brings into a namespace with a using-declaration is a member of that namespace, as in C++. `` puts the C library's `sqrt` in `std` with `using ::sqrt;`, so `cxx::std::sqrt(x)` finds it. See [C/C++ Interop](/docs/language/c-cpp/) for the full FFI model. ## FFI Linkage Declarations The `ffi` keyword also applies foreign linkage to individual declarations or blocks: ```kairo // Single declaration ffi "c++" fn create_window(i32, i32) -> *Window // Block of declarations ffi "c++" { fn gl_init() fn gl_clear(u32) class Renderer { fn draw(self, *Mesh) } } ``` Declarations inside an `ffi` block are parsed normally but stamped with C/C++ linkage. See [C/C++ Interop](/docs/language/c-cpp-calling/#constraints-and-safety) for details on FFI constraints and capabilities. ## Import Cycles Imports may form a cycle: `a` imports `b` while `b` imports `a`, a longer chain, or a file that imports itself. An import never needs to come "first", so the order of `import` lines and of files does not matter. Every module on a cycle sees the others' public declarations, so functions can call each other across it, a type can name a type from the other side, and a `pub import` re-exports through it: ```kairo // node.k pub struct Node { pub var owner: unsafe *Tree; pub var v: i32 } // tree.k pub import node::* pub struct Tree { pub var root: unsafe *Node; pub var n: i32 } // main.k ``` A cycle compiles with a warning, [R001W](/docs/language/diagnostics/#r001w-import-cycle), on the import that closes it. The warning names the cycle and suggests moving the shared declarations into a third module. A file that imports itself gets the same warning, with a fix-it removing the import, since a file always sees its own declarations. `-fno-import-cycles` turns every cycle into the error R001E. See [Circular Dependencies](/docs/language/modules/#circular-dependencies). ## Import Reference | Form | Resolves to | Notes | |------|-------------|-------| | `import Foo` | `Foo.k` or `Foo/module.k` in a library or search directory | Never beside the importer (R068E) | | `import self::Foo` | `Foo.k` or `Foo/module.k` beside the importing file | | | `import module::Foo` | `Foo.k` or `Foo/module.k` at the module root | R069E outside any module | | `import Foo::bar` | Symbol `bar` in `Foo` | Same place as `import Foo` | | `import Foo::{a, b}` | Symbols `a`, `b` in `Foo` | Per-item aliases supported | | `import Foo::*` | All public symbols from `Foo` | Avoid; prefer selective imports | | `import Foo as m` | `Foo`, aliased to `m` | Original name unavailable | | `import module Foo` | removed | S089E; fix-it deletes `module` | | `ffi "c++" import "h.hh"` | C++ header | Optional `as` namespace | | `ffi "c++" fn foo(...)` | Single decl with C++ linkage | | | `ffi "c++" { ... }` | Block of decls with C++ linkage | | Imports may form cycles; see [Import Cycles](#import-cycles). ## See also - [Modules](/docs/language/modules/) - [Circular Dependencies](/docs/language/modules/#circular-dependencies) - [Library Entry Files](/docs/language/modules/#library-entry-files) - [Module Visibility](/docs/language/modules/#module-visibility) - [C & C++ Interoperability](/docs/language/c-cpp/) - [The `ffi` keyword](/docs/language/c-cpp-calling/#the-ffi-keyword) - [Namespace mapping](/docs/language/c-cpp-calling/#namespace-mapping) --- ## Interface Requirements URL: https://www.kairolang.org/docs/language/interfaces-requirements/ # Interface Requirements An interface body contains method signatures (including generic methods), static function signatures, operator signatures, constructor requirements, and [associated types](/docs/language/interfaces/#associated-types). This page covers the operator, constructor, static, `Self` and panicking requirements. --- ## Operators in Interfaces Interfaces can require operator overloads: ```kairo interface Equatable { fn op ==(const self, other: Self) -> bool } interface Convertible { fn op as(self) -> string } ``` `Self` in an interface signature refers to the conforming type. A class that `impl Equatable` must provide `fn op ==(const self, other: Self) -> bool` where `Self` resolves to that class. See [Operators](/docs/language/operator-overloading/) for the full list of overloadable operators. --- ## Constructors in Interfaces Interfaces can require constructor signatures: ```kairo interface Defaultable { fn Defaultable(self) } interface Cloneable { fn Cloneable(self, source: T) } ``` A conforming type must have a constructor that matches the parameter list. The constructor name in the implementation uses the type's own name, not the interface name: ```kairo interface Defaultable { fn Defaultable(self) } class Config impl Defaultable { var timeout: i32 fn Config(self) { // satisfies Defaultable's constructor requirement self.timeout = 30 } } ``` Only the conforming type's own constructors count; a base class's constructors do not. A type that declares no constructor at all has the implicit one (when every field can be built from nothing; see [Default Initialization](/docs/language/variables/#default-initialization)), so it satisfies a requirement with no parameters (`fn Defaultable(self)`) and nothing else. Built-in types such as `i32` and `bool` satisfy no constructor requirement, because `i32()` is not a call in Kairo; use `x as i32` to convert. Inside a generic body, `T(args)` constructs a `T` when one of `T`'s bounds has a constructor requirement taking that many arguments: ```kairo fn fresh() -> T { return T() } ``` ### Lifecycle attributes on constructor requirements Constructor requirements can carry `@copy` or `@move` attributes to require a specific lifecycle category. This is how you express "T must be copyable" or "T must be movable" as an interface bound: ```kairo interface Copyable { @copy fn Copyable(self, const other: Self) } interface Movable { @move fn Movable(self, other: Self) } fn store(item: T) -> T { return item } fn consume(item: T) { } ``` A `@copy` requirement is satisfied only by COPY types. A `@move` requirement is satisfied by COPY and MOVE types; a copy is a valid move. NON_TRANSFER types satisfy neither. Keep lifecycle requirements separate from a default constructor requirement. Putting `fn Copyable(self)` in `Copyable` would make "copyable" also mean "default-constructible", and the bound would reject every copyable type without a default constructor. Require default construction separately, with `Defaultable` above, where a body needs it. The standard library will provide canonical lifecycle interfaces; these are just examples. See [Lifecycle Categories](/docs/language/classes-lifecycle/#lifecycle-categories) for the underlying model. --- ## Static Methods in Interfaces Interfaces can require static methods: ```kairo interface Parseable { static fn from_string(input: string) -> Self static fn from_bytes(data: [byte]) -> Self } class Timestamp impl Parseable { var epoch: i64 fn Timestamp(self, epoch: i64) { self.epoch = epoch } static fn from_string(input: string) -> Timestamp { // parsing logic return Timestamp(0) } static fn from_bytes(data: [byte]) -> Timestamp { // parsing logic return Timestamp(0) } } ``` --- ## Return Types with `Self` Interface methods can use `Self` as a return type. `Self` resolves to the conforming type a class that `impl Chainable` and returns `Self` returns its own type: ```kairo interface Chainable { fn then(self, next: Self) -> Self } class Pipeline impl Chainable { fn then(self, next: Self) -> Self { // Self resolves to Pipeline return self } } ``` Kairo has no user-visible reference types [Tether](/docs/language/tether/) infers reference semantics where needed. In practice this means `Self` returns enable fluent chaining without `->` or explicit dereferencing: ```kairo interface Chainable { fn then(self, next: Self) -> Self } class Pipeline impl Chainable { var steps: i32 fn Pipeline(self) { self.steps = 0 } fn then(self, next: Self) -> Self { self.steps += 1 return self } fn run(self) -> i32 { return self.steps } } fn main() -> i32 { var other = Pipeline() var another = Pipeline() return Pipeline().then(other).then(another).run() } ``` To return a [pointer](/docs/language/pointers/) to the conforming type, use `*Self`: ```kairo interface Duplicable { fn clone(self) -> *Self } ``` --- ## Panicking Requirements A requirement that may [panic](/docs/language/panic/) must declare its panic set, `panic(E1, E2)`. A bare `panic` on a requirement is an error: a requirement has no body to infer a set from, and the set is the contract every conformer is held to. ```kairo struct ReadError { var path: string fn op panic (const self) -> string { return f"cannot read {self.path}" } } interface Source { fn read(self, path: string) panic(ReadError) -> string } class Disk impl Source { fn read(self, path: string) panic -> string { // set inferred: ReadError if !exists(path) { panic ReadError { path: path } } return load(path) } } class Memory impl Source { fn read(self, path: string) -> string { return "" } // ok: no panic at all } ``` A conforming method may infer its set, but the set must be a subset of the requirement's. Panicking with a type outside it is an error at the conformer. A generic interface's requirement may name the interface's own type parameters in its set. A conformer is held to it at the arguments it conforms to, and a [generic body](/docs/language/panic/#generic-functions) calling it through a bound panics with it at the bound's arguments: ```kairo interface Source { fn read(self) panic(E) -> i32 } class File impl Source { fn read(self) panic(IOError) -> i32 { ... } // ok: E = IOError } fn > twice(src: T) panic -> i32 { // panics with IOError return src.read() + src.read() } ``` --- ## See also - [Interfaces](/docs/language/interfaces/) - [Operator Overloading](/docs/language/operator-overloading/) - [Classes: Lifecycle](/docs/language/classes-lifecycle/) - [Generics](/docs/language/generics/) - [Tether](/docs/language/tether/) --- ## Built-in Macros URL: https://www.kairolang.org/docs/language/macros-builtin/ # Built-in Macros Kairo provides a set of compiler-intrinsic macros for common tasks. Builtin names are reserved: defining a macro with a builtin's name (`macro first!(...)`, `macro paste!(...)`) is a compile error. Qualified macros (`mymod::first!`) do not collide; builtins only claim the unqualified names. ## Token manipulation | Macro | Description | |---|---| | `paste!(a, b)` | Paste identifier tokens into a single identifier | | `stringify!(a)` | Convert a token to a string literal | | `unstringify!(s)` | Convert a string literal back to tokens | ```kairo var name = paste!(my, _var) // becomes: my_var var s = stringify!(some_ident) // becomes: "some_ident" ``` `paste!` joins the spelling of every argument token and produces one identifier; the result must be a valid identifier. > [!WARNING] > `unstringify!` converts a string into raw tokens that are injected into the source. This is a potential injection risk only use with trusted, compile-time-known strings. ## Variadic helpers | Macro | Description | |---|---| | `count!(...args)` | Number of arguments | | `first!(...args)` | First argument | | `last!(...args)` | Last argument | | `rest!(...args)` | All arguments except the first | | `butlast!(...args)` | All arguments except the last | ```kairo count!(a, b, c) // 3 first!(a, b, c) // a last!(a, b, c) // c rest!(a, b, c) // b, c butlast!(a, b, c) // a, b ``` These builtins expand macro invocations in their arguments first, then split on top-level commas, so they compose: ```kairo count!(rest!(a, b, c)) // 2 first!(rest!(a, b, c)) // b ``` `stringify!` and `defined!` are the exceptions: they operate on their arguments' raw tokens (quoting and name-probing would be destroyed by expansion). ## Source location | Macro | Description | |---|---| | `file!` | Current file path as a string literal | | `line!` | Current line number as an integer literal | | `column!` | Current column number as an integer literal | | `module_path!` | Current module path as a string literal | ```kairo std::io::println(f"logged from {file!}:{line!}") ``` ## Diagnostics | Macro | Description | |---|---| | `compile_error!(msg)` | Emit a compile error with the given message | | `compile_warn!(msg)` | Emit a compile warning | | `compile_note!(msg)` | Emit a compile note | ```kairo eval if defined!(__wasm__) { compile_error!("WebAssembly is not supported yet") } ``` The `compile_` prefix keeps these distinct from runtime logging: `compile_error!` aborts the build, it does not log. ## Code generation | Macro | Description | |---|---| | `include!(path)` | Paste file contents as tokens | | `embed_str!(path)` | File contents as a string literal | | `embed!(path)` | File contents as a byte array (`[byte]`) | | `unique_id!` / `unique_id!(tag)` | Generate a unique identifier | | `todo!(msg)` | Placeholder that crashes at runtime, with an optional message | | `unreachable!(msg)` | Assert a code path is unreachable (crashes if reached) | | `unreachable_unchecked!` | Optimizer hint: path is dead (UB if reached) | | `crash!()` / `crash!(msg)` | End the process: write `msg` (if given) and a newline to stderr, then abort. Never returns | ```kairo // Embed a shader as a string eval VERTEX_SHADER = embed_str!("shaders/vertex.glsl") // Embed a binary resource eval ICON_DATA = embed!("assets/icon.png") // Mark unfinished code fn process() -> Config { todo!("implement config parsing") } ``` `todo!()` and `unreachable!()` are SAFE: both crash at runtime if reached, like [`crash!()`](/docs/language/panic/#main-and-crash) (neither is a [panic](/docs/language/panic/): they join no panic set, so `fn process() -> Config { todo!(...) }` needs no `panic` specifier), with `unreachable!()` signaling a logic error rather than missing code. `unreachable_unchecked!()` is the unsafe variant: it is a hard assertion to the optimizer that the path is dead, and reaching it at runtime is undefined behavior. Reach for `unreachable_unchecked!` only when the crash branch of `unreachable!` shows up in a profile. `crash!` is not a compiler intrinsic: it is an ordinary `pub macro` declared in the builtin library, and every file sees it without an import, the way it sees the builtin types. It expands to a call to a function that returns [`!`](/docs/language/panic/#panic-and-no-return-), so the compiler knows nothing after it runs: a function returning `T` may end in `crash!()` with no `return` after it. Like `todo!()`, it is not a [panic](/docs/language/panic/): it joins no panic set and no `try` catches it, and `main` may call it. Because it is a library macro rather than a reserved name, a macro named `crash!` that a file declares or imports itself takes precedence. What a crash may do is deliberately small, because it runs on a program that has just proved itself wrong (its stack or heap may be damaged). It behaves like a signal handler: it writes the message and a newline to stderr in a single `write`, then aborts, and does nothing else. It never allocates, takes no lock, and runs no Kairo code, so `msg` is not formatted at crash time. A literal costs nothing; a runtime `string` is fine too, but only its bytes are written, as they are, and at most 4096 of them. A crash during a crash ends the process at once. Any `SIGABRT` handler the program installed is reset before the abort, so the process always dies of `SIGABRT` (exit status 134 from a shell). `unwrap!` on null, a failed checked `as` into a closed enum, and a failed [asserting downcast](/docs/language/casting/#downcasting-base-to-derived) end the program the same way, with a message the compiler writes (the expression, and its `file:line:col`). Integer division or remainder by zero does too, with the message `kairo: division by zero`. Untagged, `unique_id!` produces a fresh identifier on every invocation. The tagged form `unique_id!(tag)` is stable within one dynamic macro expansion: every `unique_id!(guard)` inside the same expansion instance yields the SAME identifier, letting a macro body refer to one generated name in several places, while separate invocations of the macro still get distinct names. ## Conditional | Macro | Description | |---|---| | `defined!(name)` | `true` if a macro with the given name exists, `false` otherwise | ```kairo eval if defined!(DEBUG_MODE) { fn log(msg: string) { std::io::println(f"[DEBUG] {msg}") } } else { fn log(msg: string) { } } ``` `defined!` sees Kairo macros (a `macro NAME!` defined earlier, or `-D NAME` on the command line) and C/C++ macros: the target's predefined macros (`__linux__`, `_WIN32`, `__x86_64__`, `__aarch64__`, ...) and every macro the file's [`ffi`](/docs/language/c-cpp/) headers define. That makes it the way to select platform code: ```kairo ffi "c" import "config.h" // #define HAVE_FAST_PATH 1 eval if defined!(__linux__) && defined!(HAVE_FAST_PATH) { fn init() { /* ... */ } } else { fn init() { /* fallback */ } } ``` --- ## Compiler Intrinsic Macros Some macros are compiler intrinsics that perform operations beyond token substitution: | Macro | Description | Details | |---|---|---| | `label!(name)` | Declare a jump target | [Control Flow](/docs/language/control-flow/#jumps) | | `jump!(name)` | Unconditional jump to a label | [Control Flow](/docs/language/control-flow/#jumps) | | `forget!(ptr)` | Drop a pointer from Tether tracking | [Unsafe](/docs/language/unsafe/#forget) | | `is_trivially_copyable!(T)` | `true` when a `T` is copied as its bytes (C++ `__is_trivially_copyable`) | [Eval](/docs/language/eval/) | | `is_trivially_destructible!(T)` | `true` when destroying a `T` runs no code | [Eval](/docs/language/eval/) | | `unwrap!(expr)` | Force-unwrap a nullable; aborts the program on null | [Nullables](/docs/language/nullables/#force-unwrap) | | `mref!(T)` | Produce an rvalue reference type (`&&T`) | [Core library](/docs/library/core/) | These use macro syntax (`name!`) to make their usage explicit and searchable in a codebase, but they are not user-definable they are built into the compiler. --- ## See also - [Macros](/docs/language/macros/) - [Attributes](/docs/language/attributes/) - [Eval](/docs/language/eval/#eval-if) - [Diagnostics](/docs/language/diagnostics/) - [Panic](/docs/language/panic/) --- ## Nullables URL: https://www.kairolang.org/docs/language/nullables/ # Nullables ## Nullable Types `T?` is sugar for `Nullable`, a built-in type that holds either a value of type `T` or `null`. It applies to any type, not just pointers. ```kairo var name: string? = get_name() // may be null var count: i32? = null // explicitly null ``` `null` is a real value: the one constant of the empty type `null_t`. `Nullable` has exactly two constructors, one from `null_t` and one from `T`, and every implicit conversion to `T?` is one of them: `var c: i32? = 5` constructs from the `i32`, `= null` from the `null_t`. A bare `null` is only ever a nullable's null: it never converts to a pointer, so `var p: unsafe *i32 = null` is a compile error. The null raw pointer is spelled `&null` (see [Pointers and nullability](#pointers-and-nullability)). The storage depends on `T`. A nullable [safe pointer](#pointers-and-nullability) is the pointer itself, the same size, with `0x0` meaning null. A nullable closed [enum](/docs/language/enums-plain/#closed-and-open-enums) is the enum itself, with a value it does not declare meaning null. Every other `T?` stores the value and a presence flag, so `bool?` is two bytes; a one-byte `bool?` is planned ([Status](/docs/status/#not-compiled-yet)). `Nullable` is not writable as a type name in Kairo; the `?` suffix is the only spelling (see [Type System](/docs/language/type-system/#nullable-types-in-the-type-system)). From C++ it is `::builtin::Nullable`; see [Using Kairo in C++](/docs/language/c-cpp-exposing/#nullables-across-the-boundary). ### Shorthand declaration The `?` suffix on the variable name infers the nullable type from the initializer: ```kairo var n? = 10 // i32? var name? = get_name() // get_name() -> string?: name is string?, not (string?)? var k = 3 var *p? = &k // (*i32)?: combines with the pointer shorthand (see Variables) // var x? = null // compile error: no underlying type to infer ``` A declaration that infers a nullable type without the `?` gets a warning, with a fix-it that adds it: `var n = find()` with `find() -> i32?` reads like a plain value, so the compiler asks for `var n? = find()`. See [Declaration Shorthands](/docs/language/variables/#declaration-shorthands). ### Null checking The `?` suffix on a variable name in a condition checks for non-null: ```kairo var result? = find_user("alice") if result? { // result is non-null here std::io::println(result.name) } ``` `x?`, `x != null` and `null != x` are the same test, and `!x?`, `x == null` and `null == x` are its negation. Every spelling narrows the same way. Accessing members on an unchecked nullable is a compile error: ```kairo var user? = find_user("alice") user.name // compile error: user has not been null-checked ``` ### Narrowing The compiler tracks, at every point in a function, whether each nullable variable or field path (`user`, `req.body`, `a.b.c`) is **known non-null**, **known null**, or **maybe null**. A known non-null nullable is used as its `T` directly, with no syntax at the use. Reading the value of a maybe-null or known-null one (member access, a dereference, an operator, passing it where a `T` is expected) is a compile error, in every build mode. No mode inserts a hidden check; the null path is always written in the source. Uses that do not need the value are fine in any state: assigning it, passing it to a `T?` parameter, and `?`, `== null`, `??`, `?.`, `===`, `unwrap!()`. Where the compiler cannot tell, the answer is maybe null. Where paths merge, the result is the weaker state: non-null on one path and null on the other is maybe null. #### Assignments set the state An assignment gives the variable the state of the value assigned: ```kairo var x? = 10 // known non-null: a plain i32 was assigned std::io::println(x + 1) // ok, no check needed x = null // known null // x + 1 // compile error: x is always null here x = lookup() // lookup() -> i32?: maybe null // x + 1 // compile error: x may be null here if x? { std::io::println(x + 1) } // ok var y? = x // y has x's state var k = 7 var p: *i32? = &k // known non-null: an address is never null ``` A parameter of type `T?` starts maybe null. #### Conditions refine the state - `if x? { ... } else { ... }`: `x` is non-null in the first block and null in the `else`. - `!` swaps the two: in `if !x? { ... } else { ... }`, the `else` block sees `x` non-null. - `a && b`: `b` is checked as if `a` were true, so `x? && x > 0` is fine. The `if` block of `if a && b` sees what both establish. - `a || b`: `b` is checked as if `a` were false, so `!x? || x > 0` is fine. The `else` of `if a || b` sees what both refute. - Value-form `if c => t else e` and `??` follow the same rules. - **Early exit.** When one branch cannot fall through (`return`, `break`, `continue`, a `panic`, a call to a `-> !` function), the code after the `if` continues with the other branch's state: ```kairo fn area(s: Shape?) -> f64 { if !s? { return 0.0 } return s.width * s.height // s is non-null from here on } ``` **Mind the precedence.** `&&` binds tighter than `||`, so this is an error: ```kairo var a? = lookup() if a? && a > 0 || a < 0 { ... } // compile error: a may be null here // parsed as (a? && a > 0) || a < 0, and a < 0 runs when a? is false ``` The compiler offers a fix-it that adds the parentheses putting every use on the checked path, with a note that `unwrap!(a)` is the alternative: ```kairo if a? && (a > 0 || a < 0) { ... } // ok ``` #### Loops A loop condition refines the body the same way an `if` does. Inside the body, a variable stays narrowed unless the body itself can make it maybe null again: `while x? { ... }` re-tests every iteration, so `x` is non-null at the top of the body whatever the body does to it. After a `while`, the state is the condition's false case, merged with the state at every `break`. A `for` loop has no condition to refine with; its body starts from the state before the loop, minus anything the body can make maybe null. ```kairo var node: *Node? = head while node? { visit(node) // node is non-null: the condition proves it node = node->next // next: *Node?, so node is maybe null again... } // ...until the condition re-tests it ``` `next` is a nullable pointer, not a `Node?`: a `T?` holds its `T` in place, so a `Node` holding a `Node?` would contain itself, which is a compile error. #### What makes it maybe null again Besides an assignment, anything that can write the variable where the compiler cannot see the value: - passing it to an [`@inout`](/docs/language/functions-parameter-modes/) parameter; - writing through a non-`const` pointer to it, or to anything that contains it, or passing such a pointer to a function (see [Closures and stored pointers](#closures-and-stored-pointers)); - for a field path such as `foo.data`: any of the above on `foo`, and any method call that takes `foo` as mutable `self`. The call can change `foo`'s fields, not make `foo` itself null, so a nullable `foo` that was checked stays non-null. A `const` pointer, a `const self` call, or passing it by value leaves the state alone. Taking a pointer into a local (`var *p = &x`) changes nothing by itself; writing through it, or letting it escape, does. ```kairo if cfg.path? { cfg.reload() // fn reload(self): may write cfg.path // open(cfg.path) // compile error: cfg.path may be null here } ``` A nullable reached through `->` or a subscript (`p->cache`, `items[i].cache`) is not tracked: a check on it does not narrow it, and the compiler says so. Copy it to a local and check that: ```kairo var c? = p->cache if c? { use(c.value) } ``` #### Closures and stored pointers A [closure](/docs/language/closures/) that captures by copy needs no special care: its copy starts in the state the variable had when the closure was made, unless the closure assigns its copy, which keeps its value from one call to the next. Inside a closure that captures `x` by pointer, `*x` is checked like any other nullable: `if (*x)? { use((*x).value) }` narrows it. It starts out maybe null, since the closure can run at any point, and any call, or a write through another pointer, makes it maybe null again, because anything else holding a pointer to `x` could change it. A closure that captures by non-`const` pointer, or a pointer value such as `var *p = &x`, can write `x` behind the compiler's back, so the compiler follows it: - calling a closure that captured `x` by pointer, or writing through `p`, makes `x` maybe null; - once that closure or pointer escapes (passed to a function that can keep it, stored in a field, a global or a container, or returned), **every** call from then until `x` goes out of scope makes `x` maybe null, since any call might run it. A check still narrows `x` until the next call. ```kairo var x: Node? = make() var clear = fn ()|*x| { *x = null } if x? { clear() // x.value // compile error: clear() may have set x to null } ``` A `const *` capture or pointer cannot write, and changes nothing. #### Globals and statics A nullable `static` or file-scope variable is narrowed by a check only until the next call: any call may write it. ```kairo static current: Session? = null fn report() { if current? { var id = current.id // ok: no call since the check log(id) // current.id // compile error: log() may have written current } } ``` ### Matching on a nullable A [`match`](/docs/language/pattern-matching/#matching-a-nullable) on a `T?` must answer `case null` first; every later arm, `default` included, sees the value as non-null, and `case var v` binds the unwrapped `T`. ### Safe access (`?.`) The [`?.` operator](/docs/language/operators/#null-safe-access) calls a method or accesses a member only if the value is non-null. If it is null, nothing to the right of `?.` is evaluated and the whole expression is null, so its type is the member's type made nullable: ```kairo var config? = load_config() var t? = config?.timeout // i32?: null when config is null var n = config?.timeout ?? 30 // i32: 30 when config is null var ok? = config?.save(path()) // bool?: save() and path() run only when config is non-null ``` `x?.m` means `if x? => x.m else null`, and `x?.f(args)` the same, with the call and its arguments evaluated only on the non-null path. Nothing is ever constructed on the null path. When the member's type is already nullable it is not wrapped twice: `x?.m` with `m: T?` is `T?`. `?->` is the same over a [nullable pointer](#pointers-and-nullability), and a chain `a?.b?.c` applies each step to the previous step's result. The steps after a `?.` act on the value, up to the next `?.`: `user?.address.city` is `string?` when `address` is not nullable. A call's result is the nullable, so `user?.find_order()?.total` needs the second `?.`. A method that returns nothing makes a statement: `conn?.close()` calls `close()` only when `conn` is non-null. The result is a value, not a place: `config?.timeout = 5` is a compile error. `?.` and `?->` on a value that cannot be null are a compile error too, with a fix-it that writes `.` (or `->`). ### Null coalescing (`??`) `??` provides a fallback value when the left side is null. Both sides must be the same underlying type. The result is `T`, or `T?` when the right side is itself nullable, and `??` chains to the right: ```kairo var value = get_f32() ?? 0.212 // value is f32, not f32? var name = get_name() ?? "anonymous" // string var host? = env_host() ?? config_host() // string?: config_host() -> string? var port = env_port() ?? file_port() ?? 80 // i32 ``` ### Null-aware equality (`===`) `a === b` is true when both are non-null and their values are equal: `(a? && b?) && a == b`. A non-nullable operand needs no test, so `a === 5` is `a? && a == 5`. The `==` is the values' own, a user `op ==` included. On nullable pointers it compares what they point to, one level down. In a [generic](/docs/language/generics/#type-parameter-constraints) body, `===` on a `T?` compares with the `op ==` a bound on `T` declares (without one it is an error), and a `T` is never a pointer there: a `*i32` passed as `T` is compared as an address by its `==`; write `(*T)?` to compare pointees. At least one operand must be nullable, and `x === null` is an error (it is never true; write `!x?`). Like the conjunction it reads as, a true `a === b` narrows both: in `if a === b { ... }`, `a` and `b` are non-null. See [Operators](/docs/language/operators/#comparison). ### Force unwrap `unwrap!()` extracts the value, or terminates the program if it is null: ```kairo var x = unwrap!(maybe_value) // aborts the program if null ``` `unwrap!(x)` reads as `if x? => x else `. On null it writes a message naming the expression and its source location to stderr (`unwrap!(maybe_value) on null at /home/me/app/main.k:12:13`: the source file's full path, line and column), then aborts the process (like C++ `std::abort`). Since the program cannot continue past a null, `x` itself is known non-null after `unwrap!(x)`, and on a variable or field `unwrap!(x)` is that variable: `unwrap!(cfg).port = 80` writes `cfg`'s value. `unwrap!` on a value that cannot be null is a compile error. It is not a [panic](/docs/language/panic/): nothing can catch it, so it needs no `try` and no `panic` specifier, and it is not part of a function's panic set. Use it where a null value means the program itself is wrong; where null is an outcome to handle, use `if x?`, `??` or `?.`. ### Const interaction `const` on a nullable binding works the same as on any other type the binding cannot be reassigned after initialization: ```kairo const x: i32? = 42 x = null // compile error: x is const x = 100 // compile error: x is const var y: i32? = null y = 42 // ok: var is mutable y = null // ok: can go back to null ``` ### Pointers and nullability `*T` is non-null by construction, it cannot hold `&null`. No null checks are needed on dereference because the pointer is always valid: ```kairo var x = 42 var ptr: *i32 = &x *ptr = 10 // guaranteed valid, no check var bad: *i32 = &null // compile error: *T is non-null ``` To represent a pointer that might not exist, use `*T?`, a nullable pointer. It reads as `(*T)?`, not as a pointer to a nullable, which is `*(T?)` (see [Pointers](/docs/language/pointers/#pointers-and-nullable-types)). It is one pointer wide, with null stored as `0x0`, and supports `?`, `?.`, `?->`, `??`, `===` and `unwrap!()`: ```kairo var ptr: *i32? = find_pointer() if ptr? { std::io::println(*ptr) // compiler knows ptr is non-null here } var *val = ptr ?? &fallback // *i32: use fallback if null var *forced = unwrap!(ptr) // aborts if null ``` For a raw pointer with no compiler tracking, use `unsafe *T`. It is the only pointer that can hold the null address, written `&null` (a bare `null` is a nullable's null, never a pointer), and it is checked by comparing against `&null` by hand: ```kairo var raw: unsafe *i32 = &null if raw != &null { std::io::println(*raw) } ``` See [Pointers](/docs/language/pointers/) for the full pointer model and how [Tether](/docs/language/tether/) tracks pointer provenance. ## See also - [Variables & Bindings](/docs/language/variables/) - [Pointers](/docs/language/pointers/) - [Panic](/docs/language/panic/) - [Tether](/docs/language/tether/) - [Pattern Matching](/docs/language/pattern-matching/) - [ADT Enums](/docs/language/enums-adt/) - [Nullable to Non-Nullable](/docs/language/casting/#nullable-to-non-nullable) - [Nullable Types in the Type System](/docs/language/type-system/#nullable-types-in-the-type-system) --- ## Operator Overloading URL: https://www.kairolang.org/docs/language/operator-overloading/ # Operator Overloading Operators are overloaded by defining `fn op` methods on a [class](/docs/language/classes/) or [struct](/docs/language/structures/), or in an [extension](/docs/language/extends/). The syntax mirrors the operator being defined. An extension may declare any overloadable operator except `as`, `[]`, `[]=`, `->` and `delete`, which are **member-only**: they must be declared in the type's own body. The built-in types follow the same rules. `[T]`, `{T}`, `{K: V}`, `[T;]` and `string` are ordinary types to the compiler, so an operator they declare (for example `fn op in (self) -> yield T`, or `fn op [] (self, i: usize) -> *T`) is the one a `for` loop or a subscript calls. Only when such a type declares no operator of that kind does the compiler fall back to the built-in behavior. ## All Overload-able Operators for User-Defined Types | Operator | Overload-able | Const-overloadable | Notes | |---|---|---|---| | `+` `-` `*` `/` `%` | ok | no | Returns a new value. | | Unary `+` `-` | ok | no | Returns a new value. | | `^^` | ok | no | Returns a new value. | | `<<` `>>` | ok | no | Returns a new value. | | `&` `\|` `^` `~` (bitwise) | ok | no | Returns a new value. | | `==` | ok | no | Returns `bool`. | | `!=` | ok | no | Returns `bool`. Derived from `op ==` when not declared. | | `<` `<=` `>` `>=` | ok | no | Return `bool`. Derived from `op <=>` when not declared. | | `<=>` | ok | no | Returns `Ordering`. | | `l++` `r++` `l--` `r--` | ok | no | Mutating operators. | | `[]` | ok | ok | Returns a place into `self` (`*T` / `*const T`). Member-only. | | `[]=` | ok | no | Returns the place a write goes through (`*T`). Member-only. See [Reading and writing](#reading-and-writing--and-). | | `->` | ok | ok | Returns a place into `self` (`*T` / `*const T`). Member-only. | | `in` (containment) | ok | no | Returns `bool`. | | `in` (iteration) | ok | no | Returns `yield T`. | | `as` | ok | no | Returns a converted value. Member-only. | | `finally` | ok | no | Custom destructor. Member-only. Not C++'s allocation `operator delete`. | | `await` | ok | no | Returns the awaited value. | | `panic` | ok | no | `fn op panic (const self) -> string`: the optional message for a [panicked](/docs/language/panic/#error-types) value. See [`op panic`](#op-panic). | | `+=` `-=` `*=` `/=` `%=` `&=` `\|=` `^=` `<<=` `>>=` | ok | no | Returns nothing. Declare either this or its binary operator, not both. | | `=` | no | no | Generated by the compiler; cannot be overloaded. | | `new`, and C++'s allocation `operator new` / `operator delete` (array forms included) | no | no | A class defines its constructors and its destructor, never how its memory is obtained. Kairo defines C++'s four allocation operators for every class itself; see [Allocators & Ownership](/docs/language/c-cpp-memory/#class-specific-operator-new-and-operator-delete). | | `===` | no | no | Built in; needs a nullable operand. | | `.` `::` | no | no | Language syntax; not overloadable. | | Unary `&` `*` | no | no | Built-in pointer operations. Not overloadable on Kairo types. On an imported C++ class, `*x` calls the class's `operator*`, which is how C++ iterators and smart pointers are read. | | `&&` `\|\|` `!` | no | no | Preserve built-in short-circuit semantics. | | `?.` `?->` | no | no | Derived automatically from the corresponding non-null-safe operator. | | `..` `..=` | no | no | Implemented through the `Steppable` interface. | | `sizeof` `alignof` `typeof` | no | no | Compile-time language keywords. | ## Standard binary and unary operators ```kairo class Vec3 { var x: f32 var y: f32 var z: f32 fn op + (self, other: Vec3) -> Vec3 { return Vec3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z } } fn op - (self) -> Vec3 { // unary negation return Vec3 { x: -self.x, y: -self.y, z: -self.z } } fn op == (self, other: Vec3) -> bool { return self.x == other.x && self.y == other.y && self.z == other.z } } ``` Operators have no default arguments, and every comparison operator (`==`, `!=`, `<`, `<=`, `>`, `>=`) must return `bool`. ## Derived comparisons A comparison the type does not declare is derived: `!=` from `op ==`, and `<`, `<=`, `>`, `>=` from `op <=>`. A declared operator always wins over a derived one, so a type can declare `op <=>` for ordering and still declare its own `op <` when it has a faster path. ```kairo struct Version { var major: i32 var minor: i32 fn op == (self, o: Version) -> bool { return self.major == o.major && self.minor == o.minor } fn op <=> (self, o: Version) -> Ordering { /* ... */ } } var a = Version { major: 1, minor: 2 } var b = Version { major: 1, minor: 3 } a != b // derived from op == a < b // derived from op <=> ``` ## Compound assignment Each compound assignment and its binary operator form a pair: `+=` / `+`, `-=` / `-`, `*=` / `*`, `/=` / `/`, `%=` / `%`, `&=` / `&`, `|=` / `|`, `^=` / `^`, `<<=` / `<<`, `>>=` / `>>`. A type declares **one** half of a pair and the other is derived from it. Declaring both halves is an error. - From `op +`: `a += b` is `a = a + b`, with `a` evaluated once. - From `op +=`: `a + b` copies `a`, applies `+=` to the copy with `b`, and yields the copy. A compound assignment operator mutates `self` and returns nothing, so `a += b` on a struct or class is a statement, not a value: ```kairo struct Acc { var total: i32 fn op += (self, n: i32) { self.total = self.total + n } } var acc = Acc { total: 0 } acc += 5 // calls op += var acc2 = acc + 7 // op + derived from op +=: acc2.total == 12 ``` Declaring `op +` instead derives `+=` the other way. Declare whichever form is natural for the type; the in-place form usually avoids a copy. [Imported C++ types](/docs/language/c-cpp-calling/#operators-on-c-types) are not paired: they get exactly the operators their C++ declaration has. For a type that cannot be copied, `a + b` with a variable `a` is SC182E, because the derived `+` copies `a`. Write `a += b`, or use a temporary on the left. ## Increment and decrement Use the `l` (left/prefix) or `r` (right/postfix) modifier to specify which variant you are overloading. A type may declare both. An unmarked `op ++` or `op --` is taken as the prefix form, with a warning. ```kairo fn op r-- (self) -> T // postfix: x-- fn op l-- (self) -> T // prefix: --x fn op l++ (self) -> T // prefix: ++x the ++ is on the left of the operand fn op r++ (self) -> T // postfix: x++ the ++ is on the right of the operand ``` ## Const Overloading Operators `op []` and `op ->` may overload on receiver const-ness, the one exception to the const-overload restriction that applies to named methods. For a place overload, the `const self` version returns `*const T` where the `self` version returns `*T` (see [Places and values](#places-and-values---)). This exception exists because operators cannot be renamed. See [Functions](/docs/language/functions-overloading/#const-overloading-restriction) for details. ```kairo class Buffer { priv var data: [u8] fn op [] (self, index: usize) -> *u8 { return &self.data[index] } fn op [] (const self, index: usize) -> *const u8 { return &self.data[index] } } var buff = Buffer { data: [1, 2, 3] } var p: u8 = buff[1] // `buff` is not const: the `self` overload is picked, and the read // dereferences the returned `*u8` to `u8` buff[1] = 42 // `self` overload; writes through the returned `*u8` const cbuff = Buffer { data: [1, 2, 3] } var c: u8 = cbuff[1] // `cbuff` is const: the `const self` overload is picked cbuff[1] = 42 // error: the place is `*const u8` ``` A non-const receiver prefers the `self` overload; a const receiver can only use the `const self` one. The result of a place operator is used as the value it points to, as a read or as the target of an assignment. A named method returning `*T` is not dereferenced this way. Every other operator follows the named-method rule: a `const self` overload of it is a redeclaration error, the same as for a named method. ```kairo struct V { var x: i32 fn op + (self, o: V) -> V { /* ... */ } fn op + (const self, o: V) -> V { /* ... */ } // error: only [] and -> overload on const-ness } ``` ## Special operators | Operator | Signature | Description | |---|---|---| | `as` | `fn op as (self) -> TargetType` | Type conversion takes no parameters | | `in` (containment) | `fn op in (self, other: T) -> bool` | `if item in collection` checks membership | | `in` (iteration) | `fn op in (self) -> yield T` | `for x in collection` yields elements | | `finally` | `fn op finally (self)` | Custom destructor, run when the value's scope ends (an explicit `x.finally()` is planned for 0.3) | | `panic` | `fn op panic (const self) -> string` | The message for an error of this type, used when the error is shown (optional) | The two `in` signatures are distinguished by context: the compiler uses the `-> bool` variant in `if` expressions and the `-> yield T` variant in `for` loops. ```kairo class IntSet { priv var data: [i32] fn op in (self, value: i32) -> bool { // containment check: "if 5 in my_set" for item in self.data { if item == value { return true } } return false } fn op in (self) -> yield i32 { // iteration: "for x in my_set" for item in self.data { yield item } } } var s = IntSet { data: [1, 2, 3] } if 2 in s { /* ... */ } // calls the bool variant for x in s { // calls the yield variant std::io::println(f"{x}") } ``` ### Implicit `op as` An `@implicit fn op as (self) -> T` is applied automatically where a `T` is wanted, so the caller does not write `as`: - The result type must match exactly. A `T` produced this way is not converted any further, so it does not fill a `T?` or a wider numeric type. - Conversions never chain: at most one `@implicit` operator applies, and never on top of another implicit conversion. - `if`/`match` arms and operator operands are never converted this way. ```kairo struct Name { var first: string var last: string @implicit fn op as (const self) -> string { return f"{self.first} {self.last}" } } fn greet(who: string) { ... } fn maybe_greet(who: string?) { ... } var n = Name { first: "Ada", last: "Lovelace" } greet(n) // n as string, applied implicitly var s: string = n // also implicit maybe_greet(n) // error: string? is not an exact match var t = n + "!" // error: operands are not converted; write (n as string) + "!" ``` Without [`@implicit`](/docs/language/attributes/#conversions), `op as` only runs on an explicit `as`. ### `op panic` Any movable type can be [panicked](/docs/language/panic/#error-types); `op panic` is optional. When a type defines it, the operator returns the human-readable message for an error of that type: ```kairo struct ConfigError { var key: string fn op panic (const self) -> string { return f"missing config key {self.key}" } } fn port(cfg: Config) panic -> i32 { if !cfg.has("port") { panic ConfigError { key: "port" } } return cfg.get_int("port") } ``` - The signature is fixed: no parameters besides `const self`, and a `string` result. A plain `self` receiver is an error whose fix-it inserts `const`. - The message is built only when the error is displayed, for example by [`value_or_throw`](/docs/language/c-cpp-exceptions/#converting-to-an-exception) on the C++ side. Raising, propagating and catching an error never call it. - Without `op panic`, a displayed error shows its type name and source location instead of a message. - An [extension](/docs/language/extends/) may add `op panic` to a Kairo type it doesn't own, such as a primitive or another module's type. A C++ type cannot define it; it can still be panicked, and shows its type name. ## Places and values: `[]`, `->` `op []` is either a **place** or a **value** operator. The declared return type decides which. A safe pointer return (`*T` or `*const T`) makes it a place: - `a[i]` is the `T` the pointer points at. It is an lvalue, and `const` if the pointer was. - `a[i] = x` and `a[i] += 1` write into `self`, and `&a[i]` gives the pointer back. - C++ sees the operator as returning `T&` / `const T&`. Any other return makes it a value operator: `a[i]` is the returned value, an rvalue. You can read it but not assign to it, and `&a[i]` is an error. `unsafe *T` is rejected as a return type, because it is neither a place nor a value. A pointer return from `[]` always means a place, so `op []` cannot return a pointer by value. Use a named method to hand out a pointer. `op ->` isn't part of this rule. It must return `*T` or `*const T`, and `->` is then applied to that result, as with C++'s `operator->`. `unsafe *T` is rejected there too. Both kinds can be overloaded on a `const self` receiver. ```kairo struct Buf { var data: [T; 4] fn op [](self, i: usize) -> *T { return &self.data[i] } // place fn op [](const self, i: usize) -> *const T { return &self.data[i] } // place, const receiver fn op [](self, r: Range) -> [T;] { ... } // value: a slice } var b = Buf{ data: [1, 2, 3, 4] } b[0] = 10 // through the place var s = b[0..2] // a new value var *p = &b[1] // *i32 into b.data ``` On a const object only the `const self` form of `op []` can be called; an element reached through it, or through a const array or vector, is const, so writing it, passing `&x[i]` to `@inout`, or calling a `self` method on it is an error. ## Reading and writing: `[]` and `[]=` A type can declare its subscript in two forms. `op []` is the **read form**: it gives the element to read, as `*const T` or a value. `op []=` is the **place form**: it gives the place a write goes through, as `*T`. ```kairo class Buf { priv var data: [i32] fn op [] (const self, i: usize) -> *const i32 { return &self.data[i] } fn op []= (self, i: usize) -> *i32 { return &self.data[i] } } var b = Buf { data: [1, 2, 3] } b[0] = 10 // op []= b[1] += 1 // op []=, called once var x = b[2] // op [] var *p = &b[0] // op []=, *i32 const cb = Buf { data: [1, 2, 3] } var *q = &cb[0] // op [], *const i32 cb[0] = 1 // error: 'cb' is const, and 'op []=' takes 'self' ``` When a type declares `op []=`, each use of `b[i]` calls the form that matches what it does with the element. Neither the type's constness nor the return type decides. - **Writes call `op []=`:** the left side of `=` and of every compound assignment, the operand of `++` and `--`, a member written through the element (`b[i].x = 4`), the container of a written nested subscript (`g[i][j] = 0` writes `g[i]` too), and the receiver of a method or `op in` that takes `self`. - **`&b[i]` takes `op []=` and gives `*T`** when `b` is mutable. On a const `b`, or where `*const T` is wanted, it takes `op []` and gives `*const T`. An `@inout` argument needs the place form. - **`var t = b[i..j]`** on a mutable `b` binds the place form, so `t` is a view you can write through. `const t = b[i..j]` binds the read form. If `t` is never written through, SC281W suggests `const`. - **Every other use reads** and calls `op []`. The forms do not stand in for each other. A read through a type that declares only `op []=` is SC279E. For one index type, the two forms describe one element: `op []` returns `*const T` (or a value) where `op []=` returns `*T`. `op []` beside an `op []=` cannot return `*T`, and `op []=` takes `self` and returns `*T` or a mutable view `[T;]` (SC280E). A type that declares no `op []=` keeps the single `op []` of [Places and values](#places-and-values---). The builtin containers are such types today. C++ sees the forms as `__kairo_op_get` and `__kairo_op_set`, and the class gets `operator[]` overloads that forward to them: `T& operator[](I)` to the place form and `const T& operator[](I) const` to a `const self` read form. When both forms would be the same C++ overload, `operator[]` is the place form and the read form is `__kairo_op_get`. ## Finally Operator `op finally` defines custom destruction logic. It runs when the value's scope ends, the same idea as a standalone [`finally { }` block](/docs/language/control-flow/#standalone-finally-scope-exit), and, from 0.3, early when called as `x.finally()` (C++'s `x.~T()`; until then it is [SC116E](/docs/language/diagnostics/#sc116e-a-feature-is-not-yet-supported)). The old spelling `op delete` is an error with a fix-it. If not defined, the compiler generates a [default destructor](/docs/language/classes-lifecycle/#destructors---op-finally). If any member has a deleted destructor (`fn op finally() = delete`), the containing type's destructor is also deleted and instances must be managed in an [unsafe](/docs/language/unsafe/) context. > [!NOTE] > The `op finally` operator is **not** the same as C++'s `delete` operator, and Kairo has no `delete` expression. `op finally` is a cleanup hook that runs automatically when a value's scope ends (explicit `x.finally()` is planned for 0.3); it never frees the object's own storage. Memory allocated with `@create T()` is freed with `@destroy p`, which runs the destructor and then returns the memory to the allocator. > > C++'s allocation operators, `operator new` and `operator delete` and their array forms, are not overloadable in Kairo: a class defines its constructors and its destructor, never its allocation functions. Kairo defines all four for every class, bound to the global allocator, so C++ code that `new`s or `delete`s a Kairo object goes through Kairo's allocator. See [Allocators & Ownership](/docs/language/c-cpp-memory/#class-specific-operator-new-and-operator-delete). ```kairo class FileHandle { priv var fd: i32 fn op finally (self) { close(self.fd) } } ``` See [Tether](/docs/language/tether/#destruction-timing) for destruction timing and [Allocators](/docs/language/allocators/) for allocator interaction. --- ## See also - [Operators](/docs/language/operators/) - [Casting](/docs/language/casting/) - [Implicit Conversions](/docs/language/casting-implicit/) - [Interface Requirements](/docs/language/interfaces-requirements/) - [Extends](/docs/language/extends/) - [Structures](/docs/language/structures/) - [Classes](/docs/language/classes/) - [Destructors & Lifecycle Categories](/docs/language/classes-lifecycle/) --- ## Pattern Matching URL: https://www.kairolang.org/docs/language/pattern-matching/ # Pattern Matching `match` is Kairo's multi-way dispatch construct. It handles value matching, enum variant dispatch, ADT destructuring, struct field extraction, and range checks all with compiler-enforced exhaustiveness. ```kairo match status_code { case 200 { std::io::println("OK") } case 404 { std::io::println("Not Found") } case 500 { std::io::println("Internal Server Error") } default { std::io::println(f"Unknown: {status_code}") } } ``` ## Value matching `match` operates on integers, [strings](/docs/language/primitives/#strings), and booleans by comparing against literal values: ```kairo match command { case "start" { engine.start() } case "stop" { engine.stop() } case "reset" { engine.reset() } default { log_unknown(command) } } match is_valid { case true { proceed() } case false { abort() } } ``` ## Enum variant matching For [plain enums](/docs/language/enums-plain/), use the [`.Variant` shorthand](/docs/language/enums/#shorthand-syntax) when the type is inferred from the match operand: ```kairo match dir { case .North { go_up() } case .South { go_down() } case .East { go_right() } case .West { go_left() } } ``` The fully qualified form `Direction::North` also works. The compiler verifies all variants are covered. ## ADT destructuring ADT enum variants carry payloads. Destructure them in `match` with `var` or `const` bindings inside parentheses. Field names must match the variant declaration: ```kairo enum LookupResult { Found { key: K, value: V }, NotFound { key: K }, Error { message: string }, } match result { case .Found(var key, var value) { std::io::println(f"{key} = {value}") } case .NotFound(var key) { std::io::println(f"{key} not found") } case .Error(const message) { // message cannot be reassigned bound as const log_error(message) } } ``` You can omit fields you do not need exhaustive field extraction is not required: ```kairo match result { case .Found(var value) { // only value is bound, key is ignored process(value) } default { } } ``` See [Enums](/docs/language/enums-adt/) for ADT enum declarations and construction. ## `where` guards Append [`where`](/docs/language/where/#where-in-match) followed by a boolean expression to add a condition to a case. The branch only matches if both the pattern and the guard are satisfied: ```kairo match result { case .Found(var key, var value) where value > 0 { std::io::println(f"{key} has positive value") } case .Found(var key, var value) { std::io::println(f"{key} has non-positive value") } default { } } ``` Guards work the same way in a value-form `match`, written before the arrow: ```kairo var amount = match result { case .Found(var key, var value) where value > 0 => value default => 0 } ``` Guards are evaluated after the pattern matches. A case with a guard that fails falls through to the next case this is the only situation where control moves between cases. ## Struct matching [Structs](/docs/language/structures/) have a single shape (no variants), so `match` on a struct is [destructuring](/docs/language/structures/#destructuring) combined with guards. A struct `case` without a `where` guard always matches and is a compile error unless it is the only case or the last case (acting as a catch-all): ```kairo struct Response { var status: i32 var body: string } match response { case Response(var status, var body) where status == 200 { process(body) } case Response(var status) where status >= 400 { log_error(f"HTTP {status}") } default { // catch-all } } ``` ## Range matching Integer cases can match a [range](/docs/language/operators/#ranges) using `..` (exclusive end) or `..=` (inclusive end): ```kairo match http_status { case 200..=299 { std::io::println("success") } case 300..=399 { std::io::println("redirect") } case 400..=499 { std::io::println("client error") } case 500..=599 { std::io::println("server error") } default { std::io::println("unknown") } } ``` The same ranges in a value-form `match`: ```kairo var kind = match http_status { case 200..=299 => "success" case 300..=399 => "redirect" case 400..=599 => "error" default => "unknown" } ``` ## Matching a nullable A `match` on a [nullable](/docs/language/nullables/) `T?` must answer null first: its first arm is `case null`, on its own and with no `where` guard. A first arm that is anything else is a compile error (not a warning). When the match has no `case null` at all, the fix-it inserts `case null { }` at the top (in expression form, where the arm needs a value, the error says to add `case null => `); when `case null` is further down, or shares its arm with other patterns, the error points at it. Because null is answered once, at the top, every later arm, `default` included, sees the value as non-null: ```kairo match port { // port: i32? case null { use_default() } // port is null here case 0 { pick_free() } // a value pattern only matches a present value default { bind(port) } // port is non-null: case null took null } ``` A binding pattern binds the unwrapped value, so `case var v` on an `i32?` binds `v: i32` and never matches null: ```kairo var label = match port { case null => "none" case var p where p < 1024 => f"system port {p}" // p: i32 default => f"port {port}" // port reads as i32 } ``` A `where` guard narrows its arm the same way an `if` condition does. After the `match`, the value's null state is the merge of every arm that can fall through. A second `case null` is an error: the first arm already answered null. Exhaustiveness is checked over `T`, so a `bool?` with `case null`, `case true` and `case false` needs no `default`. ## `match` as an expression ```kairo var label = match level { case .Debug => "debug" case .Info => "info" case .Warning => "warning" case .Error => "error" case .Fatal => "fatal" } var priority = match code { case 200..=299 => 0 case 400..=499 => 1 case 500..=599 => 2 default => -1 } var message = match result { case .Found(var key, var value) => f"{key}: {value}" case .NotFound(var key) => f"{key} not found" case .Error(var message) => message } ``` Each arm is `case pattern => value` or `default => value`. All arms must produce the same type. - Arms are not separated by commas. A comma between arms is an error ([S076E](/docs/language/diagnostics/#s076e-match-arms-separated-by-a-comma)). - Guards come before the arrow: `case .Found(var v) where v > 0 => v`. - You may break before or after `=>`. - A `match` closes with `}`, so it can be used directly as an operand: `var n = match k { ... } + 1`. The [parentheses rule](/docs/language/control-flow/#how-far-an-arm-extends) for `if` and `try` does not apply to it. - All arms of one `match` use the same form, either all `=>` or all `{ }`. Mixing the two is an error ([S075E](/docs/language/diagnostics/#s075e-match-arms-mix--and---forms)). - In statement position, a `match` whose arms are all `=>` is an expression, and exhaustiveness is required as for any `match` expression. A `match` with block arms is a statement. In expression form, exhaustiveness is required every possible value must be covered. For integers and strings, this means `default` is mandatory. ## Exhaustiveness The compiler verifies that all possible values are covered: | Matched type | Coverage rule | |---|---| | Plain enum | All variants covered, or `default` present | | ADT enum | All variants covered, or `default` present | | Integers / strings | `default` always required | | Booleans | `true` + `false` covers it | | Structs | `default` always required | | Nullable `T?` | `case null` first, then the rule for `T` | A `default` case matches any value not covered by preceding cases. It must be the last case. In a [generic](/docs/language/generics/#type-parameter-constraints) body, a match on a generic ADT at a dependent argument (`r: Rep`) is checked like any other: its variants are known, and missing one is an error. A match on a value of a type parameter `T` itself can only bind it, guard it or ignore it (`case var v where v_ok(k)`, `case _`, `default`): `T` has no variants or values a pattern could test, so any other pattern is an error, and the match is exhaustive only when an unguarded binding, `_` or `default` ends it. A match whose arms are all `=>` is an expression, wherever it appears. ## No fall-through Each case is an isolated block. There is no fall-through between cases and no `@fallthrough` attribute. If you need multiple values to execute the same code, list them in a single case separated by commas: ```kairo match priority { case 1, 2, 3 { handle_high() } case 4, 5 { handle_medium() } default { handle_low() } } ``` ## `break` in `match` inside a loop Inside a `match` nested within a loop, [`break`](/docs/language/control-flow/#break-and-continue) exits the **loop**, not the match. Match cases are already isolated blocks with no fall-through, so there is nothing to "break" out of within the match itself. ```kairo for item in items { match item.kind { case .Sentinel { break // exits the for loop } case .Data(var payload) { process(payload) } default { } } } ``` --- ## See also - [Control Flow](/docs/language/control-flow/) - [Enums](/docs/language/enums/) - [ADT Enums](/docs/language/enums-adt/) - [Plain Enums](/docs/language/enums-plain/) - [Structures](/docs/language/structures/) - [`where`](/docs/language/where/) - [Nullables](/docs/language/nullables/) - [Diagnostics](/docs/language/diagnostics/) --- ## Bounds and Provenance URL: https://www.kairolang.org/docs/language/tether-bounds/ # Bounds and Provenance ## Pointer Arithmetic Kairo permits [pointer arithmetic](/docs/language/pointers/#pointer-arithmetic) on safe pointers. This is a deliberate departure from Rust's safe subset, and Tether is what makes it sound. ```kairo var a: *i32 = @create i32(120) *(a + 10) = 19 ``` At this dereference Tether knows the allocation base, element type (`i32`), element size (4 bytes), and element count (120). The offset 10 is a compile-time constant. C3 reduces to `10 < 120`, proven statically. C1, C2, C4, C5, C6 are all proven. Residual set is empty -> `PROVEN_STATIC`: ``` mov [rdi + 40], 19 ``` No check. No metadata. Nothing. ### Runtime offset ```kairo var i = std::input() *(a + i) = 19 ``` Now C3 cannot be proven (the offset is runtime data) and C2 cannot be proven (`i` is signed and may be negative). Every other clause holds. Residual set is `{bounds}`, not hoistable -> `REQUIRES_DYNAMIC`: ```asm assert((0 <= i) && (i < 120)); mov [rdi + i*4], 19 ``` Note both halves of the check. **`i < 120` alone is unsound** for a signed offset: a negative `i` passes it and reads out of bounds backward. The canonical obligation is `0 <= off AND off + sizeof T <= size`, and Tether emits both comparisons unless it can prove non-negativity separately (e.g. `i` is unsigned, or dominated by an `i >= 0` guard). For an unsigned offset the lower-bound clause C2 is discharged statically and only the upper comparison is emitted. The check is on the **offset**, computed before the pointer is formed never on the resulting pointer address. Checking `result_ptr < end` after forming the pointer is the bypassable version: if `i * sizeof T` overflowed the address width, the formed pointer can wrap below `end` and pass a post-hoc check. Tether checks the offset in a width that cannot wrap for any in-allocation offset (the valid offset range is bounded by `size`, which is known), then forms the pointer. ### Hoisting ```kairo for i in 0..<120 *(a + i) = 0 ``` Tether proves `0 <= i < 120` holds for the entire loop body from the loop's induction structure (see [the numeric domain](/docs/language/tether-proof-model/#the-numeric-domain)). The bounds clause is `HoistableResidual` if it is the only residual -> `PROVEN_RANGE`. The per-iteration check is lifted to a single check before the loop: ```asm loop: mov [rdi + i*4], 0 ; no per-iteration check ``` And when the loop bound and the allocation size derive from the same value: ```kairo var n = std::input() var a: *i32 = @create i32(n) for i in 0..`, `>=`) are defined only when both operands share provenance (point into the same allocation, one-past included). A relational comparison between pointers into different allocations is a compile error; when Tether cannot prove the operands share an allocation, it is a compile error too. Compare addresses through `as usize` if a cross-allocation ordering is genuinely wanted. This is a larger expressiveness envelope than safe Rust, which routes all of this through slices and iterators. The safety **guarantee** is the same no out-of-bounds access reaches memory but the cost model is pay-only-when-unprovable rather than always-checked-unless-elided, and the surface syntax is C-style arithmetic rather than slice methods. > Tether does not present an unprovable bounds access as a *warning*. The programmer did nothing questionable; the allocation size is runtime data. It is reported as an **optimization remark** when remarks are enabled, naming the fact that blocked the proof: `[amt] runtime bounds check at : allocation size depends on runtime value 'n'; cost: one check; to eliminate: bound the index by a compile-time constant or hoist the proof.` --- ## Provenance and Epochs Use-after-free is not a separate debug-only feature. It is clause C1 of the dereference obligation, and it is discharged by the same lattice machinery as bounds. Every allocation carries a **generation** (an epoch) in its provenance fact. Any operation that can free or relocate the allocation increments its epoch: - explicit `@destroy` or `@free` - scope exit of the owning binding - [ownership transfer](/docs/language/ownership/#transfer-semantics) (move) out of the owning binding - assignment *into* the binding (copy or move assignment), which replaces the contents a derived pointer was looking at - reallocation (e.g. a `Vec` growing its backing buffer) - the close of a [scoped allocator](/docs/language/allocators/#scoped-allocator) that owns the allocation A pointer value derived at epoch *e* records *e* in its provenance. Clause C1 requires `epoch(prov(p)) == live_epoch(alloc(prov(p)))` at the dereference. Statically, most epochs are provably equal there is no intervening freeing operation between derivation and use so C1 is `Proven` and emits nothing. When Tether cannot prove the epochs equal (a free *might* have happened on some path), C1 is residual: ```kairo var buf: *i32 = @create i32(64) var *p = buf + 5 realloc(buf) // increments buf's epoch *p = 1 // C1 residual: p was derived at the old epoch ``` If provenance is intact (Tether still knows which allocation and can read the live epoch), C1 residual is **Tier R**: an epoch comparison at the dereference, in both modes. If provenance has been lost entirely (the pointer was laundered through an untracked path and Tether no longer knows the allocation), there is nothing to compare against and it is **Tier N**: a hard error. Epochs are 64-bit. A generation counter that wraps lets a stale pointer whose epoch has come back around pass the comparison; at 64 bits the wrap is unreachable in practice. > [!NOTE] > `PROVEN_STATIC` needs no metadata. A Tier R check does: the bounds check reads `size(alloc)` and the epoch check reads `live_epoch(alloc)` at run time, for a pointer that may have arrived as a parameter with a runtime offset. Where those values come from (pointer representation, allocator lookup, or caller-supplied facts) is not decided yet, and the choice affects the pointer ABI. Whatever is chosen, the epoch word must remain readable after the allocation is freed, since reading it out of freed memory would itself be a use-after-free. Folding UAF into the same obligation as bounds is what makes the architecture scale: there is one analysis, one lattice, one residual table, and "use-after-free detection" is not a bolted-on sanitizer but a clause that is either proven away or checked like any other. --- ## Field access and interior pointers `foo.bar.baz` is `PROVEN_STATIC` when `foo` is non-null and the field offsets are static: the access inherits `foo`'s provenance with a constant offset, and its obligation is exactly `foo`'s obligation. Taking an interior pointer `var *p = &foo.bar` creates a new pointer whose provenance is derived from `foo`'s allocation at `foo`'s current epoch. Dropping `foo`, moving out of it, or assigning a new value into it increments that epoch, so a later `*p` fails C1 by the same mechanism as any other use-after-free. Interior pointers are not special-cased; they reuse the epoch machinery. ## See also - [Tether](/docs/language/tether/) - [Proof Model](/docs/language/tether-proof-model/) - [Ownership and Promotion](/docs/language/tether-promotion/) - [Threading](/docs/language/tether-threading/) - [Tether Internals](/docs/language/tether-internals/) - [Pointers](/docs/language/pointers/) - [Ownership](/docs/language/ownership/) - [Collections](/docs/language/collections/) --- ## Tether Internals URL: https://www.kairolang.org/docs/language/tether-internals/ # Tether Internals ## C/C++ Interop The FFI boundary is where Tether's facts run out, and the cost model has an honest asterisk: pointers crossing the boundary carry no provenance Tether can trust, so accessing them in safe code is not free. ### Inbound pointers are tainted A pointer that enters Kairo from C++ has **no provenance** Tether does not know its allocation, size, or epoch. Such a pointer is *tainted* (clause C6). Dereferencing a tainted pointer in safe code cannot be `PROVEN_STATIC`. If Tether can recover enough provenance to form a check, the dereference is Tier R; if the provenance is fully opaque, it is Tier N a hard error demanding an [`unsafe` block](/docs/language/unsafe/#unsafe-blocks) or an explicit `assume`/launder that transfers responsibility to the programmer. A pointer that acquires its provenance *inside* an `unsafe` block carries the same taint when it flows back into safe code: unsafe is allowed to *narrow* where checks vanish, but it does not let an untracked pointer leak into a safe dereference as if it were proven. ### Outbound pointers freeze their epoch A Kairo pointer handed to C++ has its allocation's epoch frozen pessimistically: Tether must assume C++ may free, relocate, or retain it. On return from the FFI call, all optimistic facts about that allocation are erased unless an annotation says otherwise. This is unavoidable Tether genuinely lacks the proof and it is where the "as fast as unchecked C++" property does not hold: at the interop boundary you pay, because the proof is on the other side of a wall Tether cannot see through. ### Smart-pointer and reference parameters C++ functions using [smart-pointer or reference types](/docs/language/c-cpp-calling/#pointers-and-references) map automatically and require no `unsafe`: | C++ type | Kairo Tether type | Requires `unsafe` | |----------------------|---------------------------|-------------------| | `std::unique_ptr` | `std::Unique` | No | | `std::shared_ptr` | `std::Shared` | No | | `std::weak_ptr` | `std::Weak<*T>` | No | | `T&`, `const T&` | `*T`, `*const T` | No | | `T&&` (move ref) | `*T` (ownership transfer) | No | A mismatch between Tether's promotion and the C++ signature is a compile error. ### Raw-pointer parameters and shallow analysis C++ functions taking raw pointers (`T*`, `void*`) require an `unsafe` block; Tether does not track across the boundary. For raw FFI calls where the C++ source is visible via the imported header, Tether performs a **one-level** heuristic: if the function only dereferences the pointer without aliasing, storing, or forwarding it, the call may be classified safe without `unsafe`. The analysis does not recurse. If the body is not visible (forward-declared, compiled library), all raw-pointer parameters are opaque and `unsafe` is required. Reading a C++ body is outside what Tether can prove, so a call classified safe this way rests on an **assumption**, not a proof: the build records it in its [unchecked assumptions](#unchecked-assumptions) as "`foo` treated as non-retaining by body inspection". --- ## Generic Code Tether analyzes each monomorphization with full concrete type information [generics](/docs/language/generics/) are not an opaque boundary: ```kairo fn take_ownership(x: *T) { // x is the sole pointer to the allocation after this call } fn caller() { var *cfg = @create Config(8080) take_ownership(cfg) // ownership transferred; using cfg after this is a compile error } ``` If `T` has a `@move` [transfer constructor](/docs/language/classes-lifecycle/#the-transfer-constructor), Tether tracks the transfer through the move; if `T` is `@copy`, Tether knows both source and destination are live after the copy. Each instantiation is analyzed as if it were a hand-written concrete function. --- ## .amt Summaries Whole-program analysis cannot re-walk every callee at every call site. Each translation unit produces a `.amt` summary alongside its object file, and the link pass consumes all summaries to resolve cross-TU pointer flows. The summary is what lets a caller discharge a callee's obligations without re-analyzing its body. ### Summary contents A function's summary records four sections per pointer parameter and for the function's effect on reachable state: - **Requires**: preconditions the caller must discharge before the call (e.g. *`ptr` in allocation, access `<=` 16 bytes*). - **Guarantees**: postconditions the caller may assume after the call (e.g. *`ptr` unchanged*). - **Preserves**: arguments and state the function provably does not mutate. Hoisting reads this: the `loop_bound == allocation_count` proof requires that an intervening call **Preserves** the size variable. - **Escapes**: what the function retains beyond its own frame (stores, returns, captures). Lifetime analysis reads this. `Escapes` defaults to *everything* and `Preserves` to *nothing* when analysis is incomplete: the summary fails **closed**. An incomplete summary costs precision (more residual, more checks or errors), never soundness. The caller-discharges-obligation model: when a pointer flows into a function, Tether consumes the summary rather than the body. If the caller has already proven the `Requires`, the checks are skipped; if it cannot, Tether emits one assertion before the call to establish the precondition. Tether does not need to look inside the callee. ### Summaries are proof certificates, not caches A summary is only sound if it is **correct and current**. A stale summary one whose source changed but whose summary was not regenerated silently disables checks at every call site, which is the single largest soundness surface in the system. Summaries are therefore **content-hashed** against the function body's IR. A call site consuming a summary records the hash; a mismatch at link time is a **hard error**, not a remark and not a silently-trusted cache. There is no "trust me" mode in release. Treat the summary as a certificate that must validate, not a file that is probably fine. (`.amt` files are regenerated by the build system and need not be committed to version control.) > [!IMPORTANT] > The `.amt` file format and the link-time resolution pass are still being finalized. The four-section schema and the content-hash invariant above are the fixed parts; wire-format specifics may change before 1.0. --- ## Soundness and Testing Tether makes a strong claim `PROVEN_STATIC` means an access is safe with no runtime evidence and a proof engine cannot ship on inspection alone. Two properties pin it down. ### The soundness property > If a dereference classifies as `PROVEN_STATIC`, then no clause of its obligation can fail at runtime for any execution. This is what licenses emitting a bare `mov`. The full proof belongs in the Tether paper, not here; the property to hold against is that the static classification is an under-approximation of safety the analysis only proves a clause when it is genuinely discharged, and every uncertainty is resolved toward residual (the monotone "take the weaker state at a merge" rule). Failing closed at every boundary interop, threads, summary gaps, non-convergent recursion is what keeps the under-approximation honest: optimism is what would make the property false, and Tether is never optimistic at a boundary. ### Unchecked assumptions Some facts Tether uses cannot be proven from Kairo source. Each one is recorded in a list the build emits next to its output, so the soundness claim for a program is exactly "safe, given these assumptions" and the assumptions are visible: - a raw-pointer C++ call classified safe by the [one-level body heuristic](#raw-pointer-parameters-and-shallow-analysis) - a function [declared single-threaded](/docs/language/tether-threading/#entry-from-c-and-c) although C++ can reach it - an `assume`/launder that transfers responsibility for a tainted pointer to the programmer An empty list means the proof covers the whole program. ### Paranoid mode the empirical falsifier The contrapositive of the soundness property is directly testable. **Paranoid mode** emits the runtime check for *every* dereference regardless of its classification including the ones marked `PROVEN_STATIC`. Then: > If a check fires in paranoid mode at a site Tether classified `PROVEN_STATIC`, the static proof was wrong. That is a soundness bug. Paranoid mode is the fuzzing oracle. It is cheap to build (the check-emission machinery already exists for Tier R; paranoid mode just disables the suppression) and it turns "is the lattice sound" from a question answered by inspection into one answered by running the test suite under instrumentation. **It is the first thing to build,** before trusting any `PROVEN_STATIC` in anger. ### Optimization-level independence Tether's proof results are **independent of the LLVM optimization level**. The lattice is computed before, and separately from, the backend optimization passes. A higher opt level may *lower* a check more cheaply, but it may never change a dereference's proof *state*. The set of dereferences that carry a runtime check is **identical at every opt level**. This is a hard invariant, and it is the kind that belongs in CI: a `FileCheck` assertion that a given dereference emits (or does not emit) a check, pinned and run at every opt level. Without it, safety-relevant codegen the presence or absence of a check could drift with optimization settings, and a check that exists at `-O0` but is "optimized away" at `-O2` would be indistinguishable from a miscompile. The invariant makes that class of bug impossible by construction and testable by assertion. ## See also - [Tether](/docs/language/tether/) - [Proof Model](/docs/language/tether-proof-model/) - [Bounds and Provenance](/docs/language/tether-bounds/) - [Ownership and Promotion](/docs/language/tether-promotion/) - [Threading](/docs/language/tether-threading/) - [C/C++ Interop](/docs/language/c-cpp/) - [Generics](/docs/language/generics/) - [Unsafe](/docs/language/unsafe/) --- ## Ownership and Promotion URL: https://www.kairolang.org/docs/language/tether-promotion/ # Ownership and Promotion Provenance and epochs govern whether an *access* is safe. A separate analysis governs *where a value lives and who frees it*. Its residuals are Tier P (transformable) or Tier N (unfixable), never Tier R there is no runtime check for "who owns this." When Tether determines that a heap pointer needs ownership semantics, it selects a [smart pointer type](/docs/language/pointers/#smart-pointer-promotion) from the pointer's whole-program usage. In **debug** it performs the promotion and warns; in **release** it emits a hard error naming the type to annotate. ## `std::Unique` single owner Exactly one live binding holds the pointer at any point. Ownership may transfer between scopes; the count of live owners is always one. ```kairo fn make_config() -> *Config { var *cfg = @create Config(8080) return cfg // debug: promote cfg -> std::Unique // release: error, annotate the return type } ``` ## `std::Shared` multiple owners Multiple live bindings refer to the same allocation and single ownership cannot be proven. The allocation is reference-counted; the object is destroyed when the last `Shared` reference's scope ends. ```kairo fn share_config(a: *Server, b: *Server) { var *cfg = @create Config(8080) a.config = cfg b.config = cfg // debug: promote cfg -> std::Shared } ``` A short-lived alias that dies before the owner escapes does **not** force `Shared`. The trigger is not "multiple pointers exist" but "multiple pointers are *live* at a point where shared ownership is required for safety." ```kairo var *cfg = @create Config(8080) { var tmp: *Config = cfg validate(tmp) } // tmp is dead here return cfg // single owner at the escape -> Unique ``` ## `std::Weak<*T>` back-reference A pointer that, promoted to `Shared`, would close a reference cycle (A -> B -> A). `Weak` does not contribute to the count and does not keep the target alive; access requires a liveness check. ```kairo class Node { var child: *Node var parent: *Node // points back at the owner -> Weak } ``` ## No promotion A pointer whose lifetime is fully contained, or provably bounded by its referent's lifetime, stays a plain `*T` with no overhead: ```kairo fn process() { var *data = @create Buffer(1024) fill(data) consume(data) @destroy data // fully contained -> plain *T } ``` Field access and interior pointers are covered in [Bounds and Provenance](/docs/language/tether-bounds/#field-access-and-interior-pointers). --- ## Stack Pointers A stack value has no heap allocation behind it, so it cannot be promoted to a smart pointer. But the (B) model splits stack escape into two cases by whether the value is **heap-promotable** that is, whether Tether can mechanically rewrite the stack allocation into a [`@create`](/docs/language/pointers/#heap-allocation) call. **Heap-promotable escape Tier P.** A plain local whose address escapes via return or store, where the value's type can be heap-allocated: ```kairo fn make() -> *i32 { var x = 42 return &x // debug: rewrite `var x = 42` into `var x = @create i32(); *x = 42`, // then promote the escaping pointer (Unique) // release: hard error, heap-allocate explicitly or restructure } ``` In debug, Tether lifts `x` to the heap and the escape becomes a legal ownership transfer. In release this is a hard error, because silently turning a stack allocation into a heap allocation in a release binary is exactly the hidden allocation the language forbids. The diagnostic shows the fix: ``` error[Tether]: address of stack local 'x' escapes its scope --> src/m.k:3:12 3 | return &x | ^^ 'x' is stack-allocated and destroyed at end of make() note: in debug, Tether would heap-promote: var x = @create i32() help: allocate on the heap explicitly, or restructure to avoid the escape ``` **Non-promotable escape Tier N.** A borrow with no value to lift (a pointer into a structure Tether cannot heap-allocate, an escape into an opaque sink where Tether cannot even establish the heap-allocation pattern) is a hard error in both modes. There is nothing to transform. Dangling within a function is likewise a hard error in both modes the value is gone, there is no allocation to lift, and the access is statically known to be invalid: ```kairo fn also_bad() { var p: *i32 { var x = 42 p = &x } // x destroyed here (epoch incremented) *p = 10 // hard error: p's provenance epoch is stale } ``` ## See also - [Tether](/docs/language/tether/) - [Proof Model](/docs/language/tether-proof-model/) - [Bounds and Provenance](/docs/language/tether-bounds/) - [Threading](/docs/language/tether-threading/) - [Tether Internals](/docs/language/tether-internals/) - [Ownership](/docs/language/ownership/) - [Pointers](/docs/language/pointers/) - [Class Lifecycle](/docs/language/classes-lifecycle/) --- ## Proof Model URL: https://www.kairolang.org/docs/language/tether-proof-model/ # Proof Model ## The Dereference Obligation Every [safe-pointer](/docs/language/pointers/#safe-pointers-t) dereference `*p` where `p: *T` carries a single safety obligation, stated as a conjunction of independent clauses. The access is sound if and only if every clause holds: $$ \def\arraystretch{1.5} \begin{array}{l} \operatorname{deref}(p : {*}T) \ \text{is sound} \iff \\ \begin{array}{lrll} \htmlClass{k-tag}{\texttt{C1}} & & \operatorname{epoch}(\operatorname{prov}(p)) = \operatorname{live\_epoch}(\operatorname{alloc}(\operatorname{prov}(p))) & \enspace \htmlClass{k-note}{\small\text{provenance / use-after-free}} \\ \htmlClass{k-tag}{\texttt{C2}} & \land & 0 \le \operatorname{byte\_offset}(p) & \enspace \htmlClass{k-note}{\small\text{no underflow}} \\ \htmlClass{k-tag}{\texttt{C3}} & \land & \operatorname{byte\_offset}(p) + \operatorname{sizeof} T \le \operatorname{size}(\operatorname{alloc}(\operatorname{prov}(p))) & \enspace \htmlClass{k-note}{\small\text{no overflow / bounds}} \\ \htmlClass{k-tag}{\texttt{C4}} & \land & p \ne \text{null} & \enspace \htmlClass{k-note}{\small\text{nullability}} \\ \htmlClass{k-tag}{\texttt{C5}} & \land & \bigl(\neg \operatorname{shared}(\operatorname{alloc}(\operatorname{prov}(p))) \lor \text{readonly\_extent} \lor \text{synced}\bigr) & \enspace \htmlClass{k-note}{\small\text{data-race freedom}} \\ \htmlClass{k-tag}{\texttt{C6}} & \land & \bigl(\neg \operatorname{tainted}(\operatorname{prov}(p)) \lor \operatorname{laundered}(p)\bigr) & \enspace \htmlClass{k-note}{\small\text{provenance integrity}} \end{array} \end{array} $$ Where: - $$\operatorname{prov}(p)$$ is the **provenance** of `p`: which allocation it points into and the epoch at which that pointer value was derived. - $$\operatorname{alloc}(\operatorname{prov}(p))$$ is the originating allocation; $$\operatorname{size}(\dots)$$ is its byte size; $$\operatorname{live\_epoch}(\dots)$$ is its current generation (see [Provenance and Epochs](/docs/language/tether-bounds/#provenance-and-epochs)). - $$\operatorname{byte\_offset}(p)$$ is the offset of `p` from the allocation base, in bytes. Stated in bytes so the $$\operatorname{sizeof} T$$ scaling in C3 is explicit and the element-count-times-size multiply cannot silently overflow. Each clause is a distinct **proof domain** with its own analysis. Tether discharges as many clauses as it can statically. The clauses that remain (the **residual**) determine what is generated. The mapping from a residual clause to a code-generation response is the entire specification of Tether's behavior, and it is given in [The Residual Table](#the-residual-table). The obligation is split across formation and dereference. Forming a pointer value (`var *q = p + i`) carries one obligation of its own, the **formation range**: $$ 0 \le \operatorname{byte\_offset}(q) \le \operatorname{size}(\operatorname{alloc}(\operatorname{prov}(q))) $$ that is, `q` lies in the allocation or exactly one past its end. A formation proven in range emits nothing; one statically out of range is a compile error; an unprovable one is a Tier R check at the arithmetic, discharged and hoisted by the same bounds machinery as C3. Because every safe pointer value satisfies the formation range, C2 holds for every formed pointer, and at `*q` only C3's extra `sizeof T` of room (and the other clauses) remain. Tether still carries symbolic offsets through SSA and discharges both obligations as late and as rarely as it can; adjacent formation and dereference checks fuse into one (see [Pointer Arithmetic](/docs/language/tether-bounds/#pointer-arithmetic)). --- ## The Proof Lattice Tether is a forward dataflow analysis over the program's SSA graph. For each pointer at each program point it computes a **fact tuple**: one element per clause domain, recording how strongly that clause is currently proven. ### Per-clause lattice Each clause domain has a small lattice of proof states. For the structural clauses (C1, C4, C6) the lattice is height-2: $$ \def\arraystretch{1.4} \begin{array}{cl} \texttt{Proven} & \qquad \htmlClass{k-note}{\small\text{(the clause is statically discharged here)}} \\ \sqsubset & \\ \texttt{Residual} & \qquad \htmlClass{k-note}{\small\text{(the clause must be discharged at runtime, or is a hard error)}} \end{array} $$ For the bounds clause (C2/C3) the lattice is height-3, because bounds admits an intermediate state where the property is provable over a region rather than at a single point: $$ \def\arraystretch{1.4} \begin{array}{cl} \texttt{Proven} & \qquad \htmlClass{k-note}{\small\text{(offset statically known in range, no code)}} \\ \sqsubset & \\ \texttt{HoistableResidual} & \qquad \htmlClass{k-note}{\small\text{(provable over a loop/region, one check at region entry)}} \\ \sqsubset & \\ \texttt{DynamicResidual} & \qquad \htmlClass{k-note}{\small\text{(must check at this specific dereference)}} \end{array} $$ `Proven` is the strongest (least) element. The order $$\sqsubseteq$$ means "at least as proven as." `Residual` and `DynamicResidual` are the weakest elements of their domains. ### The product lattice The fact tuple for a pointer is an element of the product lattice $$ L = L_{\text{C1}} \times L_{\text{C2C3}} \times L_{\text{C4}} \times L_{\text{C5}} \times L_{\text{C6}} $$ ordered componentwise. The product of finite-height lattices is itself a finite-height lattice; the height of $$L$$ is the sum of the component heights, which is a small constant (independent of program size). The transfer functions for each IR operation are **monotone** with respect to $$\sqsubseteq$$: an operation never increases the proof strength of a clause it has no evidence for, and joining facts at control-flow merge points takes the weaker (less proven) state. Monotone transfer functions over a finite-height lattice means the Kleene iteration over the classification reaches a fixed point in a bounded number of passes (bounded by the lattice height times the number of program points). (A pass ceiling exists for *interprocedural* recursion, but it degrades precision, never soundness: hitting it demotes clauses to Residual, which is always safe. See [Summaries](/docs/language/tether-internals/#amt-summaries).) This argument covers the classification lattice only. Deciding *which* state a clause is in needs the numeric facts underneath, and that domain is not finite-height. ### The numeric domain Proving `0 <= i < 120` from a loop, or `loop_bound == allocation_count` from an allocation site, needs facts about integer values, not only proof states. Underneath the lattice, Tether keeps a relational numeric domain over SSA values: - **intervals** per integer value (`i ∈ [0, n)`) - **SSA equalities and symbolic offsets** (`n == count(a)`, `off(q) == off(p) + 4·k`) - **induction-variable recognition**: loops with a recognizable induction variable (`for i in 0..` | write one C++ header per module ([Using Kairo in C++](/docs/language/c-cpp-exposing/)) | | `--type-check-only` | parse and check without generating code | | `--target=`, `--sysroot=`, `--freestanding`, `--native` | [cross-compilation and sysroots](/docs/language/c-cpp-toolchain/#cross-compilation) | | `--no-sysroot-build` | with `--target` and no installed or cached sysroot, refuse (`P009E`, exit 2) instead of building one with [ksys](/docs/toolchain/ksys/) | | `--sysroot-exact` | use `--sysroot` exactly as given: never substitute a bundled or cached sysroot for the target (what `ksys` itself relies on when it compiles the runtimes) | | `--print-runtimes-revision` | print the LLVM runtimes revision this compiler was built from, and exit | | `--progress=auto\|always\|never\|lines` | the build status line | | `--sema-threads=N`, `--codegen-threads=N`, `--threads=N` | parallelism of type checking and code generation | | `--interface-pch=auto\|on\|off` | share precompiled Kairo interfaces between files | | `--cache-dir `, `--force-recompile` | [incremental compilation](/docs/language/c-cpp-toolchain/#incremental-compilation): unchanged files skip code generation | | `-finfer-purity` / `-fno-infer-purity` | infer `const` / `@pure` for functions that make no promise (on by default) | | `-fimplicit-conv` / `-fno-implicit-conv` | Kairo's implicit conversions ([Conversion Lattice](/docs/language/conversion-lattice/)); on by default. Applies to your files only: the builtin and std libraries always compile with the default rules | | `-funwind`, `-fcxx-implicit-conv` | apply to your own files only; the standard library always compiles with `noexcept` functions and without C++ implicit conversions | | `-fcxx-implicit-conv` / `-fno-cxx-implicit-conv` | at a call into C++, apply the implicit conversions C++ would (one converting constructor or conversion operator; a string literal as its `const char[N]`); off by default, so such an argument needs ` as T` | | `-Wconst-self` | opt-in lint for methods that could take `const self` | | `--error-format=...`, `--explain `, `--diag-show-ids` | diagnostics: `--explain` prints the long form of a code | | `--print-stats`, `-v` | timings, counts, and what each step did Also, in a build with an import cycle, the number of re-export fixpoint rounds | | `--help`, `--help-hidden` | list the flags; `--help-hidden` adds internal and not-yet-implemented ones | On x86, `--march` names a CPU as `--mcpu` does, and an unknown one is an error (P006E) before compilation starts. `--print-ast=tree` lists a struct's and union's constructors and operators as well as its fields. ## Targets and sysroots `--target=` compiles for another platform. The first time you name a target whose sysroot is neither shipped in the install (`/sysroot/`) nor already cached, `kairo` builds it in-process from the sources the toolchain ships and prints `building sysroot for , first time only`. Later builds reuse the cached root. `--sysroot=` names a root you already have, `--freestanding` compiles without one, and `--no-sysroot-build` turns the automatic build into an error. A failed build is `P010E` (exit 3); a refusal is `P009E` (exit 2). The `*-apple-macosx` and `*-windows-msvc` targets need your own SDK and are never built this way ([ksys](/docs/toolchain/ksys/#targets-that-need-your-sdk)). Target names, including the glibc version suffix (`x86_64-linux-gnu.2.17`), the cache and `KAIRO_SYSROOT_CACHE` are on the [ksys](/docs/toolchain/ksys/) page. Pretty diagnostics show the location as `file:line:col`. On a terminal a build prints a single status line (`parse`, `sema`, `codegen` with counts) that disappears before any diagnostic appears. `kairo` finds its standard library, runtime and clang resources relative to its own location, so an unpacked release runs without flags. `python3 build.py` stages the same layout when building from source ([Installation](/docs/install/#building-from-source)). See also [kcc](/docs/toolchain/kcc/), [ksys](/docs/toolchain/ksys/), [kld](/docs/toolchain/kld/) and [kfmt](/docs/toolchain/kfmt/). --- ## kals URL: https://www.kairolang.org/docs/toolchain/kals/ # kals `kals` is the Kairo language server. It speaks the Language Server Protocol over stdin and stdout, so any editor with an LSP client can use it. ```sh kals # run the server (an editor starts this) kals --version ``` `kals` ships with the Kairo toolchain, in the same `bin/` as `kairo` and `kfmt`, so installing Kairo installs it. Formatting runs `kfmt`, found beside `kals` or on `PATH`. ## What it does | Feature | Notes | |---|---| | Diagnostics | the compiler's own, from the text in the editor, saved or not. Syntax errors in the file being edited come first, from a parse of that file alone; the type check's diagnostics follow and replace them | | Quick fixes | every compiler fix-it is a code action | | Semantic highlighting | functions, methods, types, parameters, constants, enum members, namespaces; see below for the two Kairo-specific marks | | Go to definition | a call goes to the overload that was chosen; an operator goes to its `op` function. Also go to type definition and declaration | | Signature help | every overload of the function being called, with the argument being typed marked | | Hover | the declaration and its `///` documentation; a type shows its body (an enum its underlying type and every variant with its value or payload, a union its members) and, when it follows from the fields alone, its size and alignment | | Completion | as a name is typed: the locals and parameters in scope, the file's declarations, what it imports, the builtin library, macros (`name!`) and the keywords that fit the position; members after `.`, `->` and `::`, with only what the file may access; attributes after `@`; import paths and the names a module exports; header paths inside `ffi "c++" import "..."`. Answered from the server's index in a few milliseconds, also while the line does not parse; see below | | References, highlight, rename | across the files of the project | | Formatting | `kfmt`'s output, so the editor and the command line never disagree | | Outline, workspace symbols, folding | | | Inlay hints | the type of a declaration that did not write one; parameter names at calls; what an interface inherits from the ones it derives | | Hierarchies | callers and callees of a function; supertypes and subtypes; go to implementation | | Code lenses | reference counts above functions and types | | Links | an import path opens the file it resolved to | | Macros | hover an invocation to see what it expands to; the quick-fix menu offers **View expanded macro** (VS Code shows it read-only beside the editor) and **Expand macro here** (replaces the invocation with its expansion) | | Generate interface | on a class or struct name, the refactor menu offers **Generate interface for 'Name'**: `pub interface IName` above the type with every public instance method's signature and doc comment, and `impl IName` added to the type | | C and C++ beside Kairo | a C or C++ file of the project that writes `#include "foo.k"` resolves in clangd: kals writes `foo.k`'s C++ header into `.kairo/clangd/`, keeps it current as you type, and points clangd at it through a VFS overlay in a `.clangd` file (see below) | | Progress | shown while a workspace is first indexed, in editors that display LSP progress | ### Overloads and `where` dispatch A call in Kairo can be more than it looks: the name may stand for several overloads, `a + b` may run a user-defined `op +`, and a function with [`where`](/docs/language/where/) guards picks its body at run time. kals marks these with two semantic token modifiers: | Modifier | Meaning | |---|---| | `overloaded` | the callee is one of several declarations of that name, is constrained by a `requires` clause, or the operator is user-defined | | `dispatched` | the callee dispatches through `where` guards | Other modifiers kals sends: | Modifier | Meaning | |---|---| | `extension` | a call to a method or operator an `extend` block supplies | | `ffi` | a name declared in C or C++ (such a call is never also `overloaded`) | | `unsafe` | a call to an `unsafe fn`, the operator of `unsafe &x` / `unsafe *p`, and the `unsafe` keyword | | `mutates` | the `&` of an argument the call may write through: an `@inout` marker, or the address of a `var` passed to a `*T` parameter (never to a `*const T`) | | `inout` | the `&` of an argument bound to an `@inout` parameter, or to a C++ `T&` | | `pointer` | the `&` of an argument bound to a pointer parameter; with `unsafe` for `unsafe *T` (a C++ `T*`), with `readonly` for `*const T` (both for a C++ `const T*`) | | `deprecated` | a use of a `@deprecated` declaration | | `mutable` | a `var` binding and its uses | | `constant` | a `const` or `eval` binding | | `panics` | a call to a function declared `panic`; sent only when `highlightPanics` is on | A macro name and its `!` are one token of the standard `macro` type: an invocation (`double!(5)`, `greeting!`, `lib::twice!(2)`), a definition's name (with `declaration`), and a macro imported by name. A builtin macro such as `stringify!` or `file!` also carries `defaultLibrary`. This comes from the raw text, so it stays the same while a line does not parse. The editor extensions draw them the same way: `overloaded` underlined, `dispatched` underlined and italic, `extension` and `ffi` italic, `unsafe` bold, `mutates` bold, `deprecated` struck through, constants in the enum-member colour, macros in amber, and `panics` with a dotted underline where the editor can draw one (Neovim; not VS Code). The `&` of a call argument is bold and coloured by the parameter it binds to, so a call site shows what the call can do with the argument: | Argument | Parameter | Colour | |---|---|---| | `bump(&n)` | `@inout x: i32`, or a C++ `int&` | green | | `poke(&n)` | `p: *i32` (or `*i32?`) | the theme's operator colour | | `raw(unsafe &n)` | `p: unsafe *i32`, or a C++ `int*` | purple | | `peek(&n)` | `p: *const i32` | grey-blue | | `rawc(unsafe &n)` | `p: unsafe *const i32`, or a C++ `const int*` | purple, italic | The same holds for `&a.b`, `&v[i]`, named arguments and method calls. A C++ `const T&` or `T&&` parameter takes no `&` at the call, so there is nothing to colour. In VS Code these are defaults you can override: ```json "editor.semanticTokenColorCustomizations": { "rules": { "*.overloaded:kairo": { "underline": true }, "*.dispatched:kairo": { "underline": true, "italic": true }, "operator.inout:kairo": { "bold": true, "foreground": "#2EA043" }, "operator.pointer.unsafe:kairo": { "bold": true, "foreground": "#B44FD6" }, "operator.pointer.readonly:kairo": { "bold": true, "foreground": "#7088A8" }, "macro:kairo": { "foreground": "#D4900A" } } } ``` An undeclared name reports R020E without hiding the inferred types of the rest of the file. ## Completion Completion does not run the compiler. kals keeps, for every file of the project and of the library, a table of what the file declares (each name with its kind, signature, visibility and type), and for every open file the names its imports bring in. A request is answered from those tables and from the text in the editor, so the list arrives in a few milliseconds and does not depend on the line, or the file, parsing. | Where | What is offered | |---|---| | a name | locals and parameters in scope (a local of a block that has closed is not), the members of the enclosing type, the file's declarations, what it imports, the builtin library, macros as `name!`, and keywords: statement keywords at a statement's start, declaration keywords at file level and in a type's body, types and primitive type names where a type is written | | after `.`, `->`, `::` | the members of the receiver: a value's type, a type, a module, an enum. Inherited members and the methods of the `extend` blocks the file sees are included; a `priv` or `prot` member is offered only where the file may use it | | after `@` | the built-in attributes, each with how it is written and what it does; before a declaration that is already written, the attributes that declaration takes | | in `import a::b::` | module paths, and inside `import a::{ ... }` the names the module declares | | in `ffi "c" import "` / `ffi "c++" import "` | headers from the include directories of the project's compile (`-I`, `--cxx-include`, the C and C++ libraries), one directory at a time | | in a comment, in a string, where a name is being declared | nothing | Each item shows its signature; its documentation is loaded when the item is selected. The list holds every candidate for the position, so the editor filters it as you type or delete and does not ask again. The compiler is asked only when the tables cannot say what the receiver is: a range subscript (`v[a..b].`), a C or C++ value, the result of a generic function, a call to overloads that return different types. After a primitive type's name and `::` (`usize::`, `f64::`), completion offers the type's constants (`MAX`, `EPSILON`, …) and the statics of the `extend` blocks the file sees. A local typed since the last check shows its type when it is a construction or a literal. That answer takes a re-check of the file (a few hundred milliseconds, more for a file in a large import cycle). Completion after a deletion: kals answers wherever the cursor is in or after a name. Whether a request is sent after a backspace is the editor's choice. The VS Code extension asks again after a deletion that leaves the cursor in a name (`kairo.completion.triggerOnDelete`, on by default). ## Projects A Kairo command line names one entry point; the compiler finds every other file through imports. kals reads the project's entry points from `kairo_compile.json`, in the workspace folder or any directory above it: ```json { "version": 1, "entries": [ { "entry": "src/main.k", "args": ["-I", "include/", "-fimplicit-conv"] } ], "default_args": ["-I", "include/"] } ``` | Key | Meaning | |---|---| | `entry` | the file you pass to `kairo` | | `args` | every other argument, exactly as on the command line | | `directory` | where the command runs, relative to this file; `.` when omitted | | `default_args` | flags for a file no entry imports yet | A file belongs to the entry that imports it. A file no entry reaches is checked on its own with `default_args`. With no `kairo_compile.json`, every file is checked on its own with no flags, which is enough for a single script. The file is written by hand for now; the build tool will write it. ## Editors The editor clients are in [kairo-lsp](https://github.com/kairolang/kairo-lsp). Each finds `kals` on `PATH` and needs no configuration. The VS Code extension (0.9.2) shows completions again after a deletion that leaves the cursor in a name; `kairo.completion.triggerOnDelete` turns that off. | Editor | Install | |---|---| | Visual Studio Code | the Kairo extension (`vscode/`) | | Zed | `zed/` as a dev extension, then `"languages": { "Kairo": { "semantic_tokens": "combined" } }` (semantic highlighting is off in Zed by default) | | Neovim 0.11+ | put `nvim/` on the runtimepath | | Helix 25.01+ | merge `helix/languages.toml` into `~/.config/helix/languages.toml`, copy `helix/runtime/queries/kairo` into `~/.config/helix/runtime/queries/`, then `hx --grammar fetch` and `hx --grammar build`. Helix colours with tree-sitter only, so the semantic-token marks are not shown | Any other client: start `kals` with no arguments and speak LSP on its stdin and stdout. Positions are UTF-16. Settings, as LSP `initializationOptions` (the VS Code extension passes them from `kairo.kals.*`): | Option | Default | | |---|---|---| | `syntaxDebounceMs` | `100` | fallback only: the edited file is re-parsed alone (its syntax errors, and keyword highlighting while it does not parse) by a long-lived parser process on every keystroke, with no wait; this delay applies only where that process cannot run (Windows for now) and a process is started per pass instead | | `debounceMs` | `150` | wait after the last keystroke before the type check | | `liveCheck` | `true` | Keeps each project entry's graph checked in a worker process and re-checks an edit in place. Set `false` (or `KALS_LIVE_CHECK=0` in the server's environment) for a process per analysis. | | `indexCompletion` | `true` | answer completion from the index. `false` (or `KALS_INDEX_COMPLETION=0` in the server's environment) asks the compiler for every list; for comparing the two | | `maxWorkers` | `2` | entry points analysed at once (a large project always runs one at a time) | | `highlightPanics` | `false` | send the `panics` modifier on calls that can panic (VS Code: `kairo.kals.highlightPanics`; Neovim: `setup({ init_options = { highlightPanics = true } })` or `vim.g.kairo_highlight_panics`) | ## C and C++ files: clangd When a C or C++ file of the project (one named in `compile_commands.json`, or any under the workspace when there is none) includes a Kairo file with `#include "foo.k"`, kals writes the C++ declarations `foo.k` exports to `/.kairo/clangd/foo.hh`, regenerates it on every edit of `foo.k` (saved or not) and of the modules it reads, and writes `/.kairo/clangd/overlay.yaml`, which tells clang to read that header wherever it would read `foo.k`. clangd picks the overlay up from a `.clangd` file in the project: ```yaml CompileFlags: Add: [-ivfsoverlay, /path/to/project/.kairo/clangd/overlay.yaml, -I/path/to/project/.kairo/clangd] ``` kals writes that file itself when the project has none (its first line marks it as kals'). A `.clangd` you wrote is never changed: kals logs the two lines to add instead. Add `.kairo/` to `.gitignore`. clangd then knows every Kairo name the C++ file uses, and a jump to a Kairo declaration opens `foo.k` at the declaration's line: the header is laid out so each declaration sits on the line it has in `foo.k`, with what the compiler adds around it in `foo.hh.prelude` beside it. A declaration on the first line of `foo.k`, or one the C++ header must order after a later declaration (a class that depends on a class below it), can still land a few lines off. ## How it works Each analysis is a separate `kals` process that type-checks one entry point and exits, so a compiler crash on half-typed code costs one stale answer, not the editor's connection. The server keeps the last good result and answers from it until a newer one arrives. There is no incremental analysis yet: a change re-checks the entry's import graph. That is a fraction of a second for a small project and much longer for a very large one. ## Not yet On-type formatting and go to implementation of a single method. Completion after a range subscript (`v[a..b].`), a C or C++ value or a generic function's result asks the compiler, and offers nothing there while the expression does not parse (an unclosed call). User-defined attributes are not listed after `@`. --- ## kbld URL: https://www.kairolang.org/docs/toolchain/kbld/ --- ## kcc URL: https://www.kairolang.org/docs/toolchain/kcc/ # kcc `kcc` is a drop-in replacement for `clang` / `clang++` that understands Kairo. It takes clang's command line (C, C++, Objective-C and Objective-C++ sources, `.k` files, objects and archives) and runs clang in-process: the release ships no `clang` binary. ```sh kcc main.cc -o app # a plain C++ build kcc main.cc foo.k -o app # C++ and Kairo in one link ``` Two additions over clang: - **`#include "foo.k"`** works in a C++ (or Objective-C++) file. The preprocessor reads the Kairo file's interface as C++ tokens, so the C++ side uses Kairo types and functions directly. Only `pub` declarations, and `prot` ones for a C++ file inside the same module, are visible. - **`.k` inputs** are compiled by the Kairo compiler and linked with everything else. An option that Kairo has its own flag for becomes that flag; any other option reaches clang unchanged. `kcc --help` and `kcc --version` describe `kcc`, and `-###` prints each compile job and the link without running them. `--target=` works as in [kairo](/docs/toolchain/kairo/): when the target's sysroot is not installed or cached, `kcc` builds it on first use with [ksys](/docs/toolchain/ksys/), and `--no-sysroot-build` refuses instead. `--sysroot=` names a root you already have and `--freestanding` compiles without one. `kcc` is the supported way to compile C++ in a Kairo project. See [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) for the toolchain model, sysroots, separate compilation and incremental builds, and [Using Kairo in C++](/docs/language/c-cpp-exposing/) for what a C++ file sees. --- ## kfmt URL: https://www.kairolang.org/docs/toolchain/kfmt/ # kfmt `kfmt` formats Kairo source. There is one style and almost no knobs: the line width is 100 columns, blank lines are capped at 4, and there is no config file. It ships in the release beside `kairo` and `kcc`. ```sh kfmt src/ # --check (default): list files that would change, exit 1 if any kfmt --write src/main.k # rewrite in place kfmt --stdout main.k # print the formatted file ``` A directory argument formats every `.k` file under it. ## Flags | Flag | Meaning | |---|---| | `--check` | the default: list the files that would change and exit 1 if there are any | | `--write` | rewrite files in place | | `--stdout` | print the formatted file | | `--no-align` | turn off every alignment rule; a wrapped parameter list falls back to the block form | | `--indent=spaces\|tabs` | indent with spaces (default) or tabs. Tabs are only ever indentation: the padding that aligns columns is always spaces, so alignment survives any tab width | | `--tab-size=N` | width of one indent level: N spaces (default 4) or N tabs (default 1). In tabs mode a tab counts as `N` columns toward the 100-column limit | | `--normalize-parens` | opt-in: remove redundant parentheses and add none, by Kairo's precedence. Every change is checked against the syntax tree | ## What it does **Lists are on one line or one item per line.** Parameters, call arguments, tuple and list literals, named initializers and braced import lists either fit on one line or put every item on its own line; there is no "fill as many as fit". The one-line limit is 100 columns, but a call must end by column 80 or it is split. A list that does not fit has two shapes: the aligned form keeps the first item on the opener's line and aligns the rest under it (parameters), and the block form puts the items one level deeper with the closer on its own line (calls, literals). The block form ends with a trailing comma, the one-line and aligned forms have none. A table of more than six short items becomes a grid, padded per column. **Blocks always break.** `{` ends the line of its header and `}` stands alone; a block is never kept on one line, even for one short statement. `{ }` stays for an empty block. `} else {`, `} catch E {`, `} case B {`, `} default {` and `} finally {` chain on one line. **Imports.** A single name loses its braces (`import Foo::{foo}` becomes `import Foo::foo`, and an aliased one `import Foo::Bar as Baz`); two or more names are always one per line with a trailing comma and no `;` after the `}`. `ffi` header imports come first, Kairo imports are sorted by path. A list of more than six short names becomes a grid. **Alignment.** Runs of consecutive declarations align their keyword, name and type columns, with the `:` glued to the name; runs of assignments align their `=`; name/value lists align when broken; trailing comments in a run align. `--no-align` turns all of this off. **Semicolons.** A `;` that only ends a line is removed, unless the next line starts with something that would continue the statement (`.`, `->`, an infix operator, `else`, `catch`, `=>` and the like). Required semicolons stay (several statements on one line, a C-style `for` header, array types such as `[T; N]`, statement expressions). kfmt never adds one. **Breaks.** A long `&&` / `||` chain breaks before every operator. kfmt never breaks a line in front of `+ - * & ~ ! ++ -- .. ... = ? @ as`, because a line starting with one of those begins a new statement. A string literal is never split, and a line that cannot break is allowed to run over. **Blank lines.** Up to 4 blank lines are kept, none at the start or end of a block, and one blank line goes after a line made only of closers (`}`, `)`, `]`) before the next statement, unless that next line is a closer too. **Comments.** Comment text is never changed or reordered. An own-line comment takes the indentation of the code it precedes. A trailing comment is anchored to the first line of the node it was written on, so it stays with its code when the code is wrapped. **if, try and match expressions.** Both branches stay on aligned lines (`else if` chains are padded to line up under the `if`), a `try` expression's `catch` sits under the `try` with its `=>` aligned, and a `match` expression with more than two cases is broken one case per line. A case with more than six alternatives is laid out as a grid. Text inside string, character, raw-string and f-string literals (including the expressions inside `{...}`) is copied byte for byte. ## Safety kfmt never writes a file whose meaning could have changed. Before `--write` replaces a file the output has to pass all of these: - it parses; - it re-lexes to the same code tokens, apart from removed `;`, a comma before a closer, import order (compared as a multiset) and, under `--normalize-parens`, parentheses; - every comment is present, in the same order; - it dumps to the same syntax tree as the input; - formatting the output again gives the same text. A file that fails any check (or does not parse at all) is left alone, reported as refused, and makes kfmt exit 1. Refusal is not a crash: the rest of the files are still formatted. For the full rule set, with before/after examples, see the formatter's specification in the repository, `Extras/Formatter/README`. --- ## kld URL: https://www.kairolang.org/docs/toolchain/kld/ # kld `kld` is the linker of the Kairo toolchain: LLD, run in-process, for ELF, Mach-O, PE/COFF (including MinGW) and WebAssembly. You rarely call it yourself. `kairo` and `kcc` link through it, and the toolchain ships no separate `ld.lld`. ```sh kld -flavor gnu -o app main.o foo.o # ELF kld -flavor link /out:app.exe main.obj ``` `-flavor` takes the same values as `lld`: `gnu` (ELF), `darwin` (Mach-O), `link` (COFF), `wasm` and `mingw`. Everything else is lld's own command line. ## When it runs Normally the compiler links inside its own process and `kld` is not started. `kld` runs as a separate process when: - the link needs lld options that change global state (`-mllvm`, `--plugin-opt=-...`); - an earlier in-process link in the same run failed in a way that left lld unable to run again. For these the compiler looks for `kld` in the same `bin/` directory as itself, and a missing `kld` is a fatal error naming the path. ## The C++ ABI check Because `kairo` and `kcc` both use the same pinned compiler, the objects of one program agree on layout and mangling. At link time the linker driver also verifies the contract recorded in those objects, so an object built by a different compiler version is reported as a link error instead of misbehaving at run time. See [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) and [ABI Compatibility](/docs/language/c-cpp-abi/). --- ## kpkg URL: https://www.kairolang.org/docs/toolchain/kpkg/ --- ## ksys URL: https://www.kairolang.org/docs/toolchain/ksys/ # ksys `ksys` builds a **sysroot** (a target's C library, headers, C++ runtimes and compiler runtime) from sources shipped inside the toolchain, the way Zig builds its libc on demand. There is no per-target download: the release archive holds one input tree and the compiler, and the first time you ask for a target the toolchain builds its sysroot and caches it. You rarely run `ksys` yourself. `kairo` and `kcc` call the same code in-process, so this is all it takes: ```sh kairo --target=aarch64-linux-musl main.k -o main # first use builds the sysroot; later uses reuse it kcc --target=riscv64-linux-gnu-glibc2.31 main.cc -o app ``` On the first use of a target the driver prints `building sysroot for , first time only` on stderr. A typical build takes 5 to 30 seconds. It needs no network, no CMake, no Ninja and no `make`; it uses the toolchain's own `kcc`, `kld` and `llvm-ar`. ## When the driver builds one For `--target T` with no `--sysroot`, `--freestanding` or `--macos-sdk`, the driver looks for a sysroot in this order: 1. `/sysroot/`, a root shipped in the archive (the host's own); 2. the cache (below); 3. a build with `ksys`, when the install has its input tree (`share/kairo/sysroot`). `--no-sysroot-build` turns step 3 into a refusal. A build that has no input tree to work from is not attempted, and the compiler warns with `P008W` and names `--sysroot`, as before. `--help`, `--version`, `--explain` and the info queries never build; `--version` reports a cached sysroot but does not create one. ```sh kairo --target=riscv32-linux-musl --no-sysroot-build main.k # refuse instead of build ``` ## Commands ``` usage: ksys [--share DIR] [--cache DIR] [-j N] [-q] probe parse and probe; print the table ensure [--glibc=X.Y] [--input DIR] the cached sysroot (built if missing); path on stdout build [--glibc=X.Y] [--input DIR] --out DIR build into DIR, uncached tables --out DIR the runtimes tables the target compiles from, unbuilt validate check a sysroot verify-share re-hash every input of the share tree ls cached sysroots by name gc drop unnamed sysroots and stage dirs older than 30 days rm drop a cached sysroot --print-runtimes-revision the LLVM runtimes revision this toolchain was built from ``` `` is a sysroot name (`x86_64-linux-musl`, `x86_64-linux-gnu-glibc2.31`) or a clang triple. | Command | What it does | |---|---| | `ensure ` | Prints the path of the cached sysroot on stdout, building it first if it is missing. Progress goes to stderr, so `$(ksys ensure T)` is safe in a script. | | `build --out DIR` | Builds into `DIR` and does not use or fill the cache. | | `probe ` | Parses the name and reports what is needed without building: the sysroot name, family, provider, libc version, whether the LLVM backend is compiled in, the clang triple, the quirks that apply, whether the provider supports the arch, whether the tools are present, and the target's properties (bits, endianness, int128, exception model). It stops with a refusal if the target cannot be built. | | `validate ` | Checks a sysroot: its structure, that the toolchain builds against it, and a C, C++ and Kairo program built and run (under QEMU, Wine or Node where one is installed; a step that cannot run is printed as `SKIP`, never as a pass). | | `tables --out DIR` | Writes the runtimes tables (the exact compile lines for compiler-rt, libunwind, libc++abi and libc++) that the target would be built from, without building. | | `verify-share` | Re-hashes every input of the share tree against its recorded hash. | | `ls`, `gc`, `rm ` | List the cache, drop unreferenced sysroots and stage directories older than 30 days, or remove one sysroot by name. | | `--print-runtimes-revision` | Prints the LLVM revision the toolchain's C++ runtimes sources must match. `kairo --print-runtimes-revision` prints the same. | Options before the command: | Option | Meaning | |---|---| | `--share DIR` | the input tree to build from (default `$KAIRO_SYSROOT_SHARE`, else `/share/kairo/sysroot`) | | `--cache DIR` | the cache root (default below) | | `-j N` | parallel compile jobs (the default is the number of hardware threads; `$KSYS_JOBS` also sets it) | | `-q` | quiet: no progress on stderr | `--glibc=X.Y` picks a glibc version and `--input DIR` names the user-supplied SDK for the targets that need one ([below](#targets-that-need-your-sdk)). Exit status: `0` ok, `1` usage, `2` a refusal (nothing was built; one line says why), `3` a build or validation failure. ## Target spelling A target is a name of the form `-[-][-glibc]`, or any clang triple that maps to one. `ksys` and the compiler accept both and normalize: | You write | The sysroot is named | The clang triple is | |---|---|---| | `x86_64-linux-musl` | `x86_64-linux-musl` | `x86_64-unknown-linux-musl` | | `x86_64-unknown-linux-musl` | `x86_64-linux-musl` | `x86_64-unknown-linux-musl` | | `x86_64-linux-gnu-glibc2.31` | `x86_64-linux-gnu-glibc2.31` | `x86_64-unknown-linux-gnu` | | `aarch64-linux-gnu` | the default glibc version of the share, spelled out in the name | `aarch64-unknown-linux-gnu` | | `x86_64-linux-gnu.2.17` | `x86_64-linux-gnu-glibc2.17` | `x86_64-unknown-linux-gnu` | | `armv7-linux-gnueabihf-glibc2.31` | the same | `armv7-unknown-linux-gnueabihf` | The glibc version can be written two ways: `-glibc` at the end of the name, or Zig's `.` suffix after the environment (`x86_64-linux-gnu.2.17`). A glibc target without a version builds against glibc 2.31, the floor the shipped roots use, so its programs run on any distribution with glibc 2.31 or newer. Any version from 2.17 to 2.42 is available (`riscv32` from 2.33, `loongarch64` from 2.36); a version outside the architecture's range is refused. 32-bit Arm on Linux is always hard-float (`gnueabihf`, `musleabihf`): the name carries no float ABI, so a soft-float triple is refused. A name that is not a sysroot name, or that matches several, stops with an error listing the candidates. Any well-formed triple names a target. Whether it can be built is then decided in this order, each with its own refusal: the LLVM backend must be compiled into the toolchain, the target's family must have a recipe for that architecture, and the runtimes must be derivable for it. ## Where things live **The cache** holds what `ksys` built: | | | |---|---| | Location | `$KAIRO_SYSROOT_CACHE`, else `sysroot/` under the toolchain cache root | | Toolchain cache root | `$KAIRO_CACHE_DIR`, else `$XDG_CACHE_HOME/kairo`, else `~/.cache/kairo`, else `%LOCALAPPDATA%\kairo` on Windows | | Layout | `sysroots//` the finished sysroots, `by-name/` the entry the driver looks up, `stage/` the build stages, `locks/` | A sysroot's key covers its inputs and the toolchain's own build, so a new toolchain builds fresh sysroots instead of reusing stale ones. Two compiles of the same target at once wait on one build. Delete the directory at any time: it is only a cache. `ksys gc` drops sysroots nothing names and stage directories older than 30 days. **The share** is the input tree: the libc sources and headers, the glibc symbol lists, the mingw-w64 and wasi-libc sources, the BSD base trees, the Linux UAPI headers and the licenses of all of it. It is at `/share/kairo/sysroot`, or wherever `$KAIRO_SYSROOT_SHARE` or `--share` points. Every input is checked against a recorded hash before anything is built, and the toolchain refuses a share that does not match it. The C++ runtimes are built from `/share/kairo/runtimes`, whose `REVISION` must equal `ksys --print-runtimes-revision`. A generated sysroot carries the licenses of the parts it was built from in `LICENSES/`, so you may ship it, for example inside a container image. ## Diagnostics | Code | Exit | Meaning | |---|---|---| | `P009E` | 2 | The generator refused: the target is not a sysroot it knows, the input tree is missing or does not match its hashes, the runtimes revision does not match the compiler, the LLVM backend is not compiled in, the family has no port for that architecture, or a tool is missing. Nothing was built and nothing is downloaded. | | `P009N` | | The note under a `P009E`: what to do about it. | | `P010E` | 3 | A build stage or the validation ran and failed. The message names the stage and a log directory; the failed stage is kept as `.failed` and is retried on the next build. A failure that repeats with the same inputs is a toolchain bug: report it with that log. | `kairo --explain P009E` and `--explain P010E` print the long form. `--no-sysroot-build` produces a `P009E`. ## Targets that need your SDK Apple's and Microsoft's licenses forbid redistributing their SDKs, so `ksys` never builds those roots from the shipped tree and the compiler never bundles them. Without one, `--target` for these triples stops with `P008E` that names the script to run, except where the compiler can assemble the root itself from an SDK you have installed: on a Mac the first macOS build does (see [Installation](/docs/install/#macos-and-msvc-targets)). The toolchain ships two scripts in `/scripts/` that build your own copy into `/sysroot/`, where `kairo --target` finds it with no flags. **macOS** (`*-apple-macosx`; `arm64`, `arm64e`, `x86_64`), on a Mac with the Command Line Tools installed (`xcode-select --install`): ```sh /scripts/darwin-sysroot.sh arm64 ``` It reads the SDK from `xcrun --sdk macosx --show-sdk-path`, or from `SDK=`. A macOS sysroot can only be built on a macOS host with this script, or from a copy of the SDK you are licensed to use. **MSVC Windows** (`*-windows-msvc`; `x86_64`, `aarch64`, `i686`). On Windows with Visual Studio (the "Desktop development with C++" workload) the script uses the installed CRT and Windows SDK: ```powershell powershell -ExecutionPolicy Bypass -File \scripts\msvc-sysroot.ps1 x86_64 ``` On Linux, macOS or WSL the script fetches the CRT and Windows SDK itself with [xwin](https://github.com/Jake-Shadle/xwin): ```sh /scripts/msvc-sysroot.sh x86_64 # or: aarch64 i686 ``` It prints Microsoft's license and asks you to accept it. `--accept-license` or `KAIRO_ACCEPT_MSVC_LICENSE=1` accepts it up front (for CI); a non-interactive run with neither stops. The script uses `xwin` from `$XWIN_BIN`, else `PATH`, else downloads a pinned release (checking its sha256) into `/share/kairo/tools/`. The download is kept in `/share/kairo/msvc-cache/` and reused by later runs. To use a splat you made yourself, set `XWIN=`. Both scripts compile libc++ and compiler-rt from `share/kairo/runtimes` with the toolchain's own `kcc` and `kld`. Keep the generated roots on your machine: they contain Apple's or Microsoft's files. ## Supported targets Names below are what `--target` accepts. "Built on first use" means the sysroot comes from the input tree; "shipped" means the archive of that host already holds it (see [Installation](/docs/install/#sysroots)). | Platform | Architectures | C library | Notes | |---|---|---|---| | Linux, musl (static) | `x86_64`, `x32`, `i686`, `aarch64`, `aarch64_be`, `armv6`, `armv7`, `thumbv7`, `riscv64`, `riscv32`, `powerpc`, `powerpc64`, `powerpc64le`, `s390x`, `mips`, `mipsel`, `mips64`, `mips64el`, `loongarch64` | musl | built from source on first use; the host's own is shipped | | Linux, glibc | `x86_64`, `i686`, `aarch64`, `aarch64_be`, `armv7` (`gnueabihf`), `riscv64`, `riscv32`, `powerpc`, `powerpc64`, `powerpc64le`, `s390x`, `mips`, `mipsel`, `mips64`, `mips64el`, `loongarch64` | glibc 2.17 to 2.42 (`riscv32` from 2.33, `loongarch64` from 2.36) | stub libraries, headers and start files built from glibc's own release data; the host's own, at 2.31, is shipped | | Windows, MinGW | `x86_64`, `aarch64`, `i686`, `armv7` (`*-windows-gnu`) | mingw-w64 (UCRT) | built from source on first use | | FreeBSD | `x86_64`, `aarch64` (`*-unknown-freebsd`) | FreeBSD 14.4 base | built on first use | | NetBSD | `x86_64` (`x86_64-unknown-netbsd`) | NetBSD 10.1 base | built on first use | | WebAssembly | `wasm32-wasi` | wasi-libc | built from source on first use | | Windows, MSVC | `x86_64`, `aarch64`, `i686` (`*-windows-msvc`) | Microsoft CRT | [your SDK](#targets-that-need-your-sdk) | | macOS | `arm64`, `arm64e`, `x86_64` (`*-apple-macosx`) | Apple libSystem | [your SDK](#targets-that-need-your-sdk) | That is 48 targets (`arm64e` compiles but is not linkable). Any glibc version in range works, written `x86_64-linux-gnu.2.28` or `x86_64-linux-gnu-glibc2.28`. **Not available yet:** - glibc on `sparc64` (lld can't link its relocations) and on `x32` (clang can't compile glibc's x32 syscall macros); `x32` with musl works; - C++ on big-endian `powerpc64` with glibc: it links C, but libc++abi fails to link; - other FreeBSD and NetBSD versions, which come from trimmed base-system files. The new glibc architectures (PowerPC, s390x, MIPS, LoongArch, `aarch64_be`, `riscv32`) are tested by linking, not by running, because there is no target glibc to run them under emulation here. Every musl target runs its test programs under QEMU. `thumbv7` code is compiled as 32-bit Arm (A32), not Thumb. The toolchain's LLVM has 16 backends plus the experimental Xtensa (X86, AArch64, ARM, RISC-V, WebAssembly, PowerPC, SystemZ, MIPS, LoongArch, Sparc, AVR, MSP430, BPF, NVPTX, AMDGPU, SPIRV), so `kcc` can compile C and C++ for those targets with `--freestanding` or your own `--sysroot`. The 0.2.0 binaries carry only the first five. See [kairo](/docs/toolchain/kairo/) and [kcc](/docs/toolchain/kcc/) for the flags, and [kairo, kcc & Cross-compilation](/docs/language/c-cpp-toolchain/) for the toolchain model. --- ======================================================================== SECTION: EXAMPLES ======================================================================== ## Example: HTTP Server URL: https://www.kairolang.org/docs/examples/http-server/ # Example: HTTP Server This example builds a minimal HTTP server from scratch, demonstrating how Kairo's features compose in a real application. The server parses requests, routes them to handlers, and sends responses, all with type-safe error handling and automatic memory management via Tether. --- ## Project Structure ``` http-server/ http-server.k <- library entry request.k response.k router.k server.k main.k ``` --- ## Request Parsing `request.k` defines the HTTP request model and a parser that converts raw bytes into a typed request object. ```kairo // request.k pub enum Method { Get, Post, Put, Delete, Patch, Head, Options, } extend Method { static fn from_string(s: string) panic -> Method { match s { case "GET" { return .Get } case "POST" { return .Post } case "PUT" { return .Put } case "DELETE" { return .Delete } case "PATCH" { return .Patch } case "HEAD" { return .Head } case "OPTIONS" { return .Options } default { panic ParseError("unknown HTTP method", 0) } } } } pub struct Header { var name: string var value: string } pub class Request { pub var method: Method pub var path: string pub var headers: [Header] pub var body: string priv var query_params: {string: string} pub fn Request(self, method: Method, path: string) { self.method = method self.path = path self.headers = [] self.body = "" self.query_params = {} } pub fn get_header(const self, name: string) -> string? { for h in self.headers { if h.name == name { return h.value } } return null } pub fn content_length(const self) -> i32 { var cl? = self.get_header("Content-Length") if !cl? { return 0 } // no header, no body // std::parse panics on malformed input: a bad header also counts as no body return try std::parse(cl) catch => 0 } } pub class ParseError { pub var message: string pub var position: i32 pub fn ParseError(self, msg: string, pos: i32) { self.message = msg self.position = pos } fn op panic (const self) -> string { return f"{self.message} (line {self.position})" } } pub fn parse_request(raw: string) panic(ParseError) -> Request { var lines = raw.split("\r\n") if lines.length() == 0 { panic ParseError("empty request", 0) } // Parse request line: "GET /path HTTP/1.1" var parts = lines[0].split(" ") if parts.length() < 3 { panic ParseError("malformed request line", 0) } var method = Method::from_string(parts[0]) var path = parts[1] var req = Request(method, path) // Parse headers var i = 1 while i < lines.length() && lines[i].length() > 0 { var colon = lines[i].index_of(":") if colon < 0 { panic ParseError("malformed header", i) } req.headers.push(Header { name: lines[i].substring(0, colon).trim(), value: lines[i].substring(colon + 1).trim(), }) i += 1 } // Remaining lines are the body if i + 1 < lines.length() { req.body = lines[i + 1] } return req } ``` Key patterns: - `Method` is a plain enum with behavior added via `extend` - `Header` is a struct: plain data, no constructor needed - `Request` is a class with private state (`query_params`) and public accessors - `ParseError` is an error type. Any movable type can be one; it also defines the optional `op panic`, the message shown when the error is displayed - `parse_request` uses `panic` for error signaling; as a `pub` function it declares its set, `panic(ParseError)`, so callers know exactly what to handle - `get_header` returns `string?` for safe nullable access --- ## Response Building `response.k` defines the response model with a builder-style API. ```kairo // response.k pub enum StatusCode derives u16 { Ok = 200, Created = 201, NoContent = 204, BadRequest = 400, NotFound = 404, MethodNotAllowed = 405, InternalError = 500, } extend StatusCode { fn reason(const self) -> string { match self { case .Ok { return "OK" } case .Created { return "Created" } case .NoContent { return "No Content" } case .BadRequest { return "Bad Request" } case .NotFound { return "Not Found" } case .MethodNotAllowed { return "Method Not Allowed" } case .InternalError { return "Internal Server Error" } } } } pub class Response { pub var status: StatusCode priv var headers: {string: string} priv var body: string pub fn Response(self, status: StatusCode) { self.status = status self.headers = {} self.body = "" } pub fn header(self, name: string, value: string) -> Self { self.headers[name] = value return self } pub fn content_type(self, mime: string) -> Self { return self.header("Content-Type", mime) } pub fn text(self, content: string) -> Self { self.body = content return self.content_type("text/plain") } pub fn json(self, content: string) -> Self { self.body = content return self.content_type("application/json") } pub fn serialize(const self) -> string { var line = f"HTTP/1.1 {self.status as u16} {self.status.reason()}\r\n" for (name, value) in self.headers { line = line + f"{name}: {value}\r\n" } line = line + f"Content-Length: {self.body.length()}\r\n" line = line + "\r\n" line = line + self.body return line } pub static fn ok() -> Response { return Response(StatusCode::Ok) } pub static fn not_found() -> Response { return Response(StatusCode::NotFound) .text("404 Not Found") } pub static fn bad_request(msg: string) -> Response { return Response(StatusCode::BadRequest) .text(msg) } pub static fn internal_error() -> Response { return Response(StatusCode::InternalError) .text("Internal Server Error") } } ``` Key patterns: - `StatusCode` is an enum with an explicit `u16` underlying type - `Response` uses method chaining (each builder method returns `Self`) - Static factory methods (`Response::ok()`, `Response::not_found()`) for common responses - `serialize` is a `const` method: it does not modify the response --- ## Router `router.k` maps method + path combinations to handler functions. ```kairo // router.k pub class HandlerError { pub var message: string pub fn HandlerError(self, msg: string) { self.message = msg } fn op panic (const self) -> string { return self.message } } pub type Handler = fn(*Request) panic(HandlerError) -> Response struct Route { var method: Method var path: string var handler: Handler } pub class Router { priv var routes: [Route] priv var not_found_handler: Handler pub fn Router(self) { self.routes = [] self.not_found_handler = fn (req: *Request) -> Response { return Response::not_found() } } pub fn get(self, path: string, handler: Handler) -> Self { self.routes.push(Route { method: .Get, path: path, handler: handler }) return self } pub fn post(self, path: string, handler: Handler) -> Self { self.routes.push(Route { method: .Post, path: path, handler: handler }) return self } pub fn put(self, path: string, handler: Handler) -> Self { self.routes.push(Route { method: .Put, path: path, handler: handler }) return self } pub fn del(self, path: string, handler: Handler) -> Self { self.routes.push(Route { method: .Delete, path: path, handler: handler }) return self } pub fn fallback(self, handler: Handler) -> Self { self.not_found_handler = handler return self } pub fn resolve(const self, req: *Request) -> Handler { for route in self.routes { if route.method == req->method && route.path == req->path { return route.handler } } return self.not_found_handler } } ``` Key patterns: - `Handler` is a type alias for a function pointer that takes a request and may panic with a `HandlerError`; a function type must declare its panic set - A handler that never panics (like the default not-found closure) converts to `Handler` as it is - `Route` is a struct: plain data with aggregate init - `Router` uses method chaining for registration - `resolve` is `const`: routing does not mutate the router --- ## Server `server.k` ties everything together with a TCP accept loop. It uses C++ interop for socket operations. ```kairo // server.k pub class BindError { pub var port: i32 pub fn BindError(self, port: i32) { self.port = port } fn op panic (const self) -> string { return f"failed to bind to port {self.port}" } } ffi "c++" import "socket_api.hh" as net pub class Server { priv var router: Router priv var port: i32 priv var running: bool pub fn Server(self, port: i32) { self.router = Router() self.port = port self.running = false } pub fn routes(self) -> *Router { return &self.router } pub fn start(self) panic(BindError) { var listener = net::tcp_listen(self.port) if listener < 0 { panic BindError(self.port) } finally { net::tcp_close(listener) } std::io::println(f"listening on :{self.port}") self.running = true while self.running { var client = net::tcp_accept(listener) if client < 0 { continue } self.handle_client(client) } } pub fn stop(self) { self.running = false } priv fn handle_client(self, fd: i32) { finally { net::tcp_close(fd) } var raw = net::tcp_read(fd, 8192) var response = try ({ var req = parse_request(raw) var handler = self.router.resolve(&req) (try handler(&req) catch => Response::internal_error()) }) catch e: ParseError => Response::bad_request(e.message) net::tcp_write(fd, response.serialize()) } } ``` Key patterns: - `ffi "c++" import` brings in socket operations; no unsafe block is needed because `tcp_listen`, `tcp_accept`, etc. take and return value types (`i32`, `string`), not raw pointers - `finally` blocks ensure sockets are closed on all exit paths (normal, panic, early return) - `try`/`catch` is used in expression form to produce a `Response` on both success and failure - Nested `try`/`catch`: the outer one handles parse errors, the inner one handles handler panics. The outer `try` needs no catch-all: `ParseError` is the only error left in its body, and an arm for a type the body can't panic with would only draw a warning - `handle_client` is `priv` (an internal implementation detail) --- ## Putting It Together `main.k` wires up routes and starts the server. ```kairo // main.k fn handle_index(req: *Request) -> Response { return Response::ok() .json("{\"status\": \"running\"}") } fn handle_health(req: *Request) -> Response { return Response::ok() .text("ok") } fn handle_echo(req: *Request) -> Response { if req->method != .Post { return Response(StatusCode::MethodNotAllowed) .text("POST only") } return Response::ok() .content_type("text/plain") .text(req->body) } fn main() { var srv = Server(8080) var *r = srv.routes() r->get("/", handle_index) r->get("/health", handle_health) r->post("/echo", handle_echo) r->fallback(fn (req: *Request) -> Response { return Response::not_found() }) try { srv.start() } catch e: BindError { std::io::println(f"server error: cannot bind to port {e.port}") } } ``` Key patterns: - Handlers are plain functions passed as function pointers; none of these panic, so each converts to `Handler` (a function that doesn't panic converts to any panicking function type) - The fallback handler is an inline closure - `main` handles every panic from `srv.start()`: `main` can never panic, so an error left unhandled there would be a compile error --- ## Building and Running ```sh kairo main.k -o server ./server ``` ``` listening on :8080 ``` ```sh curl http://localhost:8080/ # {"status": "running"} curl http://localhost:8080/health # ok curl -X POST -d "hello" http://localhost:8080/echo # hello curl http://localhost:8080/nonexistent # 404 Not Found ``` --- ## Features Used | Feature | Where | |---|---| | [Classes](/docs/language/classes/) | `Request`, `Response`, `Server`, `Router` | | [Structs](/docs/language/structures/) | `Header`, `Route` | | [Enums](/docs/language/enums/) | `Method`, `StatusCode` | | [Extends](/docs/language/extends/) | `Method::from_string`, `StatusCode::reason` | | [Interfaces](/docs/language/interfaces/) | `Handler` type alias for function pointers | | [Panic](/docs/language/panic/) | Error handling throughout | | [Try/Catch](/docs/language/pattern-matching/) | Request parsing, handler execution | | [Finally](/docs/language/control-flow/#finally) | Socket cleanup | | [Closures](/docs/language/closures/) | Fallback handler | | [Nullable types](/docs/language/nullables/#nullable-types) | `get_header` returns `string?` | | [Null checking](/docs/language/nullables/#null-checking) | `content_length` tests `cl?` before parsing it | | [Type aliases](/docs/language/type-aliases/) | `Handler` type | | [C++ interop](/docs/language/c-cpp/) | Socket API via `ffi "c++"` | | [Match](/docs/language/pattern-matching/) | Method parsing, status code reasons | | [Modules](/docs/language/modules/) | File-per-module structure | | [Const methods](/docs/language/classes/#const-methods) | `serialize`, `resolve`, `get_header` | | [Method chaining](/docs/language/classes/#self-and-self) | Response builder, router registration | --- ======================================================================== SECTION: LIBRARY ======================================================================== ## Containers URL: https://www.kairolang.org/docs/library/core/containers/ Vector, HashMap, HashSet, slices and the Hash interface. ## Contents | Name | Summary | | --- | --- | | [`Hash`](#hash) | The requirements for a `{K: V}` / `{T}` key: a hash and an equality consistent with it. | | [`fold_mul`](#fold_mul) | The 128-bit product of a and b, its high and low halves xored: the folded multiply every mix below is made of. | | [`to_usize`](#to_usize) | A 64-bit hash as a usize: itself on a 64-bit target, folded on a 32-bit one. | | [`mix64`](#mix64) | The integer mix: a full-avalanche hash of 64 bits. | | [`hash_bytes`](#hash_bytes) | rapidhash (v1) of the `len` bytes at p. | | [`hash_bytes_seeded`](#hash_bytes_seeded) | rapidhash (v1) of the `len` bytes at p, seeded with `seed`. | | [Hash implementations for primitives](#hash-implementations-for-primitives) | How each primitive type implements the interface. | | [`extend string impl Hash`](#extend-string-impl-hash) | A `string` hashes its bytes with `hash_bytes` (rapidhash v1). | | [`HASH_NPOS`](#hash_npos) | The "not found" result of an entry-index lookup. | | [`HASH_MIN_CAP`](#hash_min_cap) | The smallest entry capacity a table is created with (8). | | [`tag_of`](#tag_of) | Returns the slot tag of hash `h`: the high 32 bits of `h * 0x9e3779b97f4a7c15` (Fibonacci hashing). | | [`slot_word`](#slot_word) | Packs tag `t` and entry index `e` into a slot word (tag in the high 32 bits, index + 1 in the low). | | [`slot_entry`](#slot_entry) | Returns the entry index a non-empty slot word names (the low half minus 1). | | [`slot_tag`](#slot_tag) | Returns the tag stored in a slot word. | | [`shift_for`](#shift_for) | Returns the shift that maps a tag to its home slot in a table of `nslots` slots (a power of two): `32 - log2(nslots)`. | | [`block_bytes`](#block_bytes) | Returns the byte size of a table block: `2 * cap` 8-byte slots followed by `cap` entries of `esize` bytes. | | [`block_align`](#block_align) | Returns the alignment of a table block: 8, or `ealign` when the entries need more. | | [`block_alloc`](#block_alloc) | Allocates a table block for `cap` entries of `esize` bytes from the allocator in effect, with the slots zeroed and the entries uninitialized. | | [`block_free`](#block_free) | Frees a block from `block_alloc`; a no-op when `cap` is 0 (the empty block is not allocated). | | [`block_empty`](#block_empty) | Returns the block of an empty table: no allocation, but a non-null pointer aligned for the entries. | | [`block_slots`](#block_slots) | Returns the slot array of a block (its first `2 * cap` words). | | [`block_entries`](#block_entries) | Returns the entry array of a block: the bytes after its `2 * cap` slots. | | [`empty_slot`](#empty_slot) | Returns the first empty slot on the probe sequence for tag `t` (linear probing from the home slot). | | [`rebuild`](#rebuild) | Re-places every occupied slot of `old` (`old_n` slots) into the zeroed table `slots`, using the new `mask` and `shift`. | | [`slot_of_entry`](#slot_of_entry) | Returns the index of the slot that holds entry `e` (whose tag is `t`). | | [`remove_slot`](#remove_slot) | Empties slot `i` and closes the gap by backward-shifting later slots of the cluster (no tombstones are ever left). | | [`shift_down_after`](#shift_down_after) | After the entries above index `e` moved down by one (an order-preserving erase), decrements every slot that names an index greater than `e`. | | [`grown_cap`](#grown_cap) | Returns the entry capacity to grow to from `cap` so that `want` entries fit: 8 from empty, otherwise doubled until `want` fits. | | [`relocate_entry`](#relocate_entry) | Moves the entry at `src` to the uninitialized `dst`, leaving `src`'s storage uninitialized: a byte copy when E is trivially relocatable, else a copy-construct plus destroy. | | [`MapEntry`](#mapentry) | One key and its value, as a HashMap stores and iterates them (`m.find(k)`, `m.begin()`, `m.entries()`). | | [`HashMap`](#hashmap) | Hash map from `K` to `V`. | | [`HashSet`](#hashset) | Hash set of `T`. `{T}` desugars to `HashSet`, and `{a, b, ...}` builds one. | | [`Slice`](#slice) | A non-owning view over `len` contiguous elements. | | [`Vector`](#vector) | Growable, owning, contiguous array. | ## `Hash` ```kairo interface Hash ``` The requirements for a `{K: V}` / `{T}` key: a hash and an equality consistent with it. If `a == b` then `a.hash() == b.hash()`. Hashes are deterministic: no per-process seed, so a map's layout is the same on every run. The primitives, pointers and `string` conform out of the box; a key type conforms like any type conforms to an interface (its own members, an `extend X impl Hash`, or structurally). `other` is `const`, so comparing two keys copies neither. ### `Hash.hash` ```kairo fn hash(const self) -> usize ``` Returns the key's hash, to be folded into a table slot by the container. ### `Hash.op ==` ```kairo fn op ==(const self, const other: Self) -> bool ``` Returns true when the keys are equal; must agree with `hash`. ## `fold_mul` ```kairo inline fn fold_mul(a: u64, b: u64) -> u64 ``` The 128-bit product of a and b, its high and low halves xored: the folded multiply every mix below is made of. One `mul` where the target has a 64x64->128 multiply; four 32x32 products elsewhere. ## `to_usize` ```kairo inline fn to_usize(h: u64) -> usize ``` A 64-bit hash as a usize: itself on a 64-bit target, folded on a 32-bit one. ## `mix64` ```kairo inline fn mix64(x: u64) -> u64 ``` The integer mix: a full-avalanche hash of 64 bits. ## `hash_bytes` ```kairo inline fn hash_bytes(p: unsafe *const u8, len: usize) -> u64 ``` rapidhash (v1) of the `len` bytes at p. ## `hash_bytes_seeded` ```kairo fn hash_bytes_seeded(p: unsafe *const u8, len: usize, seed: u64) -> u64 ``` rapidhash (v1) of the `len` bytes at p, seeded with `seed`. (No default argument: a defaulted call goes through an out-of-line thunk.) ## Hash implementations for primitives Each primitive type implements `Hash` as follows. | Type | How it hashes | | --- | --- | | `bool` | `true` and `false` hash as 1 and 0 through `mix64`. | | `u8` | Unsigned integers (and `char`) hash through `mix64` of their value. | | `u16` | Unsigned integers (and `char`) hash through `mix64` of their value. | | `u32` | Unsigned integers (and `char`) hash through `mix64` of their value. | | `u64` | Unsigned integers (and `char`) hash through `mix64` of their value. | | `i8` | Signed integers hash through `mix64` of their value sign-extended to 64 bits. | | `i16` | Signed integers hash through `mix64` of their value sign-extended to 64 bits. | | `i32` | Signed integers hash through `mix64` of their value sign-extended to 64 bits. | | `i64` | Signed integers hash through `mix64` of their value sign-extended to 64 bits. | | `usize` | Pointer-sized integers hash through `mix64` of their value widened to 64 bits. | | `isize` | Pointer-sized integers hash through `mix64` of their value widened to 64 bits. | | `char` | A `char` hashes through `mix64` of its value. | | `u128` | A 128-bit integer hashes as `fold_mul` of its two 64-bit halves. | | `i128` | A 128-bit integer hashes as `fold_mul` of its two 64-bit halves. | | `f32` | A float hashes through `mix64` of its bit pattern, with `+0.0` and `-0.0` hashing alike. A NaN compares unequal to everything, itself included, so a NaN key can be inserted but never found again. Do not key a map by a float that may be NaN. | | `f64` | A float hashes through `mix64` of its bit pattern, with `+0.0` and `-0.0` hashing alike. A NaN key can be inserted but never found again; see the `f32` conformance. | ## `extend string impl Hash` ```kairo extend string impl Hash ``` A `string` hashes its bytes with `hash_bytes` (rapidhash v1). ### `string.hash` ```kairo inline fn hash(const self) -> usize ``` Returns the key's hash, to be folded into a table slot by the container. ## `HASH_NPOS` ```kairo eval HASH_NPOS: usize ``` The "not found" result of an entry-index lookup. Never a valid entry index. ## `HASH_MIN_CAP` ```kairo eval HASH_MIN_CAP: usize ``` The smallest entry capacity a table is created with (8). ## `tag_of` ```kairo inline fn tag_of(h: usize) -> u32 ``` Returns the slot tag of hash `h`: the high 32 bits of `h * 0x9e3779b97f4a7c15` (Fibonacci hashing). Mixing makes the table robust against weak `hash()` implementations. ## `slot_word` ```kairo inline fn slot_word(t: u32, e: usize) -> u64 ``` Packs tag `t` and entry index `e` into a slot word (tag in the high 32 bits, index + 1 in the low). ## `slot_entry` ```kairo inline fn slot_entry(s: u64) -> usize ``` Returns the entry index a non-empty slot word names (the low half minus 1). ## `slot_tag` ```kairo inline fn slot_tag(s: u64) -> u32 ``` Returns the tag stored in a slot word. ## `shift_for` ```kairo inline fn shift_for(nslots: usize) -> u32 ``` Returns the shift that maps a tag to its home slot in a table of `nslots` slots (a power of two): `32 - log2(nslots)`. ## `block_bytes` ```kairo inline fn block_bytes(cap: usize, esize: usize) -> usize ``` Returns the byte size of a table block: `2 * cap` 8-byte slots followed by `cap` entries of `esize` bytes. **Panics** when the size overflows (traps). ## `block_align` ```kairo inline fn block_align(ealign: usize) -> usize ``` Returns the alignment of a table block: 8, or `ealign` when the entries need more. ## `block_alloc` ```kairo fn block_alloc(cap: usize, esize: usize, ealign: usize) -> unsafe *u8 ``` Allocates a table block for `cap` entries of `esize` bytes from the allocator in effect, with the slots zeroed and the entries uninitialized. Runs the OOM hook on failure. ## `block_free` ```kairo inline fn block_free(b: unsafe *u8, cap: usize, esize: usize, ealign: usize) ``` Frees a block from `block_alloc`; a no-op when `cap` is 0 (the empty block is not allocated). ## `block_empty` ```kairo inline fn block_empty(ealign: usize) -> unsafe *u8 ``` Returns the block of an empty table: no allocation, but a non-null pointer aligned for the entries. ## `block_slots` ```kairo inline fn block_slots(b: unsafe *u8) -> unsafe *u64 ``` Returns the slot array of a block (its first `2 * cap` words). ## `block_entries` ```kairo inline fn block_entries(b: unsafe *u8, cap: usize) -> unsafe *u8 ``` Returns the entry array of a block: the bytes after its `2 * cap` slots. ## `empty_slot` ```kairo inline fn empty_slot(slots: unsafe *u64, mask: usize, shift: u32, t: u32) -> usize ``` Returns the first empty slot on the probe sequence for tag `t` (linear probing from the home slot). The table is never full, so this terminates. ## `rebuild` ```kairo fn rebuild(slots: unsafe *u64, mask: usize, shift: u32, old: unsafe *u64, old_n: usize) ``` Re-places every occupied slot of `old` (`old_n` slots) into the zeroed table `slots`, using the new `mask` and `shift`. Entry indices are unchanged and no key is rehashed. ## `slot_of_entry` ```kairo inline fn slot_of_entry(slots: unsafe *u64, mask: usize, shift: u32, t: u32, e: usize) -> usize ``` Returns the index of the slot that holds entry `e` (whose tag is `t`). The slot must exist. ## `remove_slot` ```kairo fn remove_slot(slots: unsafe *u64, mask: usize, shift: u32, i: usize) ``` Empties slot `i` and closes the gap by backward-shifting later slots of the cluster (no tombstones are ever left). ## `shift_down_after` ```kairo fn shift_down_after(slots: unsafe *u64, nslots: usize, e: usize) ``` After the entries above index `e` moved down by one (an order-preserving erase), decrements every slot that names an index greater than `e`. O(nslots). ## `grown_cap` ```kairo inline fn grown_cap(cap: usize, want: usize) -> usize ``` Returns the entry capacity to grow to from `cap` so that `want` entries fit: 8 from empty, otherwise doubled until `want` fits. **Panics** when the result would exceed 2^31 entries (traps): slots hold 32-bit indices. ## `relocate_entry` ```kairo inline fn relocate_entry(dst: unsafe *u8, src: unsafe *E) ``` Moves the entry at `src` to the uninitialized `dst`, leaving `src`'s storage uninitialized: a byte copy when E is trivially relocatable, else a copy-construct plus destroy. ## `MapEntry` ```kairo class MapEntry ``` One key and its value, as a HashMap stores and iterates them (`m.find(k)`, `m.begin()`, `m.entries()`). No constructor: it is a C++ aggregate built in place as `MapEntry(k, v)` or `MapEntry(k)`. ### `MapEntry.key` ```kairo var key: K ``` The entry's key. Do not change it through a pointer from the map: the index is keyed on it. ### `MapEntry.value` ```kairo var value: V ``` The entry's value. May be assigned through a pointer from `find` / `begin` / `entries`. ## `HashMap` ```kairo class HashMap ``` Hash map from `K` to `V`. `{K: V}` desugars to `HashMap`, and `{k: v, ...}` builds one. Entries are stored densely in insertion order, so iteration order is deterministic. Lookup, insert and `erase` are O(1) expected; `erase_ordered` is O(n). K must implement `Hash` (a `hash()` method and `==`). Inserting or erasing invalidates every pointer from `find` / `get` / `begin` / `[]` and must not happen during `for ... in m`. A copy is a deep copy. **Example** ```kairo var m: {i32: i32} = {} m[1] = 10 m.insert(2, 20) var found = false if let v = m.get(2) { found = (*v == 20) } ``` **See also** HashSet ### `HashMap.HashMap` ```kairo inline fn HashMap(self) ``` Creates an empty map. Allocates nothing. ### `HashMap.HashMap` ```kairo fn HashMap(self, const items: [(K, V);]) ``` Creates a map from `(key, value)` pairs, as `{k: v, ...}` lowers to. Entries keep written order; a repeated key keeps its first place and takes its last value. V must be default-constructible (each value is assigned after the entry is created). ## `HashSet` ```kairo class HashSet ``` Hash set of `T`. `{T}` desugars to `HashSet`, and `{a, b, ...}` builds one. Elements are stored densely in insertion order, so iteration order is deterministic. `insert`, `contains` and `erase` are O(1) expected. T must implement `Hash`. The mutation and invalidation rules are HashMap's: do not insert or erase during iteration. **Example** ```kairo var s: {i32} = {1, 2, 3} s.insert(2) var n = s.size() ``` **See also** HashMap ### `HashSet.HashSet` ```kairo inline fn HashSet(self) ``` Creates an empty set. Allocates nothing. ### `HashSet.HashSet` ```kairo fn HashSet(self, const items: [T;]) ``` Creates a set from `items`, as `{a, b, ...}` lowers to. Elements keep written order; a repeated element keeps its first place. ## `Slice` ```kairo struct Slice ``` A non-owning view over `len` contiguous elements. `[T;]` is `Slice`, and a `[...]` literal takes this type against a `[T;]` target. A `[T]` converts to it implicitly, with nothing copied. The view does not keep its elements alive and does not own them; it is a pointer and a length. **See also** Vector ### `Slice.op []` ```kairo inline fn op [] (const self, i: usize) -> *T ``` Returns the element at index `i` as a place, so `s[i] = x` assigns through the view. **Notes** This operator does no bounds check of its own (it indexes the pointer); `Vector`'s `[]` does. ### `Slice.op []` ```kairo inline fn op [] (const self, r: Range) -> [T;] ``` Returns the sub-view `s[a..b]` or `s[a..=b]`. A view: nothing is copied. O(1). **Panics** when `a > b` or the end is past `len` (traps; for `a..=b`, `b >= len`). ### `Slice.op []` ```kairo inline fn op [] (const self, r: RangeFrom) -> [T;] ``` Returns the sub-view `s[a..]`; `s[..]` is the whole view. O(1). **Panics** when `a > len` (traps). ### `Slice.op []` ```kairo inline fn op [] (const self, r: RangeTo) -> [T;] ``` Returns the sub-view `s[..b]` or `s[..=b]`. O(1). **Panics** when the end is past `len` (traps; for `..=b`, `b >= len`). ## `Vector` ```kairo class Vector ``` Growable, owning, contiguous array. `[T]` desugars to `Vector`, and the list literal `[a, b, c]` against a `[T]` target builds one. Elements live in one heap block from the allocator in effect. Indexing, `front`, `back` and `pop_back` check bounds and trap (see \panics on each); growth is geometric (twice the capacity, at least 4), so `push_back` is O(1) amortized. A copy is a deep copy; a `[MoveOnly]` has no copy and no `Vector(n)` / `resize(n, value)` (those members need T to be copyable / default-constructible). References and pointers into a vector (`v[i]`, `begin()`, `data()`) are invalidated by any operation that grows, inserts, erases or clears. **Example** ```kairo var v: [i32] = [1, 2, 3] v.push(4) var sum: i32 = 0 for x in v { sum += x } ``` **See also** Slice ### `Vector.Vector` ```kairo inline fn Vector(self) ``` Empty, no storage. Creates an empty vector. Allocates nothing; `capacity()` is 0. ### `Vector.Vector` ```kairo fn Vector(self, const items: [T;]) requires __builtin_is_constructible() ``` Creates a vector holding a copy of every element of `items`. This is what `[a, b, c]` lowers to against a `[T]` target, and what `s as [T]` calls. O(n). ### `Vector.Vector` ```kairo fn Vector(self, n: usize) requires __builtin_is_default_constructible() ``` Creates a vector of `n` default-constructed elements, with capacity exactly `n`. O(n). Only available when T is default-constructible. ### `Vector.op []` ```kairo inline fn op [] (self, i: usize) -> *T ``` Returns the element at index `i` as a place, so `v[i] = x` assigns. **Panics** when `i >= size()` (traps; no message). ### `Vector.op []` ```kairo inline fn op [] (const self, i: usize) -> *const T ``` Returns the element at index `i` through a const vector. **Panics** when `i >= size()` (traps; no message). ### `Vector.size` ```kairo inline fn size(const self) -> usize ``` Returns the number of live elements. O(1). ### `Vector.empty` ```kairo inline fn empty(const self) -> bool ``` Returns true when the vector holds no elements. O(1). ### `Vector.capacity` ```kairo inline fn capacity(const self) -> usize ``` Returns how many elements fit before the next reallocation. O(1). ### `Vector.data` ```kairo inline fn data(const self) -> *T ``` Returns a pointer to the first element (never null: a dangling, aligned pointer while the vector has no storage). One accessor for const and mutable receivers alike: it returns a mutable `*T` even from a `const self`. ### `Vector.begin` ```kairo inline fn begin(const self) -> *T ``` Returns a pointer to the first element; equal to `end()` when empty. Together with `end()` this is the pointer pair `insert` / `erase` positions are spelled in. ### `Vector.end` ```kairo inline fn end(const self) -> *T ``` Returns a pointer one past the last element. Not dereferenceable. ### `Vector.front` ```kairo inline fn front(const self) -> *T ``` Returns a pointer to the first element. **Panics** when the vector is empty (traps). ### `Vector.back` ```kairo inline fn back(const self) -> *T ``` Returns a pointer to the last element. **Panics** when the vector is empty (traps). ### `Vector.op in` ```kairo fn op in (const self) -> yield T ``` Iterates the elements in order: `for x in v` / `for *x in v`. `for x in v` binds each element as a value; `for *x in v` binds a pointer to the element itself, so it can be modified. Do not grow or erase while iterating. A write to `x` in a `for x in v` body that nothing reads afterwards changes only the copy, and is warned (SC275W) with a fix-it that writes `for *x in v`. ### `Vector.push_back` ```kairo inline fn push_back(self, v: T) ``` Appends `v` to the end. O(1) amortized; reallocates when full. `v` is taken by value, so it stays valid across the growth (`v.push_back(v[0])` is fine). A copyable lvalue is copied, a MOVE value is moved. ### `Vector.push` ```kairo inline fn push(self, v: T) ``` push\_back under the name collections.mdx documents. Appends `v` to the end; the name `collections` documents for `push_back`. Same cost. ### `Vector.emplace_back` ```kairo inline fn <...A> emplace_back(self, ...args: A) -> *T ``` Appends a T constructed in place from `args` and returns a pointer to it. O(1) amortized. On growth the new element is built in the new block before the old ones move, so an argument that refers into this vector is still valid when read. ### `Vector.insert` ```kairo fn insert(self, pos: *T, v: T) -> *T ``` Inserts `v` before `pos` and returns a pointer to the new element. O(n): later elements shift up one slot. **Parameters** - `pos`: a pointer in `[begin(), end()]`; `end()` appends. **Panics** when `pos` is outside that range (traps). ### `Vector.pop_back` ```kairo inline fn pop_back(self) ``` Destroys the last element. O(1). **Panics** when the vector is empty (traps). ### `Vector.clear` ```kairo inline fn clear(self) ``` Destroys every element and sets the size to 0. Keeps the storage. O(n), O(1) for trivial T. ### `Vector.erase` ```kairo fn erase(self, pos: *T) -> *T ``` Removes the element at `pos` and returns a pointer to the element that followed it (now at `pos`). O(n): later elements shift down one slot. **Panics** when `pos` is not in `[begin(), end())` (traps). ### `Vector.erase` ```kairo fn erase(self, first: *T, last: *T) -> *T ``` Removes the elements in `[first, last)` and returns a pointer to the element that followed them. O(n). An empty range removes nothing. **Panics** when `first > last` or `last > end()` (traps). ### `Vector.reserve` ```kairo inline fn reserve(self, n: usize) ``` Ensures capacity for at least `n` elements. Never shrinks. O(size()) when it reallocates. ### `Vector.resize` ```kairo fn resize(self, n: usize) requires __builtin_is_default_constructible() ``` Resizes to `n` elements: destroys the tail, or appends default-constructed elements. Only available when T is default-constructible. O(|n - size()|). ### `Vector.resize` ```kairo fn resize(self, n: usize, const value: T) requires __builtin_is_constructible() ``` Resizes to `n` elements: destroys the tail, or appends copies of `value`. `value` may be an element of this vector. Only available when T is copyable. --- ## Coroutines URL: https://www.kairolang.org/docs/library/core/coroutines/ Generators, futures and suspension. ## Contents | Name | Summary | | --- | --- | | [`Future`](#future) | The result type of `spawn f()`: a handle to a value of type `T` that is still being computed. | | [`YieldPromise`](#yieldpromise) | The coroutine promise behind a generator: C++ coroutine plumbing for `Yield`. | | [`Yield`](#yield) | The handle a generator function returns: the `Yield` lang item, the target of `yield`. | | [`Suspend`](#suspend) | The awaiter every suspension point uses: it always suspends and does nothing on suspend or resume. | ## `Future` ```kairo struct Future ``` The result type of `spawn f()`: a handle to a value of type `T` that is still being computed. Layout only for now: `state` points at the task's shared state. ## `YieldPromise` ```kairo class YieldPromise ``` The coroutine promise behind a generator: C++ coroutine plumbing for `Yield`. `yield v` is lowered to `yield_value`, which records the address of `v` in `cur`. The compiler and clang's coroutine machinery call the other members; user code does not. ### `YieldPromise.cur` ```kairo var cur: *T ``` The address of the most recently yielded value; valid until the generator resumes. ### `YieldPromise.get_return_object` ```kairo inline fn get_return_object(self) -> Yield ``` Builds the `Yield` handle for this coroutine's frame. ### `YieldPromise.initial_suspend` ```kairo inline fn initial_suspend(self) -> Suspend ``` Suspends at the start, so nothing runs until the first `next()`. ### `YieldPromise.yield_value` ```kairo inline fn yield_value(self, @inout v: T) -> Suspend ``` Handles `yield v`: records the address of `v` and suspends. **Parameters** - `v`: Taken `@inout`: the reader sees the generator's own value, not a copy. ### `YieldPromise.return_void` ```kairo inline fn return_void(self) ``` Handles falling off the end of the generator body. ### `YieldPromise.unhandled_exception` ```kairo inline fn unhandled_exception(self) ``` Traps (`__builtin_trap`): generators do not propagate exceptions. ## `Yield` ```kairo class Yield ``` The handle a generator function returns: the `Yield` lang item, the target of `yield`. A function containing `yield` returns one; a `for` loop over it drives `next()` and reads `current()`. Move-only; destroying the handle destroys the coroutine frame. **See also** YieldPromise ### `Yield.promise_type` ```kairo type promise_type = YieldPromise ``` The promise type clang's coroutine machinery looks up. ### `Yield.Yield` ```kairo inline fn Yield(self, f: unsafe *void) ``` Wraps a coroutine frame; called by `YieldPromise::get_return_object`. ## `Suspend` ```kairo class Suspend ``` The awaiter every suspension point uses: it always suspends and does nothing on suspend or resume. clang requires the awaiter of `final_suspend` to be non-throwing in all three calls, so all three are marked `@no_unwind`. --- ## Errors and panics URL: https://www.kairolang.org/docs/library/core/errors-panics/ Panic results, crash and assertion support. ## Contents | Name | Summary | | --- | --- | | [`AssertFail`](#assertfail) | The `assert` failure record: PanicLowering's entry point for a failed `assert`. | | [`unwrap_failed`](#unwrap_failed) | Crashes with a compiler-built message; the `UnwrapFailed` lang item. | | [`crash_with`](#crash_with) | Writes `msg` and a newline to stderr (nothing when `msg` is empty), then aborts. | | [`PanicCatch`](#paniccatch) | PanicLowering's catch entry point (the `PanicCatch` lang item). | | [`PanicRaise`](#panicraise) | PanicLowering's raise entry point (the `PanicRaise` lang item). | | [`Panic`](#panic) | What a `panic` function returns (PANIC.md §1.1): `Ok` with the declared return type, else one `Err` per type in the function's panic set. | ## `AssertFail` ```kairo struct AssertFail ``` The `assert` failure record: PanicLowering's entry point for a failed `assert`. Compiler-facing lang item; user code does not name it. The file is `assert_fail.k` because `assert` is a keyword. ## `unwrap_failed` ```kairo fn unwrap_failed(msg: *const u8, len: usize) -> ! ``` Crashes with a compiler-built message; the `UnwrapFailed` lang item. Called for `unwrap!` on null, a checked `as` into a closed enum that misses, a script global read before its line ran, and an asserting downcast `p as *D` on the wrong dynamic type. `msg[0..len)` is a literal the lowering built whole (the expression as written and its file:line:col), so nothing is formatted at crash time. The runtime writes it and a newline to stderr and aborts. `-> !` makes the failing arm `Never`. Not a panic: no `try` catches it and it is in no panic set. **Parameters** - `msg`: Pointer to `len` bytes of message. **Safety** `msg` must be valid for reads of `len` bytes (a null `msg` is an empty message). ## `crash_with` ```kairo fn crash_with(msg: string = "") -> ! ``` Writes `msg` and a newline to stderr (nothing when `msg` is empty), then aborts. This is what `crash!` calls. A runtime `string` is fine: its data pointer and length are read once and handed to the runtime, which writes at most `KAIRO_RT_CRASH_MAX` (4096) bytes of them and runs no `string` method. A literal costs no allocation. `-> !`, so a call ends its path for the flow checks. Not a panic. **See also** crash! ## `PanicCatch` ```kairo struct PanicCatch ``` PanicLowering's catch entry point (the `PanicCatch` lang item). Compiler-facing; user code does not name it. Layout only: `payload` is an opaque pointer. ## `PanicRaise` ```kairo struct PanicRaise ``` PanicLowering's raise entry point (the `PanicRaise` lang item). Compiler-facing; user code does not name it. Layout only: `payload` is an opaque pointer. ## `Panic` ```kairo enum Panic ``` What a `panic` function returns (PANIC.md §1.1): `Ok` with the declared return type, else one `Err` per type in the function's panic set. The compiler forms every instance (the set is deduplicated and sorted by type id) and lays it out itself: each tag is a type id, word 0 holds the tag and the panic site, and the payloads start at `max(8, alignof(...))`. User code does not name it (SC116E). ### `Panic.Ok` ```kairo Ok ``` The function returned normally; `value` is its declared return value. ### `Panic.Err` ```kairo Err ``` The function panicked with an error of one of the types in its panic set; one `Err` case exists per type in `E`. --- ## Formatting URL: https://www.kairolang.org/docs/library/core/formatting/ The f-string lowering target and formatting buffers. ## `FmtBuf` ```kairo class FmtBuf ``` The buffer an f-string is built in. FStringLowering turns `f"a {x} b"` into one FmtBuf and a call per part (`text`, `put_*`), then `finish()`; users can also keep one to format into repeatedly. Up to 127 bytes live inside the object; longer text spills to the heap (from the allocator in effect, the same one `string` uses). Not copyable or movable: `data` points into the object. Every `put_*` takes a `spec`, a packed u64 format spec (width, precision, fill, alignment, base, flags; layout in the file header). `0` means defaults. **Example** ```kairo var b = FmtBuf() b.write(f"x = {42}") var s = b.view() ``` ### `FmtBuf.data` ```kairo var data: *u8 ``` Pointer to the bytes: the inline storage until the first spill, then the heap block. Null after `finish()`. ### `FmtBuf.len` ```kairo var len: usize ``` Bytes written so far. ### `FmtBuf.cp_len` ```kairo var cp_len: usize ``` Codepoints written so far (what the finished string's `codepoints()` reports). ### `FmtBuf.cap` ```kairo var cap: usize ``` Usable bytes before the next growth; the block has `cap + 1` bytes for the NUL. ### `FmtBuf.FmtBuf` ```kairo fn FmtBuf(self, cap: usize) ``` Creates a buffer bounded to `cap` bytes, as the lowering does with a compile-time bound. Below 128 it uses the inline storage (growing to the heap only if the text outgrows it); from 128 up the heap block is allocated now, sized once. ### `FmtBuf.FmtBuf` ```kairo fn FmtBuf(self) ``` Creates an empty buffer on its inline storage, for formatting repeatedly (`var b = FmtBuf()`). ### `FmtBuf.reserve` ```kairo inline fn reserve(self, n: usize) ``` Room for `n` more bytes, so the puts that follow never grow. Ensures room for `n` more bytes, so the puts that follow do not grow. ### `FmtBuf.write` ```kairo inline fn write(self, const s: string) ``` Appends `s` as `{s}` would. `b.write(f"...")` never calls this: the lowering writes the f-string's parts straight onto `b`. ### `FmtBuf.text` ```kairo inline fn text(self, p: *const u8, n: usize, cp: usize) ``` Appends `n` literal bytes at `p` that encode `cp` codepoints. Both counts are trusted, not checked (constants at every lowered call site). ### `FmtBuf.put_str` ```kairo inline fn put_str(self, const s: string, spec: u64) ``` Appends a string hole. With `spec == 0` the string is copied as is; otherwise precision truncates to that many codepoints, `?` quotes and escapes, and width/fill/alignment pad (default left-aligned). **Notes** With `?`, width and alignment are not applied (the quoted text is written unpadded). ### `FmtBuf.put_bool` ```kairo inline fn put_bool(self, v: bool, spec: u64) ``` Appends `true` or `false`, padded per `spec` (default left-aligned). ### `FmtBuf.put_char` ```kairo fn put_char(self, c: char, spec: u64) ``` Appends one character UTF-8 encoded, padded per `spec`; `?` writes it quoted and escaped (`'a'`). ### `FmtBuf.put_byte` ```kairo fn put_byte(self, b: byte, spec: u64) ``` Appends a `byte` as two lowercase hex digits (`ff`); `#` adds `0x`. A byte is storage, not a number, so there is no decimal form. ### `FmtBuf.put_i8` ```kairo inline fn put_i8(self, v: i8, spec: u64) ``` Appends a `i8` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_i16` ```kairo inline fn put_i16(self, v: i16, spec: u64) ``` Appends a `i16` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_i32` ```kairo inline fn put_i32(self, v: i32, spec: u64) ``` Appends a `i32` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_i64` ```kairo inline fn put_i64(self, v: i64, spec: u64) ``` Appends a `i64` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_isize` ```kairo inline fn put_isize(self, v: isize, spec: u64) ``` Appends a `isize` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u8` ```kairo inline fn put_u8(self, v: u8, spec: u64) ``` Appends a `u8` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u16` ```kairo inline fn put_u16(self, v: u16, spec: u64) ``` Appends a `u16` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u32` ```kairo inline fn put_u32(self, v: u32, spec: u64) ``` Appends a `u32` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u64` ```kairo inline fn put_u64(self, v: u64, spec: u64) ``` Appends a `u64` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_usize` ```kairo inline fn put_usize(self, v: usize, spec: u64) ``` Appends a `usize` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_i128` ```kairo inline fn put_i128(self, v: i128, spec: u64) ``` Appends a `i128` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u128` ```kairo inline fn put_u128(self, v: u128, spec: u64) ``` Appends a `u128` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_i256` ```kairo inline fn put_i256(self, v: i256, spec: u64) ``` Appends a `i256` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u256` ```kairo inline fn put_u256(self, v: u256, spec: u64) ``` Appends a `u256` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_i512` ```kairo inline fn put_i512(self, v: i512, spec: u64) ``` Appends a `i512` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_u512` ```kairo inline fn put_u512(self, v: u512, spec: u64) ``` Appends a `u512` hole in decimal, or in the base the spec selects (`x`, `o`, `b`, with `#` for a prefix and `+` for a sign). Width, fill, alignment and `0` padding come from `spec`; numbers default to right-aligned. ### `FmtBuf.put_f16` ```kairo inline fn put_f16(self, v: f16, spec: u64) ``` Appends an `f16` hole via the runtime formatter (rt/fmt.h), honouring the sign bit of -0.0 and NaN. Precision, width, fill and alignment come from `spec`; the `e` base selects exponent form, `E` with the upper flag. ### `FmtBuf.put_bf16` ```kairo inline fn put_bf16(self, v: bf16, spec: u64) ``` Appends an `bf16` hole via the runtime formatter (rt/fmt.h), honouring the sign bit of -0.0 and NaN. Precision, width, fill and alignment come from `spec`; the `e` base selects exponent form, `E` with the upper flag. ### `FmtBuf.put_f32` ```kairo inline fn put_f32(self, v: f32, spec: u64) ``` Appends an `f32` hole via the runtime formatter (rt/fmt.h), honouring the sign bit of -0.0 and NaN. Precision, width, fill and alignment come from `spec`; the `e` base selects exponent form, `E` with the upper flag. With `spec == 0` it writes the shortest round-trip digits in place. ### `FmtBuf.put_f64` ```kairo inline fn put_f64(self, v: f64, spec: u64) ``` Appends an `f64` hole via the runtime formatter (rt/fmt.h), honouring the sign bit of -0.0 and NaN. Precision, width, fill and alignment come from `spec`; the `e` base selects exponent form, `E` with the upper flag. With `spec == 0` it writes the shortest round-trip digits in place. ### `FmtBuf.put_f128` ```kairo inline fn put_f128(self, v: f128, spec: u64) ``` Appends an `f128` hole via the runtime formatter (rt/fmt.h), honouring the sign bit of -0.0 and NaN. Precision, width, fill and alignment come from `spec`; the `e` base selects exponent form, `E` with the upper flag. ### `f256` and `f512` holes An `f256` or `f512` hole has no `put_` method on `FmtBuf`: the value formats itself, through its class's `fmt_put_` (`F256::fmt_put_`, `F512::fmt_put_`), so `FmtBuf` never names the two types and a program that does not use them never compiles their code. The text is the same contract as the other floats': the sign bit of -0.0 and NaN is honoured; precision, width, fill and alignment come from `spec`; the `e` base selects exponent form, `E` with the upper flag. The shortest form has at most 73 significant digits for `f256` and 149 for `f512`; a precision gives at most 600. ### `FmtBuf.put_ptr` ```kairo fn put_ptr(self, addr: usize, name: *const u8, name_len: usize, spec: u64) ``` Appends a pointer hole as ` @ 0x`, or `&null` for address 0. **Parameters** - `addr`: the pointer's address. - `name`: the pointee's spelling, a constant at the call site. - `name_len`: byte length of `name`. **Notes** `spec` is currently ignored. ### `FmtBuf.finish` ```kairo inline fn finish(self) -> string ``` Hands the buffer over as an owned `string`, NUL-terminated, and empties this FmtBuf. A spilled buffer's heap block is passed on as is; an inline one is copied to a new allocation of exactly `len + 1` bytes. Afterwards `data` is null and the buffer may be written again. ### `FmtBuf.view` ```kairo inline fn view(self) -> string ``` Returns the text so far as a borrowed `string` (capacity 0), without copying. Valid until this FmtBuf is written again, cleared or destroyed. **Notes** Calling it after `finish()`, before anything is written again, writes through a null `data` and crashes. ### `FmtBuf.clear` ```kairo inline fn clear(self) ``` Empties the buffer, keeping its storage (inline or heap) for reuse. --- ## Core library URL: https://www.kairolang.org/docs/library/core/ The core library (`Lib/builtin`) is the implicit prelude: every file sees these types, functions and macros without an import. The compiler lowers `[T]`, `T?`, ranges, f-strings, `panic` results and generators to the declarations documented here. | Page | Contents | | --- | --- | | [Containers](/docs/library/core/containers/) | Vector, HashMap, HashSet, slices and the Hash interface. | | [String](/docs/library/core/string/) | The string type and its methods. | | [Numbers](/docs/library/core/numbers/) | Big numbers, byte and C character types, and the `^^` operator. | | [Formatting](/docs/library/core/formatting/) | The f-string lowering target and formatting buffers. | | [Ranges and ordering](/docs/library/core/ranges-ordering/) | Range types and the Ordering enum. | | [Memory and allocation](/docs/library/core/memory-allocation/) | Allocator interfaces, scopes and raw allocation. | | [Errors and panics](/docs/library/core/errors-panics/) | Panic results, crash and assertion support. | | [Coroutines](/docs/library/core/coroutines/) | Generators, futures and suspension. | | [Intrinsics](/docs/library/core/intrinsics/) | Compiler builtins (`__builtin_*`) and target information. | | [Macros](/docs/library/core/macros/) | Macros declared in the builtin library. | | [Prelude](/docs/library/core/prelude/) | What every file sees without an import. | --- ## Intrinsics URL: https://www.kairolang.org/docs/library/core/intrinsics/ Compiler builtins (`__builtin_*`) and target information. ## Contents | Name | Summary | | --- | --- | | [`MemoryOrder`](#memoryorder) | The memory ordering of an atomic operation or fence, with the C11 / C++11 meaning. | | [`__builtin_copy`](#__builtin_copy) | Copies `size` bytes from `src` to `dst`; the regions must not overlap. | | [`__builtin_move_mem`](#__builtin_move_mem) | Copies `size` bytes from `src` to `dst`; the regions may overlap. | | [`__builtin_set_mem`](#__builtin_set_mem) | Sets `size` bytes at `ptr` to `value`. | | [`__builtin_compare_mem`](#__builtin_compare_mem) | Compares `size` bytes of `a` and `b` as unsigned bytes. | | [`__builtin_construct_at`](#__builtin_construct_at) | Placement construction: builds a `T` from `args` in the storage at `ptr` and returns a pointer to it. | | [`__builtin_destruct_at`](#__builtin_destruct_at) | Runs `T`'s destructor on `*ptr` and leaves the storage as it is. | | [`__builtin_bitcast`](#__builtin_bitcast) | Reinterprets the object representation of `v` as a `T`. | | [`__builtin_launder`](#__builtin_launder) | Returns a pointer to the `T` that now lives at `ptr`'s address, after the storage was reused for a new object. | | [`__builtin_assume_aligned`](#__builtin_assume_aligned) | Tells the optimizer that `ptr` is aligned to `align` and returns it. | | [`__builtin_size_of`](#__builtin_size_of) | Returns `sizeof T`. Evaluated at compile time. | | [`__builtin_align_of`](#__builtin_align_of) | Returns `alignof T`. | | [`__builtin_dynamic_size`](#__builtin_dynamic_size) | Returns the size of the object `p` points at, which may be a class derived from `T`: read through `T`'s hidden virtual when `T` has a virtual destructor, `sizeof T` otherwise. | | [`__builtin_dynamic_align`](#__builtin_dynamic_align) | Returns the alignment of the object `p` points at; see `__builtin_dynamic_size`. | | [`__builtin_is_same`](#__builtin_is_same) | Returns true when `T` and `U` are the same type. | | [`__builtin_is_void`](#__builtin_is_void) | Returns true when `T` is `void`. | | [`__builtin_is_pointer`](#__builtin_is_pointer) | Returns true when `T` is a pointer, safe or unsafe alike; `__builtin_is_safe_pointer` tells them apart. | | [`__builtin_is_array`](#__builtin_is_array) | Returns true when `T` is an array type. | | [`__builtin_is_function`](#__builtin_is_function) | Returns true when `T` is a function type. | | [`__builtin_is_enum`](#__builtin_is_enum) | Returns true when `T` is a plain enum. | | [`__builtin_is_union`](#__builtin_is_union) | Returns true when `T` is a union. | | [`__builtin_is_integral`](#__builtin_is_integral) | Returns true when `T` is an integer type. | | [`__builtin_is_floating_point`](#__builtin_is_floating_point) | Returns true when `T` is a floating-point type. | | [`__builtin_is_signed`](#__builtin_is_signed) | Returns true when `T` is a signed arithmetic type. | | [`__builtin_is_unsigned`](#__builtin_is_unsigned) | Returns true when `T` is an unsigned arithmetic type. | | [`__builtin_is_trivially_copyable`](#__builtin_is_trivially_copyable) | Returns true when `T` can be copied with `__builtin_copy`. | | [`__builtin_is_trivially_destructible`](#__builtin_is_trivially_destructible) | Returns true when destroying a `T` runs no code. | | [`__builtin_is_trivially_constructible`](#__builtin_is_trivially_constructible) | Returns true when a `T` can be trivially constructed from one `A`. | | [`__builtin_is_trivially_default_constructible`](#__builtin_is_trivially_default_constructible) | Returns true when `T()` runs no code. | | [`__builtin_is_trivially_assignable`](#__builtin_is_trivially_assignable) | Returns true when assigning a `U` to a `T` runs no non-trivial code. | | [`__builtin_is_trivially_relocatable`](#__builtin_is_trivially_relocatable) | Returns true when a `T` can be moved by copying its bytes and skipping the old object's destructor. | | [`__builtin_is_standard_layout`](#__builtin_is_standard_layout) | Returns true when `T` has standard layout. | | [`__builtin_is_aggregate`](#__builtin_is_aggregate) | Returns true when `T` is an aggregate. | | [`__builtin_is_empty`](#__builtin_is_empty) | Returns true when `T` is a class with no non-static data members. | | [`__builtin_is_polymorphic`](#__builtin_is_polymorphic) | Returns true when `T` has a virtual member. | | [`__builtin_is_abstract`](#__builtin_is_abstract) | Returns true when `T` has a pure virtual member. | | [`__builtin_is_final`](#__builtin_is_final) | Returns true when `T` is a final class. | | [`__builtin_has_virtual_destructor`](#__builtin_has_virtual_destructor) | Returns true when `T` has a virtual destructor. | | [`__builtin_is_base_of`](#__builtin_is_base_of) | Returns true when `B` is a base class of `D`. | | [`__builtin_is_convertible`](#__builtin_is_convertible) | Returns true when `F` converts implicitly to `T`. | | [`__builtin_is_constructible`](#__builtin_is_constructible) | Returns true when a `T` can be constructed from one `A`. | | [`__builtin_is_default_constructible`](#__builtin_is_default_constructible) | Returns true when `T()` is well formed. | | [`__builtin_is_assignable`](#__builtin_is_assignable) | Returns true when a `U` can be assigned to a `T`. | | [`__builtin_is_destructible`](#__builtin_is_destructible) | Returns true when a `T` can be destroyed. | | [`__builtin_ctz`](#__builtin_ctz) | Counts trailing zero bits of `v`, viewed as the unsigned type of `T`'s width. | | [`__builtin_clz`](#__builtin_clz) | Counts leading zero bits of `v`, viewed as the unsigned type of `T`'s width. | | [`__builtin_popcount`](#__builtin_popcount) | Counts the set bits of `v`, viewed as the unsigned type of `T`'s width. | | [`__builtin_bswap`](#__builtin_bswap) | Reverses the byte order of `v`. | | [`__builtin_rotl`](#__builtin_rotl) | Rotates `v` left by `n` bits; `n` is taken modulo the bit width of `T`. | | [`__builtin_rotr`](#__builtin_rotr) | Rotates `v` right by `n` bits; `n` is taken modulo the bit width of `T`. | | [`__builtin_add_overflow`](#__builtin_add_overflow) | Computes `a + b`, stores the wrapped result in `*result` and returns true when the exact value did not fit in `T`. | | [`__builtin_sub_overflow`](#__builtin_sub_overflow) | Computes `a - b`, stores the wrapped result in `*result` and returns true when the exact value did not fit in `T`. | | [`__builtin_mul_overflow`](#__builtin_mul_overflow) | Computes `a * b`, stores the wrapped result in `*result` and returns true when the exact value did not fit in `T`. | | [`__builtin_expect`](#__builtin_expect) | Returns `cond`, hinting that it is usually `expected`. | | [`__builtin_expect_prob`](#__builtin_expect_prob) | Returns `cond`, hinting its likely value from the probability `p` that it equals `expected`. | | [`__builtin_unreachable`](#__builtin_unreachable) | Tells the optimizer that control never reaches this call. | | [`__builtin_trap`](#__builtin_trap) | Aborts execution immediately with a trap instruction (`ud2`, `brk`, ...). | | [`__builtin_debugtrap`](#__builtin_debugtrap) | Stops in an attached debugger and otherwise continues. | | [`__builtin_assume`](#__builtin_assume) | Tells the optimizer that `cond` is true at this point. | | [`__builtin_prefetch`](#__builtin_prefetch) | Hints that the cache line holding `ptr` will be accessed soon. | | [`__builtin_is_constant_evaluated`](#__builtin_is_constant_evaluated) | Returns true when evaluated during constant evaluation and false at run time. | | [`__builtin_constant_p`](#__builtin_constant_p) | Returns true when the optimizer can fold `v` to a compile-time constant at this call. | | [`__builtin_crash`](#__builtin_crash) | Writes `msg[0..len)` and a newline to stderr, then terminates the process with `exit_code` via `_Exit` (no atexit handlers, no destructors). | | [`__builtin_signal`](#__builtin_signal) | Writes `msg[0..len)` and a newline to stderr, then raises `signal` at its default action. | | [`__builtin_abort`](#__builtin_abort) | Terminates the process abnormally. | | [`__builtin_atomic_load`](#__builtin_atomic_load) | Atomically reads `*ptr`. | | [`__builtin_atomic_store`](#__builtin_atomic_store) | Atomically writes `v` to `*ptr`. | | [`__builtin_atomic_exchange`](#__builtin_atomic_exchange) | Atomically replaces `*ptr` with `v` and returns the previous value. | | [`__builtin_atomic_cas`](#__builtin_atomic_cas) | Compare-and-swap: if `*ptr == *expected`, stores `desired` and returns true; otherwise copies `*ptr` into `*expected` and returns false. | | [`__builtin_atomic_fetch_add`](#__builtin_atomic_fetch_add) | Atomically applies `+` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fetch_sub`](#__builtin_atomic_fetch_sub) | Atomically applies `-` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fetch_and`](#__builtin_atomic_fetch_and) | Atomically applies `&` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fetch_or`](#__builtin_atomic_fetch_or) | Atomically applies `\|` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fetch_xor`](#__builtin_atomic_fetch_xor) | Atomically applies `^` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fetch_max`](#__builtin_atomic_fetch_max) | Atomically applies `max` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fetch_min`](#__builtin_atomic_fetch_min) | Atomically applies `min` to `*ptr` with `v` and returns the value `*ptr` had before. | | [`__builtin_atomic_fence`](#__builtin_atomic_fence) | A full memory fence with the given ordering. | | [`__builtin_atomic_signal_fence`](#__builtin_atomic_signal_fence) | A compiler-only fence with the given ordering, against a signal handler on the same thread; it emits no instruction. | | [`__builtin_atomic_is_lock_free`](#__builtin_atomic_is_lock_free) | Returns true when atomic operations on a `T` are always lock-free. | | [`TargetArch`](#targetarch) | The CPU architecture family of the compilation target. | | [`TargetOS`](#targetos) | The operating system of the compilation target; `Freestanding` when none is detected. | | [`TargetEnv`](#targetenv) | The ABI environment of the compilation target (libc / toolchain flavour). | | [`TargetInfo`](#targetinfo) | A description of the compilation target, from `__builtin_target_info()`. | | [`extend TargetInfo`](#extend-targetinfo) | | | [`__builtin_target_info`](#__builtin_target_info) | Returns a `TargetInfo` for the compilation target. | ## `MemoryOrder` ```kairo enum MemoryOrder derives i32 { Relaxed, Consume, Acquire, Release, AcqRel, SeqCst, } ``` The memory ordering of an atomic operation or fence, with the C11 / C++11 meaning. The discriminants are `__ATOMIC_RELAXED` .. `__ATOMIC_SEQ_CST`, so a value converts straight to clang's `int` order argument. ## `__builtin_copy` ```kairo inline fn __builtin_copy(dst: unsafe *u8, src: unsafe *const u8, size: usize) ``` Copies `size` bytes from `src` to `dst`; the regions must not overlap. Maps to `__builtin_memcpy`. **Safety** Both pointers must be valid for `size` bytes (even when `size` is 0, clang assumes they are non-null), and the regions must not overlap; use `__builtin_move_mem` if they might. ## `__builtin_move_mem` ```kairo inline fn __builtin_move_mem(dst: unsafe *u8, src: unsafe *const u8, size: usize) ``` Copies `size` bytes from `src` to `dst`; the regions may overlap. Maps to `__builtin_memmove`. **Safety** Both pointers must be valid for `size` bytes. ## `__builtin_set_mem` ```kairo inline fn __builtin_set_mem(ptr: unsafe *u8, value: byte, size: usize) ``` Sets `size` bytes at `ptr` to `value`. Maps to `__builtin_memset`. **Safety** `ptr` must be valid for writes of `size` bytes. ## `__builtin_compare_mem` ```kairo inline fn __builtin_compare_mem(a: unsafe *const u8, b: unsafe *const u8, size: usize) -> i32 ``` Compares `size` bytes of `a` and `b` as unsigned bytes. Returns a negative, zero or positive value. Maps to `__builtin_memcmp`. **Safety** Both pointers must be valid for `size` bytes. ## `__builtin_construct_at` ```kairo fn __builtin_construct_at(ptr: unsafe *u8, ...args: A) -> *T ``` Placement construction: builds a `T` from `args` in the storage at `ptr` and returns a pointer to it. Maps to placement `new` (`kairo_rt_construct_at`). **Safety** `ptr` must be valid for `sizeof T` bytes and aligned to `alignof T`, and must not already hold a live object that needs destroying. ## `__builtin_destruct_at` ```kairo fn __builtin_destruct_at(ptr: *T) ``` Runs `T`'s destructor on `*ptr` and leaves the storage as it is. Maps to an explicit `p->~T()`. **Safety** `ptr` must point at a live `T`; it must not be used or destroyed again afterwards. ## `__builtin_bitcast` ```kairo fn __builtin_bitcast(v: From) -> T ``` Reinterprets the object representation of `v` as a `T`. Maps to `__builtin_bit_cast`. `__builtin_bit_cast` is a clang keyword, so no C++ declaration can carry the name directly. **Notes** `T` and `From` must be the same size and trivially copyable; clang rejects the call otherwise. ## `__builtin_launder` ```kairo fn __builtin_launder(ptr: *T) -> *T ``` Returns a pointer to the `T` that now lives at `ptr`'s address, after the storage was reused for a new object. Maps to `__builtin_launder`. **Safety** A `T` must live at `ptr`'s address. ## `__builtin_assume_aligned` ```kairo inline fn __builtin_assume_aligned(ptr: unsafe *u8, align: usize) -> unsafe *u8 ``` Tells the optimizer that `ptr` is aligned to `align` and returns it. Implemented as an `__builtin_assume` on the address bits, so unlike clang's own form `align` need not be a constant. **Parameters** - `align`: A power of two. **Safety** `ptr` must really be `align`-aligned; otherwise the behaviour is undefined. ## `__builtin_size_of` ```kairo eval fn __builtin_size_of() -> usize ``` Returns `sizeof T`. Evaluated at compile time. ## `__builtin_align_of` ```kairo eval fn __builtin_align_of() -> usize ``` Returns `alignof T`. Evaluated at compile time. ## `__builtin_dynamic_size` ```kairo inline fn __builtin_dynamic_size(p: *T) -> usize ``` Returns the size of the object `p` points at, which may be a class derived from `T`: read through `T`'s hidden virtual when `T` has a virtual destructor, `sizeof T` otherwise. The compiler writes the body. **Safety** Read it before the destructor runs, and only for a live object. ## `__builtin_dynamic_align` ```kairo inline fn __builtin_dynamic_align(p: *T) -> usize ``` Returns the alignment of the object `p` points at; see `__builtin_dynamic_size`. **Safety** Read it before the destructor runs, and only for a live object. ## `__builtin_is_same` ```kairo eval fn __builtin_is_same() -> bool ``` Returns true when `T` and `U` are the same type. ## `__builtin_is_void` ```kairo eval fn __builtin_is_void() -> bool ``` Returns true when `T` is `void`. ## `__builtin_is_pointer` ```kairo eval fn __builtin_is_pointer() -> bool ``` Returns true when `T` is a pointer, safe or unsafe alike; `__builtin_is_safe_pointer` tells them apart. ## `__builtin_is_array` ```kairo eval fn __builtin_is_array() -> bool ``` Returns true when `T` is an array type. ## `__builtin_is_function` ```kairo eval fn __builtin_is_function() -> bool ``` Returns true when `T` is a function type. ## `__builtin_is_enum` ```kairo eval fn __builtin_is_enum() -> bool ``` Returns true when `T` is a plain enum. An ADT enum is a C++ struct, so it answers false (`__builtin_is_adt_enum`). ## `__builtin_is_union` ```kairo eval fn __builtin_is_union() -> bool ``` Returns true when `T` is a union. ## `__builtin_is_integral` ```kairo eval fn __builtin_is_integral() -> bool ``` Returns true when `T` is an integer type. ## `__builtin_is_floating_point` ```kairo eval fn __builtin_is_floating_point() -> bool ``` Returns true when `T` is a floating-point type. ## `__builtin_is_signed` ```kairo eval fn __builtin_is_signed() -> bool ``` Returns true when `T` is a signed arithmetic type. ## `__builtin_is_unsigned` ```kairo eval fn __builtin_is_unsigned() -> bool ``` Returns true when `T` is an unsigned arithmetic type. ## `__builtin_is_trivially_copyable` ```kairo eval fn __builtin_is_trivially_copyable() -> bool ``` Returns true when `T` can be copied with `__builtin_copy`. Maps to `__is_trivially_copyable`. ## `__builtin_is_trivially_destructible` ```kairo eval fn __builtin_is_trivially_destructible() -> bool ``` Returns true when destroying a `T` runs no code. Maps to `__is_trivially_destructible`. ## `__builtin_is_trivially_constructible` ```kairo eval fn __builtin_is_trivially_constructible() -> bool ``` Returns true when a `T` can be trivially constructed from one `A`. Maps to `__is_trivially_constructible(T, A)`. Exactly one argument type: an imported template does not yet take a forwarded pack, so the no-argument form is `__builtin_is_trivially_default_constructible`. ## `__builtin_is_trivially_default_constructible` ```kairo eval fn __builtin_is_trivially_default_constructible() -> bool ``` Returns true when `T()` runs no code. Maps to `__is_trivially_constructible(T)`. ## `__builtin_is_trivially_assignable` ```kairo eval fn __builtin_is_trivially_assignable() -> bool ``` Returns true when assigning a `U` to a `T` runs no non-trivial code. Maps to `__is_trivially_assignable`. ## `__builtin_is_trivially_relocatable` ```kairo eval fn __builtin_is_trivially_relocatable() -> bool ``` Returns true when a `T` can be moved by copying its bytes and skipping the old object's destructor. Maps to `__builtin_is_cpp_trivially_relocatable`. ## `__builtin_is_standard_layout` ```kairo eval fn __builtin_is_standard_layout() -> bool ``` Returns true when `T` has standard layout. Maps to `__is_standard_layout`. ## `__builtin_is_aggregate` ```kairo eval fn __builtin_is_aggregate() -> bool ``` Returns true when `T` is an aggregate. Maps to `__is_aggregate`. ## `__builtin_is_empty` ```kairo eval fn __builtin_is_empty() -> bool ``` Returns true when `T` is a class with no non-static data members. Maps to `__is_empty`. ## `__builtin_is_polymorphic` ```kairo eval fn __builtin_is_polymorphic() -> bool ``` Returns true when `T` has a virtual member. Maps to `__is_polymorphic`. ## `__builtin_is_abstract` ```kairo eval fn __builtin_is_abstract() -> bool ``` Returns true when `T` has a pure virtual member. Maps to `__is_abstract`. ## `__builtin_is_final` ```kairo eval fn __builtin_is_final() -> bool ``` Returns true when `T` is a final class. Maps to `__is_final`. ## `__builtin_has_virtual_destructor` ```kairo eval fn __builtin_has_virtual_destructor() -> bool ``` Returns true when `T` has a virtual destructor. Maps to `__has_virtual_destructor`. ## `__builtin_is_base_of` ```kairo eval fn __builtin_is_base_of() -> bool ``` Returns true when `B` is a base class of `D`. Maps to `__is_base_of`. ## `__builtin_is_convertible` ```kairo eval fn __builtin_is_convertible() -> bool ``` Returns true when `F` converts implicitly to `T`. Maps to `__is_convertible`. ## `__builtin_is_constructible` ```kairo eval fn __builtin_is_constructible() -> bool ``` Returns true when a `T` can be constructed from one `A`. Maps to `__is_constructible(T, A)`. Exactly one argument type; see `__builtin_is_trivially_constructible`. ## `__builtin_is_default_constructible` ```kairo eval fn __builtin_is_default_constructible() -> bool ``` Returns true when `T()` is well formed. Maps to `__is_constructible(T)`. ## `__builtin_is_assignable` ```kairo eval fn __builtin_is_assignable() -> bool ``` Returns true when a `U` can be assigned to a `T`. Maps to `__is_assignable`. ## `__builtin_is_destructible` ```kairo eval fn __builtin_is_destructible() -> bool ``` Returns true when a `T` can be destroyed. Maps to `__is_destructible`. ## `__builtin_ctz` ```kairo fn __builtin_ctz(v: T) -> u32 ``` Counts trailing zero bits of `v`, viewed as the unsigned type of `T`'s width. `ctz(0)` is the bit width. Maps to `__builtin_ctzg`. Plain `fn`, not `eval fn`, so it accepts run-time values; it is `constexpr` in C++, so constant arguments still fold. ## `__builtin_clz` ```kairo fn __builtin_clz(v: T) -> u32 ``` Counts leading zero bits of `v`, viewed as the unsigned type of `T`'s width. `clz(0)` is the bit width. Maps to `__builtin_clzg`. ## `__builtin_popcount` ```kairo fn __builtin_popcount(v: T) -> u32 ``` Counts the set bits of `v`, viewed as the unsigned type of `T`'s width. Maps to `__builtin_popcountg`. ## `__builtin_bswap` ```kairo fn __builtin_bswap(v: T) -> T ``` Reverses the byte order of `v`. A 1-byte `T` is returned unchanged. Maps to `__builtin_bswap16` / `32` / `64`. ## `__builtin_rotl` ```kairo fn __builtin_rotl(v: T, n: u32) -> T ``` Rotates `v` left by `n` bits; `n` is taken modulo the bit width of `T`. ## `__builtin_rotr` ```kairo fn __builtin_rotr(v: T, n: u32) -> T ``` Rotates `v` right by `n` bits; `n` is taken modulo the bit width of `T`. ## `__builtin_add_overflow` ```kairo fn __builtin_add_overflow(a: T, b: T, result: *T) -> bool ``` Computes `a + b`, stores the wrapped result in `*result` and returns true when the exact value did not fit in `T`. Maps to `__builtin_add_overflow`. **Parameters** - `result`: Receives the wrapped value even when the call returns true. ## `__builtin_sub_overflow` ```kairo fn __builtin_sub_overflow(a: T, b: T, result: *T) -> bool ``` Computes `a - b`, stores the wrapped result in `*result` and returns true when the exact value did not fit in `T`. Maps to `__builtin_sub_overflow`. **Parameters** - `result`: Receives the wrapped value even when the call returns true. ## `__builtin_mul_overflow` ```kairo fn __builtin_mul_overflow(a: T, b: T, result: *T) -> bool ``` Computes `a * b`, stores the wrapped result in `*result` and returns true when the exact value did not fit in `T`. Maps to `__builtin_mul_overflow`. **Parameters** - `result`: Receives the wrapped value even when the call returns true. ## `__builtin_expect` ```kairo inline fn __builtin_expect(cond: bool, expected: bool) -> bool ``` Returns `cond`, hinting that it is usually `expected`. Maps to `__builtin_expect`. ## `__builtin_expect_prob` ```kairo inline fn __builtin_expect_prob(cond: bool, expected: bool, p: f64) -> bool ``` Returns `cond`, hinting its likely value from the probability `p` that it equals `expected`. Only the direction of the hint is kept (`p >= 0.5`): clang takes an exact probability only as a literal, and `p` is a run-time value here. Maps to `__builtin_expect`. ## `__builtin_unreachable` ```kairo inline fn __builtin_unreachable() -> ! ``` Tells the optimizer that control never reaches this call. Maps to `__builtin_unreachable`. **Safety** Reaching it is undefined behaviour. ## `__builtin_trap` ```kairo inline fn __builtin_trap() -> ! ``` Aborts execution immediately with a trap instruction (`ud2`, `brk`, ...). Maps to `__builtin_trap`. Prints nothing and runs no handlers. ## `__builtin_debugtrap` ```kairo inline fn __builtin_debugtrap() ``` Stops in an attached debugger and otherwise continues. Maps to `__builtin_debugtrap`. ## `__builtin_assume` ```kairo inline fn __builtin_assume(cond: bool) ``` Tells the optimizer that `cond` is true at this point. Maps to `__builtin_assume`. **Safety** If `cond` is false the behaviour is undefined. `cond` is not evaluated for effects the program relies on. ## `__builtin_prefetch` ```kairo inline fn __builtin_prefetch(ptr: unsafe *const u8, rw: i32 = 0, locality: i32 = 3) ``` Hints that the cache line holding `ptr` will be accessed soon. Maps to `__builtin_prefetch`; never faults, even for an invalid address. **Parameters** - `rw`: 0 for a read (default), anything else for a write. - `locality`: 0 (no reuse) to 3 (keep in all cache levels, the default); other values are treated as 3. ## `__builtin_is_constant_evaluated` ```kairo inline fn __builtin_is_constant_evaluated() -> bool ``` Returns true when evaluated during constant evaluation and false at run time. Maps to `__builtin_is_constant_evaluated`. ## `__builtin_constant_p` ```kairo fn __builtin_constant_p(v: T) -> bool ``` Returns true when the optimizer can fold `v` to a compile-time constant at this call. A false result proves nothing. Maps to `__builtin_constant_p`. ## `__builtin_crash` ```kairo inline fn __builtin_crash(msg: *const u8, len: usize, exit_code: i32) -> ! ``` Writes `msg[0..len)` and a newline to stderr, then terminates the process with `exit_code` via `_Exit` (no atexit handlers, no destructors). Never returns. **Parameters** - `exit_code`: The process exit status. **Safety** `msg` must be valid for reads of `len` bytes. ## `__builtin_signal` ```kairo inline fn __builtin_signal(msg: *const u8, len: usize, signal: SIGNAL) -> ! ``` Writes `msg[0..len)` and a newline to stderr, then raises `signal` at its default action. Never returns. **Safety** `msg` must be valid for reads of `len` bytes. ## `__builtin_abort` ```kairo inline fn __builtin_abort() -> ! ``` Terminates the process abnormally. Maps to `__builtin_abort`; never returns. ## `__builtin_atomic_load` ```kairo fn __builtin_atomic_load(ptr: *const T, order: MemoryOrder) -> T ``` Atomically reads `*ptr`. Maps to `__atomic_load_n`. Pass `order` as a constant so the inlined helper folds it; a run-time order compiles to a switch. **Parameters** - `order`: `Relaxed`, `Consume`, `Acquire` or `SeqCst`. ## `__builtin_atomic_store` ```kairo fn __builtin_atomic_store(ptr: *T, v: T, order: MemoryOrder) ``` Atomically writes `v` to `*ptr`. Maps to `__atomic_store_n`. **Parameters** - `order`: `Relaxed`, `Release` or `SeqCst`. ## `__builtin_atomic_exchange` ```kairo fn __builtin_atomic_exchange(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically replaces `*ptr` with `v` and returns the previous value. Maps to `__atomic_exchange_n`. ## `__builtin_atomic_cas` ```kairo fn __builtin_atomic_cas( ptr: *T, expected: *T, desired: T, weak: bool, succ: MemoryOrder, fail: MemoryOrder ) -> bool ``` Compare-and-swap: if `*ptr == *expected`, stores `desired` and returns true; otherwise copies `*ptr` into `*expected` and returns false. Maps to `__atomic_compare_exchange_n`. **Parameters** - `weak`: A weak exchange may fail spuriously; use it in a retry loop. - `succ`: The order when the exchange happens. - `fail`: The order of the load when it does not; it may not be `Release` or `AcqRel` nor stronger than `succ`. ## `__builtin_atomic_fetch_add` ```kairo fn __builtin_atomic_fetch_add(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `+` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_add`. ## `__builtin_atomic_fetch_sub` ```kairo fn __builtin_atomic_fetch_sub(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `-` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_sub`. ## `__builtin_atomic_fetch_and` ```kairo fn __builtin_atomic_fetch_and(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `&` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_and`. ## `__builtin_atomic_fetch_or` ```kairo fn __builtin_atomic_fetch_or(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `|` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_or`. ## `__builtin_atomic_fetch_xor` ```kairo fn __builtin_atomic_fetch_xor(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `^` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_xor`. ## `__builtin_atomic_fetch_max` ```kairo fn __builtin_atomic_fetch_max(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `max` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_max`. ## `__builtin_atomic_fetch_min` ```kairo fn __builtin_atomic_fetch_min(ptr: *T, v: T, order: MemoryOrder) -> T ``` Atomically applies `min` to `*ptr` with `v` and returns the value `*ptr` had before. Maps to `__atomic_fetch_min`. ## `__builtin_atomic_fence` ```kairo inline fn __builtin_atomic_fence(order: MemoryOrder) ``` A full memory fence with the given ordering. Maps to `__atomic_thread_fence`. ## `__builtin_atomic_signal_fence` ```kairo inline fn __builtin_atomic_signal_fence(order: MemoryOrder) ``` A compiler-only fence with the given ordering, against a signal handler on the same thread; it emits no instruction. Maps to `__atomic_signal_fence`. ## `__builtin_atomic_is_lock_free` ```kairo eval fn __builtin_atomic_is_lock_free() -> bool ``` Returns true when atomic operations on a `T` are always lock-free. Maps to `__atomic_always_lock_free(sizeof(T), 0)`. ## `TargetArch` ```kairo enum TargetArch { Unknown, X86, X86_64, Arm, AArch64, RiscV32, RiscV64, Wasm32, Wasm64, PowerPC64, LoongArch64 } ``` The CPU architecture family of the compilation target. ## `TargetOS` ```kairo enum TargetOS { Unknown, Linux, Windows, MacOS, IOS, FreeBSD, NetBSD, OpenBSD, Wasi, Emscripten, Android, Freestanding } ``` The operating system of the compilation target; `Freestanding` when none is detected. ## `TargetEnv` ```kairo enum TargetEnv { Unknown, Gnu, Musl, Msvc, MinGW, Android, Eabi } ``` The ABI environment of the compilation target (libc / toolchain flavour). `Unknown` when the driver did not define one for the triple. ## `TargetInfo` ```kairo struct TargetInfo ``` A description of the compilation target, from `__builtin_target_info()`. ## `extend TargetInfo` ```kairo extend TargetInfo ``` ### `TargetInfo.is_linux` ```kairo eval fn is_linux(const self) -> bool ``` Returns true for Linux. ### `TargetInfo.is_windows` ```kairo eval fn is_windows(const self) -> bool ``` Returns true for Windows. ### `TargetInfo.is_macos` ```kairo eval fn is_macos(const self) -> bool ``` Returns true for macOS. ### `TargetInfo.is_apple` ```kairo eval fn is_apple(const self) -> bool ``` Returns true for macOS or iOS. ### `TargetInfo.is_bsd` ```kairo eval fn is_bsd(const self) -> bool ``` Returns true for FreeBSD, NetBSD or OpenBSD. ### `TargetInfo.is_unix` ```kairo eval fn is_unix(const self) -> bool ``` Returns true for Linux, Android, Apple and BSD targets. ### `TargetInfo.is_wasm` ```kairo eval fn is_wasm(const self) -> bool ``` Returns true for wasm32 or wasm64. ### `TargetInfo.is_64bit` ```kairo eval fn is_64bit(const self) -> bool ``` Returns true when pointers are 64 bits wide. ### `TargetInfo.is_musl` ```kairo eval fn is_musl(const self) -> bool ``` Returns true when the environment is musl. ## `__builtin_target_info` ```kairo eval fn __builtin_target_info() -> TargetInfo ``` Returns a `TargetInfo` for the compilation target. Evaluated at compile time from clang's predefined macros and `__kairo_env___`, which the driver defines from the triple (nothing else tells musl from glibc). --- ## Macros URL: https://www.kairolang.org/docs/library/core/macros/ Macros declared in the builtin library. ## `crash!` ```kairo macro crash!(...msg) ``` Ends the process with an optional message: `crash!()` or `crash!("why")`. Not a panic: it joins no panic set and no `try` catches it, so a function that calls it needs no `panic` specifier and `main` may use it. The message and a newline go to stderr (nothing when empty), then the process aborts. It expands to `crash_with(msg...)`, so the call never returns and ends its path for the flow checks. What it reports is not final; rely only on "it does not return". A file's own `crash!` shadows this one. **Example** ```kairo fn main() -> i32 { if false { crash!("unreachable state") } return 0 } ``` **See also** crash\_with --- ## Memory and allocation URL: https://www.kairolang.org/docs/library/core/memory-allocation/ Allocator interfaces, scopes and raw allocation. ## Contents | Name | Summary | | --- | --- | | [`Allocator`](#allocator) | Everything a type must have to be used as an allocator: `alloc` and `free`, both static. | | [`Resizer`](#resizer) | An allocator that can grow or shrink a block without moving it. | | [`Reallocator`](#reallocator) | An allocator that can grow or shrink a block, moving it if it has to. | | [`ZeroAllocator`](#zeroallocator) | An allocator that gets zeroed memory for free (fresh pages, `calloc`). | | [`ScopedAllocator`](#scopedallocator) | An allocator usable with `AllocatorScope`. | | [`FullAllocator`](#fullallocator) | An allocator with every capability: `Allocator` plus resize, realloc and zeroed allocation. | | [`ScopedFullAllocator`](#scopedfullallocator) | A `FullAllocator` that is also a `ScopedAllocator`: what `AllocatorScope` takes. | | [`is_pow2`](#is_pow2) | Returns true when `v` is a power of two (zero is not). | | [`align_up`](#align_up) | Rounds `v` up to the next multiple of `align`. | | [`dangling`](#dangling) | Returns a non-null, aligned pointer that owns nothing: what a zero-size request gets. | | [`realloc_by_copy`](#realloc_by_copy) | A `realloc` for an allocator with no faster path: allocates, copies, frees the old block. | | [`set_oom_handler`](#set_oom_handler) | Replaces what `create` does when the allocator returns `&null`. | | [`oom`](#oom) | Runs the OOM handler for a failed allocation of `size` bytes at `align`; never returns. | | [`ScopeFrame`](#scopeframe) | One active scope: the allocator's static functions as pointers, the range snapshot taken when it opened, and the bounding box of it and every scope below it. | | [`ScopeChunk`](#scopechunk) | SCOPE\_CHUNK frames, plus their ranges packed for the scan: lo[i + 1] and span[i + 1] = hi - lo for frames[i], so a hit is one subtract and one unsigned compare. | | [`alloc_raw`](#alloc_raw) | Allocates `size` bytes from the allocator in effect: the innermost open `AllocatorScope`, else `Global`. | | [`free_raw`](#free_raw) | Gives a block back to whichever allocator it came from: the open scope whose range holds it, else `Global`. | | [`Uninitialized`](#uninitialized) | Storage for one `T` that holds no `T`. | | [`uninitialized_from`](#uninitialized_from) | Runs `*p`'s destructor and returns its storage as an `Uninitialized`. | | [`UninitializedSlice`](#uninitializedslice) | Storage for `cap` Ts, of which `[0, len)` are live. | | [`size`](#size) | Returns the number of live elements. | | [`capacity`](#capacity) | Returns the number of elements the storage has room for. | | [`as_bytes`](#as_bytes) | Returns the storage as raw bytes. | | [`push`](#push) | Constructs a `T` from `args` in the next free slot. | | [`finish`](#finish) | Every slot is live: ownership of the cap Ts moves to the caller, who destroys them and frees capacity() \* sizeof T bytes. | | [`clear`](#clear) | Destroys the live prefix, last first. | ## `Allocator` ```kairo interface Allocator ``` Everything a type must have to be used as an allocator: `alloc` and `free`, both static. Failure is `&null`; an allocator never aborts or panics (the OOM policy belongs to the front end). See `base/alloc.k` for the full contract. ### `Allocator.alloc` ```kairo static fn alloc(size: usize, align: usize) -> unsafe *u8 ``` Returns `size` bytes aligned to `align`, or `&null` on failure. **Parameters** - `size`: Nonzero; the front end never forwards a zero-size request. - `align`: A power of two. ### `Allocator.free` ```kairo static fn free(ptr: unsafe *u8, size: usize, align: usize) ``` Gives a block back. **Safety** `ptr` must be a non-null block this allocator returned, and `size` and `align` must be the values it was allocated (or last successfully resized) with. ## `Resizer` ```kairo interface Resizer derives Allocator ``` An allocator that can grow or shrink a block without moving it. ### `Resizer.resize` ```kairo static fn resize(ptr: unsafe *u8, old_size: usize, new_size: usize, align: usize) -> bool ``` Resizes the block in place. Returns false, with the block untouched, when it cannot. ## `Reallocator` ```kairo interface Reallocator derives Allocator ``` An allocator that can grow or shrink a block, moving it if it has to. ### `Reallocator.realloc` ```kairo static fn realloc(ptr: unsafe *u8, old_size: usize, new_size: usize, align: usize) -> unsafe *u8 ``` Resizes the block, moving it if needed, and returns the new pointer. Returns `&null`, with the original block untouched, on failure. ## `ZeroAllocator` ```kairo interface ZeroAllocator derives Allocator ``` An allocator that gets zeroed memory for free (fresh pages, `calloc`). ### `ZeroAllocator.alloc_zeroed` ```kairo static fn alloc_zeroed(size: usize, align: usize) -> unsafe *u8 ``` Like `alloc`, but every returned byte is zero. Returns `&null` on failure. ## `ScopedAllocator` ```kairo interface ScopedAllocator derives Allocator ``` An allocator usable with `AllocatorScope`. `enter()` returns a token that `leave()` takes back, and `range()` is the address range every block it hands out lies in while the scope is open. No two open scopes may have overlapping ranges. ### `ScopedAllocator.enter` ```kairo static fn enter() -> usize ``` Called when a scope opens; returns a token that is passed back to `leave`. ### `ScopedAllocator.leave` ```kairo static fn leave(mark: usize) ``` Called when the scope closes, with the token `enter` returned. ### `ScopedAllocator.range` ```kairo static fn range() -> (unsafe *u8, unsafe *u8) ``` Returns the half-open address range `[lo, hi)` that all of this allocator's blocks lie in. ## `FullAllocator` ```kairo interface FullAllocator derives Resizer + Reallocator + ZeroAllocator ``` An allocator with every capability: `Allocator` plus resize, realloc and zeroed allocation. What the front end and `@set_global_allocator` take until `eval if` can test a capability per instantiation; then the front end will take `Allocator` and fall back where one is missing. ## `ScopedFullAllocator` ```kairo interface ScopedFullAllocator derives ScopedAllocator + FullAllocator ``` A `FullAllocator` that is also a `ScopedAllocator`: what `AllocatorScope` takes. ## `is_pow2` ```kairo inline fn is_pow2(v: usize) -> bool ``` Returns true when `v` is a power of two (zero is not). ## `align_up` ```kairo inline fn align_up(v: usize, align: usize) -> usize ``` Rounds `v` up to the next multiple of `align`. **Parameters** - `align`: A power of two. ## `dangling` ```kairo inline fn dangling(align: usize) -> unsafe *u8 ``` Returns a non-null, aligned pointer that owns nothing: what a zero-size request gets. **Safety** Never dereference or free the result. ## `realloc_by_copy` ```kairo fn realloc_by_copy( ptr: unsafe *u8, old_size: usize, new_size: usize, align: usize ) -> unsafe *u8 ``` A `realloc` for an allocator with no faster path: allocates, copies, frees the old block. Returns `&null`, with the original block untouched, when the new allocation fails. **Safety** `ptr` must be a block `A` allocated with `old_size` and `align`. ## `set_oom_handler` ```kairo fn set_oom_handler(h: fn(usize, usize) -> !) ``` Replaces what `create` does when the allocator returns `&null`. The handler never returns. The default writes `kairo: out of memory` to stderr and exits with code 134. The handler is process-wide, not per thread, and the call is not synchronized. ## `oom` ```kairo fn oom(size: usize, align: usize) -> ! ``` Runs the OOM handler for a failed allocation of `size` bytes at `align`; never returns. ## `ScopeFrame` ```kairo struct ScopeFrame ``` One active scope: the allocator's static functions as pointers, the range snapshot taken when it opened, and the bounding box of it and every scope below it. 64 bytes on a 64-bit target: one cache line. ## `ScopeChunk` ```kairo struct ScopeChunk ``` SCOPE\_CHUNK frames, plus their ranges packed for the scan: lo[i + 1] and span[i + 1] = hi - lo for frames[i], so a hit is one subtract and one unsigned compare. Slot 0 is a sentinel (lo 0, span MAX) that every address hits, which ends the scan of a chunk without a bounds check. ## `alloc_raw` ```kairo inline fn alloc_raw(size: usize, align: usize) -> unsafe *u8 ``` Allocates `size` bytes from the allocator in effect: the innermost open `AllocatorScope`, else `Global`. Returns `&null` on failure. A zero `size` returns `dangling(align)`. Pair the block with `free_raw`. **Parameters** - `align`: A power of two (asserted). **Safety** The result is uninitialized memory; free it with `free_raw` using the same `size` and `align`. ## `free_raw` ```kairo inline fn free_raw(ptr: unsafe *u8, size: usize, align: usize) ``` Gives a block back to whichever allocator it came from: the open scope whose range holds it, else `Global`. With no scope open this is one thread-local load, one test and a tail call to `Global::free`. A zero `size` is a no-op. **Safety** `ptr` must come from `alloc_raw` / `resize_raw` (or `dangling` for size 0), with the `size` and `align` it was last allocated with. ## `Uninitialized` ```kairo class Uninitialized ``` Storage for one `T` that holds no `T`. Move-only. Turn it into an object with `construct`, or give it back with `release_in`. This is the typed layer between an allocator's bytes and a live object. ### `Uninitialized.Uninitialized` ```kairo inline fn Uninitialized(self, ptr: unsafe *u8) ``` Wraps raw bytes. The caller vouches for size and alignment. ### `Uninitialized.construct` ```kairo inline fn <...A> construct(self, ...args: A) -> *T ``` Builds a T in the storage. The only safe way to a \*T. ### `Uninitialized.assume_init` ```kairo inline fn assume_init( self ) -> *T requires __builtin_is_trivially_copyable() && __builtin_is_trivially_destructible() ``` For a T whose bytes have all been written through as\_bytes. Only for types that come into being when their bytes are written (trivially copyable and destructible). ### `Uninitialized.as_bytes` ```kairo inline fn as_bytes(const self) -> unsafe *u8 ``` Returns the storage as raw bytes. ### `Uninitialized.retype` ```kairo fn retype(self) -> Uninitialized requires sizeof U <= sizeof T && alignof U <= alignof T ``` Reinterprets the storage for a U of the same or smaller size and alignment. Nothing lives in it either way. ## `uninitialized_from` ```kairo inline fn uninitialized_from(p: *T) -> Uninitialized ``` Runs `*p`'s destructor and returns its storage as an `Uninitialized`. **Safety** `p` must point at a live `T` that is not used afterwards. ## `UninitializedSlice` ```kairo class UninitializedSlice ``` Storage for `cap` Ts, of which `[0, len)` are live. Dropping it destroys only the live prefix; the storage itself goes back through `destroy_slice` or `destroy_slice_in`. Move-only: a moved-from slice is left empty so its drop destroys nothing. ### `UninitializedSlice.UninitializedSlice` ```kairo inline fn UninitializedSlice(self, ptr: unsafe *u8, cap: usize) ``` Wraps `cap` Ts' worth of raw bytes, with none of them live. **Safety** `ptr` must be valid for `cap * sizeof T` bytes at `alignof T`. ## `size` ```kairo inline fn size(const self) -> usize ``` Returns the number of live elements. ## `capacity` ```kairo inline fn capacity(const self) -> usize ``` Returns the number of elements the storage has room for. ## `as_bytes` ```kairo inline fn as_bytes(const self) -> unsafe *u8 ``` Returns the storage as raw bytes. ## `push` ```kairo inline fn <...A> push(self, ...args: A) ``` Constructs a `T` from `args` in the next free slot. **Panics** Traps (`__builtin_trap`) when the slice is full. ## `finish` ```kairo inline fn finish(self) -> *T ``` Every slot is live: ownership of the cap Ts moves to the caller, who destroys them and frees capacity() \* sizeof T bytes. ## `clear` ```kairo fn clear(self) ``` Destroys the live prefix, last first. Idempotent. --- ## Numbers URL: https://www.kairolang.org/docs/library/core/numbers/ Big numbers, byte and C character types, and the `^^` operator. ## Contents | Name | Summary | | --- | --- | | [`__builtin_c_char`](#__builtin_c_char) | C and C++'s plain `char`, a character type distinct from `i8` and `u8`. | | [`__builtin_c_wchar`](#__builtin_c_wchar) | C++'s `wchar_t`, the `CWChar` lang item. | | [`__builtin_c_char16`](#__builtin_c_char16) | C++'s `char16_t`, the `CChar16` lang item. | | [`__builtin_c_char8`](#__builtin_c_char8) | C++'s `char8_t`, the `CChar8` lang item. | | [Operators](#operators) | | | [`BigFloat`](#bigfloat) | The arbitrary-precision float lang item. | | [`BigInt`](#bigint) | The arbitrary-precision integer lang item. | ## `__builtin_c_char` ```kairo type __builtin_c_char = u8 ``` C and C++'s plain `char`, a character type distinct from `i8` and `u8`. Users spell it `std::c_char`. The `u8` body is only what parses; the type is the `CChar` lang item, which C++ spells `char`. ## `__builtin_c_wchar` ```kairo type __builtin_c_wchar = u32 ``` C++'s `wchar_t`, the `CWChar` lang item. Users spell it `std::c_wchar`. Distinct from every integer type. The `u32` body is only what parses; the type store lays it out from the target (16 bits wide on Windows). ## `__builtin_c_char16` ```kairo type __builtin_c_char16 = u16 ``` C++'s `char16_t`, the `CChar16` lang item. Users spell it `std::c_char16`. ## `__builtin_c_char8` ```kairo type __builtin_c_char8 = u8 ``` C++'s `char8_t`, the `CChar8` lang item. Users spell it `std::c_char8`. ## Operators `x ^^ n` on a primitive base is lowered to a call to `pow`. The function is private, so it is documented here rather than called by name. ### `pow` ```kairo fn pow(base: B, exp: E) -> B ``` Implements `^^` on a primitive base: `x ^^ n` is lowered to `pow(x, n)`. Repeated squaring, so overflow is exactly `*`'s. A negative exponent is `(1 / base) ^^ -exp` under the base type's own division: for an integer base that reciprocal is 0, 1 or -1 and nothing can overflow on the way back; for a float base it is the reciprocal. The exponent negation is written `-(exp + 1)` rather than `-exp`, which has no value for the minimum. `: type` rather than a bound: `B` and `E` are only ever primitives and no interface says "numeric" yet, so C++ checks this one body per instance. **See also** Lib/builtin/base/pow.k ## `BigFloat` ```kairo struct BigFloat ``` The arbitrary-precision float lang item. Layout only: no operations are declared in builtin yet. Fields: `mant` is the mantissa (a BigInt) and `exp` is the exponent. ## `BigInt` ```kairo struct BigInt ``` The arbitrary-precision integer lang item. Layout only: no operations are declared in builtin yet. Fields: `limbs` points at the 64-bit limbs of the magnitude, `len` counts them, and `neg` is the sign flag. --- ## Prelude URL: https://www.kairolang.org/docs/library/core/prelude/ What every file sees without an import. ## Contents | Name | Summary | | --- | --- | | [`null_t`](#null_t) | The type of the `null` constant. | | [`Nullable`](#nullable) | The type behind `T?`. | | [`__builtin_niche_of`](#__builtin_niche_of) | Counts the bit patterns a `T` never holds, which the layout engine uses to store a `T?` without a tag: 1 for a pointer, the values past a plain enum's or an ADT tag's range, a record's first field's niches, and 0 for anything else. | | [`__builtin_type_id`](#__builtin_type_id) | Returns `T`'s panic type id, the tag an `Err` holding a `T` is stored as. | | [`__builtin_panic_site`](#__builtin_panic_site) | Returns the panic site id of this call, registered in the translation unit's `__kairo_panic_sites` table as a `panic` would be. | | [`__builtin_is_safe_pointer`](#__builtin_is_safe_pointer) | Kairo-only type queries, answered at compile time for a concrete `T`. | | [`__builtin_is_unsafe_pointer`](#__builtin_is_unsafe_pointer) | Returns true when `T` is an unsafe pointer (`unsafe *U`). | | [`__builtin_is_nullable`](#__builtin_is_nullable) | Returns true when `T` is a nullable type (`U?`). | | [`__builtin_is_adt_enum`](#__builtin_is_adt_enum) | Returns true when `T` is an enum with payload cases, not a plain enum. | | [`__builtin_is_class`](#__builtin_is_class) | Returns true when `T` is a `class`. | | [`__builtin_is_struct`](#__builtin_is_struct) | Returns true when `T` is a `struct`. | | [`__builtin_is_tuple`](#__builtin_is_tuple) | Returns true when `T` is a tuple type. | | [`__builtin_tuple_arity`](#__builtin_tuple_arity) | Returns the number of elements of the tuple type `T`. | ## `null_t` ```kairo struct null_t ``` The type of the `null` constant. Every `null` converts to a `T?`, and a C++ host spells the constant `::builtin::null`. It carries nothing, so the struct is empty. ## `Nullable` ```kairo enum Nullable ``` The type behind `T?`. Kairo code spells it only as the `?` suffix; C++ hosts name it. It is an ADT, so the payload is a real `T` only while present: it is constructed in place and destroyed exactly once, and copy and move follow `T`'s own. Every implicit `T -> T?` and `null -> T?` conversion is one of its constructors; C++ also gets `is_null()`, the unchecked `__value()`, and `==` when `T` has one. The compiler may lay it out niche-filled (a null pointer as the null case, for instance), so nothing may depend on the layout. **See also** \_\_builtin\_niche\_of ### `Nullable.Value` ```kairo Value ``` A present value: `T?` holding `v`. ### `Nullable.Null` ```kairo Null ``` No value: what `null` assigns to a `T?`. ## `__builtin_niche_of` ```kairo eval fn __builtin_niche_of() -> u64 ``` Counts the bit patterns a `T` never holds, which the layout engine uses to store a `T?` without a tag: 1 for a pointer, the values past a plain enum's or an ADT tag's range, a record's first field's niches, and 0 for anything else. Answered at compile time: the compiler replaces every call with the count, so this body never runs. Compiler test hook; user code has no reason to call it. ## `__builtin_type_id` ```kairo eval fn __builtin_type_id() -> u32 ``` Returns `T`'s panic type id, the tag an `Err` holding a `T` is stored as. It is the same in every translation unit. Answered at compile time; this body never runs. Compiler test hook. ## `__builtin_panic_site` ```kairo fn __builtin_panic_site() -> u32 ``` Returns the panic site id of this call, registered in the translation unit's `__kairo_panic_sites` table as a `panic` would be. The compiler replaces every call with the id; this body never runs. Compiler test hook. ## `__builtin_is_safe_pointer` ```kairo eval fn __builtin_is_safe_pointer() -> bool ``` Kairo-only type queries, answered at compile time for a concrete `T`. C++ spells a safe and an unsafe pointer alike, and a class, a struct and an ADT enum are all C++ structs, so only the compiler can tell them apart. A `T` that depends on a generic parameter is an error, and these bodies never run. The queries C++ can answer are in `base/intrinsics.k`. Each returns true when `T` is a safe pointer (`*U`). ## `__builtin_is_unsafe_pointer` ```kairo eval fn __builtin_is_unsafe_pointer() -> bool ``` Returns true when `T` is an unsafe pointer (`unsafe *U`). ## `__builtin_is_nullable` ```kairo eval fn __builtin_is_nullable() -> bool ``` Returns true when `T` is a nullable type (`U?`). ## `__builtin_is_adt_enum` ```kairo eval fn __builtin_is_adt_enum() -> bool ``` Returns true when `T` is an enum with payload cases, not a plain enum. ## `__builtin_is_class` ```kairo eval fn __builtin_is_class() -> bool ``` Returns true when `T` is a `class`. ## `__builtin_is_struct` ```kairo eval fn __builtin_is_struct() -> bool ``` Returns true when `T` is a `struct`. ## `__builtin_is_tuple` ```kairo eval fn __builtin_is_tuple() -> bool ``` Returns true when `T` is a tuple type. ## `__builtin_tuple_arity` ```kairo eval fn __builtin_tuple_arity() -> usize ``` Returns the number of elements of the tuple type `T`. --- ## Ranges and ordering URL: https://www.kairolang.org/docs/library/core/ranges-ordering/ Range types and the Ordering enum. ## Contents | Name | Summary | | --- | --- | | [`Ordering`](#ordering) | The result of a three-way comparison: what `a <=> b` evaluates to. | | [`Range`](#range) | A bounded range: `a..b` (exclusive end) and `a..=b` (inclusive end). | | [`RangeFrom`](#rangefrom) | A range with no end: `a..`, or `..` as `begin: 0` (a `RangeFrom`). | | [`RangeTo`](#rangeto) | A range with no start: `..b` or `..=b`. | ## `Ordering` ```kairo enum Ordering derives i8 ``` The result of a three-way comparison: what `a <=> b` evaluates to. The discriminants are -1, 0 and 1. The relational operators are lowered from `op <=>`: `a < b` becomes `((a.op<=>(b)) as i8) < 0`, with the original token compared against 0. **Example** ```kairo struct Version { var major: i32 } extend Version { fn op <=>(const self, const other: Version) -> Ordering { if self.major < other.major { return Ordering::Less } if self.major > other.major { return Ordering::Greater } return Ordering::Equal } } fn main() -> i32 { var a = Version { major: 1 } var b = Version { major: 2 } if (a <=> b) == Ordering::Less { return 0 } return 1 } ``` ### `Ordering.Less` ```kairo Less ``` The left operand orders before the right (-1). ### `Ordering.Equal` ```kairo Equal ``` The operands are equivalent (0). ### `Ordering.Greater` ```kairo Greater ``` The left operand orders after the right (1). ## `Range` ```kairo struct Range ``` A bounded range: `a..b` (exclusive end) and `a..=b` (inclusive end). Field order is evaluation order: RangeLowering builds a range as a designated initializer, and C++ evaluates those in declaration order, so `f()..g()` runs `f` first. Keep `begin` before `end`. A `for` loop over a range is lowered to a counting loop directly and never builds one. **Example** ```kairo fn main() -> i32 { var sum = 0 for i in 0..4 { sum += i } return sum - 6 } ``` ## `RangeFrom` ```kairo struct RangeFrom ``` A range with no end: `a..`, or `..` as `begin: 0` (a `RangeFrom`). Only valid as a subscript index, such as `v[2..]`. ## `RangeTo` ```kairo struct RangeTo ``` A range with no start: `..b` or `..=b`. Only valid as a subscript index, such as `v[..3]`. --- ## String URL: https://www.kairolang.org/docs/library/core/string/ The string type and its methods. ## `string` ```kairo class string ``` The UTF-8 string type. Immutable-by-default text with cheap literals and an owned, growable heap form. `data` is bytes and `len` counts them; `codepoints()` counts the Unicode codepoints they encode. A string literal is borrowed (points into static storage, `capacity() == 0`, no allocation); the first mutation moves it to the heap. Every string keeps a NUL after `len`, so `c_str()` is O(1). Copying an owned string is a deep copy; copying a borrowed one shares the static bytes. Indexing is by byte and is not bounds-checked. **Example** ```kairo var s = "héllo" s += " wörld" var bytes = s.length() var chars = s.codepoints() ``` --- ## Library reference URL: https://www.kairolang.org/docs/library/ Library reference pages are generated from the `///` doc comments in the library sources. | Page | Contents | | --- | --- | | [Core library](/docs/library/core/) | The implicit prelude: containers, strings, memory, errors, intrinsics. | | [Standard library](/docs/library/std/) | Explicitly imported modules: I/O, environment, memory, C types. | --- ## std::ctypes URL: https://www.kairolang.org/docs/library/std/ctypes/ Types for talking to C and C++ that Kairo's primitives do not cover. ## Contents | Name | Summary | | --- | --- | | [`c_char`](#c_char) | C and C++'s plain `char`: neither `i8` (`signed char`) nor `u8` (`unsigned char`), and signed or not as the target's C is. | | [`c_wchar`](#c_wchar) | C++'s `wchar_t`: 32 bits on most targets and 16 on Windows, signed or not as the target's C++ says. | | [`c_char16`](#c_char16) | C++'s `char16_t`: a UTF-16 code unit, 16 bits, unsigned. | | [`c_char8`](#c_char8) | C++'s `char8_t`: a UTF-8 code unit, 8 bits, unsigned, a type apart from `char` and `unsigned char` (`u8`). | ## `c_char` ```kairo type c_char = __builtin_c_char ``` C and C++'s plain `char`: neither `i8` (`signed char`) nor `u8` (`unsigned char`), and signed or not as the target's C is. A C string is `*const c_char`, which is `const char*` exactly, and a C `char` imports as this. A character, not a number: `as` converts it to and from the integers, and a literal takes it only in 0 through 127. ## `c_wchar` ```kairo type c_wchar = __builtin_c_wchar ``` C++'s `wchar_t`: 32 bits on most targets and 16 on Windows, signed or not as the target's C++ says. A C++ `wchar_t` imports as this, so `const wchar_t*` is `*const c_wchar` and `f(wchar_t)` is an overload apart from `f(int)`. Like `c_char`, a character, not a number: `as` converts it to and from the integers, and a literal takes it only in 0 through 0xFFFF, which fits it on every target. ## `c_char16` ```kairo type c_char16 = __builtin_c_char16 ``` C++'s `char16_t`: a UTF-16 code unit, 16 bits, unsigned. `as` to and from the integers; a literal takes it in 0 through 0xFFFF. ## `c_char8` ```kairo type c_char8 = __builtin_c_char8 ``` C++'s `char8_t`: a UTF-8 code unit, 8 bits, unsigned, a type apart from `char` and `unsigned char` (`u8`). `as` to and from the integers; a literal takes it in 0 through 255. --- ## std::env URL: https://www.kairolang.org/docs/library/std/env/ The process's view of its host. ## `exe_path` ```kairo fn exe_path() -> string ``` Returns this executable's absolute path as UTF-8. The path is '/'-separated on every host (Windows backslashes are converted) and has symlinks resolved where the OS resolves them (`/proc/self/exe` on Linux, `realpath` on macOS). It is a `string`, not a path type: the bytes are exactly what the OS reported. **Returns** the absolute path, or `""` when the OS cannot say **Example** ```kairo fn main() -> i32 { io::println(env::exe_path()) return 0 } ``` --- ## Standard library URL: https://www.kairolang.org/docs/library/std/ The standard library (`Lib/std`) is an ordinary Kairo library named `kairo::std`, spelled `std`. Nothing in it is implicit: write `import std::io` and call `io::println`. | Page | Contents | | --- | --- | | [std::io](/docs/library/std/io/) | Printing to standard output and standard error. | | [std::env](/docs/library/std/env/) | The process's view of its host. | | [std::mem](/docs/library/std/mem/) | Heap allocation, re-exported from the core library. | | [std::ctypes](/docs/library/std/ctypes/) | Types for talking to C and C++ that Kairo's primitives do not cover. | | [std::rt::Float8](/docs/library/std/rt-float8/) | The OCP FP8 formats F8E4M3 and F8E5M2 as library structs. | ## Root re-exports ```kairo pub import io ``` The `std::io` module: `print`, `println`, `eprint`, `eprintln` and `flush`. ```kairo pub import env ``` The `std::env` module: the process's view of its host (`exe_path`). ```kairo pub import ctypes::* ``` C and C++ character types (`c_char`, `c_wchar`, `c_char16`, `c_char8`), re-exported at the std root, so they are spelled `std::c_char` and so on. ```kairo pub import mem::* ``` The allocation API from `std::mem` (`create`, `destroy`, `AllocatorScope`, ...), re-exported at the std root. --- ## std::io URL: https://www.kairolang.org/docs/library/std/io/ Printing to standard output and standard error. ## Contents | Name | Summary | | --- | --- | | [`println`](#println) | Writes `s` followed by a newline to standard output. | | [`print`](#print) | Writes `s` to standard output without a trailing newline. | | [`eprintln`](#eprintln) | Writes `s` followed by a newline to standard error. | | [`eprint`](#eprint) | Writes `s` to standard error without a trailing newline. | | [`flush`](#flush) | Flushes the C runtime's stdio buffers on every stream. | ## `println` ```kairo fn println(const s: string) ``` Writes `s` followed by a newline to standard output. Unbuffered: the bytes are out when the call returns. A line shorter than 4096 bytes goes out in a single `write(2)`, so concurrent lines from different threads are not split. Longer lines take two writes (the text, then the newline). Write errors are ignored. **Parameters** - `s`: the text to write **Example** ```kairo fn main() -> i32 { io::println("hello") return 0 } ``` ## `print` ```kairo fn print(const s: string) ``` Writes `s` to standard output without a trailing newline. Unbuffered, like `println`. Write errors are ignored. **Parameters** - `s`: the text to write ## `eprintln` ```kairo fn eprintln(const s: string) ``` Writes `s` followed by a newline to standard error. Same single-write behaviour as `println`. Because neither stream is buffered, output to stdout and stderr interleaves in call order when both go to the same place (`2>&1`). **Parameters** - `s`: the text to write ## `eprint` ```kairo fn eprint(const s: string) ``` Writes `s` to standard error without a trailing newline. **Parameters** - `s`: the text to write ## `flush` ```kairo fn flush() ``` Flushes the C runtime's stdio buffers on every stream. Nothing in `std::io` buffers, so this exists only for ordering against C and C++ code that writes through stdio (`printf`, `fwrite(stdout)`, a C++ library). stdout is block-buffered when it is a pipe or a file, so bytes such code wrote before a print here can otherwise appear after it. Call `flush` at that boundary. --- ## std::mem URL: https://www.kairolang.org/docs/library/std/mem/ Heap allocation, re-exported from the core library. ## Re-exports ```kairo pub import builtin::base::alloc::{ Allocator, Resizer, Reallocator, ZeroAllocator, ScopedAllocator, FullAllocator, ScopedFullAllocator, Uninitialized, UninitializedSlice, uninitialized_from, AllocatorScope, Global, System, create, try_create, destroy, create_slice, destroy_slice, alloc_raw, free_raw, resize_raw, create_in, try_create_in, destroy_in, create_slice_in, destroy_slice_in, alloc_in, release_in, alloc_bytes, free_bytes, alloc_zeroed, resize_bytes, try_resize_in_place, realloc_by_copy, set_oom_handler, oom, } ``` Heap allocation API, re-exported from `builtin::base::alloc` so user code can write `std::create(...)` and `std::destroy(p)`. The functions without an `_in` suffix use the allocator in effect: the innermost open `AllocatorScope` on this thread, otherwise `Global`. The `*_in<.., A>` functions name the allocator `A` explicitly. Each re-exported item is documented in the core library reference. Re-exported items: [`Allocator`](/docs/library/core/memory-allocation/#allocator), [`Resizer`](/docs/library/core/memory-allocation/#resizer), [`Reallocator`](/docs/library/core/memory-allocation/#reallocator), [`ZeroAllocator`](/docs/library/core/memory-allocation/#zeroallocator), [`ScopedAllocator`](/docs/library/core/memory-allocation/#scopedallocator), [`FullAllocator`](/docs/library/core/memory-allocation/#fullallocator), [`ScopedFullAllocator`](/docs/library/core/memory-allocation/#scopedfullallocator), [`Uninitialized`](/docs/library/core/memory-allocation/#uninitialized), [`UninitializedSlice`](/docs/library/core/memory-allocation/#uninitializedslice), [`uninitialized_from`](/docs/library/core/memory-allocation/#uninitialized_from), `AllocatorScope`, `Global`, `System`, `create`, `try_create`, `destroy`, `create_slice`, `destroy_slice`, [`alloc_raw`](/docs/library/core/memory-allocation/#alloc_raw), [`free_raw`](/docs/library/core/memory-allocation/#free_raw), `resize_raw`, `create_in`, `try_create_in`, `destroy_in`, `create_slice_in`, `destroy_slice_in`, `alloc_in`, `release_in`, `alloc_bytes`, `free_bytes`, `alloc_zeroed`, `resize_bytes`, `try_resize_in_place`, [`realloc_by_copy`](/docs/library/core/memory-allocation/#realloc_by_copy), [`set_oom_handler`](/docs/library/core/memory-allocation/#set_oom_handler), [`oom`](/docs/library/core/memory-allocation/#oom). --- ## std::rt::Float8 URL: https://www.kairolang.org/docs/library/std/rt-float8/ The OCP FP8 formats F8E4M3 and F8E5M2 as library structs. ## Contents | Name | Summary | | --- | --- | | [`f32_bits`](#f32_bits) | Returns the IEEE binary32 bit pattern of `x`. | | [`bits_f32`](#bits_f32) | Returns the `f32` whose IEEE binary32 bit pattern is `b`. | | [`F8E4M3`](#f8e4m3) | OCP E4M3, finite-only. | | [`extend F8E4M3`](#extend-f8e4m3) | | | [`F8E5M2`](#f8e5m2) | OCP E5M2. 1 sign / 5 exponent / 2 mantissa, bias 15. IEEE-shaped: infinities AND NaN both present, unlike E4M3FN. | | [`extend F8E5M2`](#extend-f8e5m2) | | | [`extend F8E4M3`](#extend-f8e4m3-1) | | | [`extend F8E5M2`](#extend-f8e5m2-1) | | | [`verify_e4m3_roundtrip`](#verify_e4m3_roundtrip) | Every one of the 256 E4M3FN bit patterns survives bits -> f32 -> bits unchanged. | | [`verify_e5m2_roundtrip`](#verify_e5m2_roundtrip) | Checks that every non-NaN E5M2 bit pattern survives bits -> f32 -> bits unchanged. | | [`verify_e4m3_known`](#verify_e4m3_known) | Spot-check the values the OCP spec names explicitly. | | [`verify_e5m2_known`](#verify_e5m2_known) | Spot-checks the E5M2 encodings the OCP spec names: 0, 1, 2, max finite (57344), overflow to infinity, and -1. | ## `f32_bits` ```kairo fn f32_bits(x: f32) -> u32 ``` Returns the IEEE binary32 bit pattern of `x`. **Parameters** - `x`: the value **Notes** Currently a numeric `as` conversion, not a bit cast (see the TODO in the source), so it does not yet reinterpret the bits. ## `bits_f32` ```kairo fn bits_f32(b: u32) -> f32 ``` Returns the `f32` whose IEEE binary32 bit pattern is `b`. **Parameters** - `b`: the bit pattern **Notes** Currently a numeric `as` conversion, not a bit cast (see the TODO in the source). ## `F8E4M3` ```kairo struct F8E4M3 ``` OCP E4M3, finite-only. 1 sign / 4 exponent / 3 mantissa, bias 7. ```text Layout: S EEEE MMM Max finite: 448.0 (S.1111.110) Min normal: 2^-6 (S.0001.000) Min subnormal: 2^-9 (S.0000.001) NaN: S.1111.111 -- the ONLY NaN encoding Infinity: none. Overflow saturates to +/-448. Precision, not range. This is the weights-and-activations format. ``` ### `F8E4M3.BIAS` ```kairo static BIAS: i32 ``` Exponent bias. ### `F8E4M3.MANT` ```kairo static MANT: u32 ``` Number of mantissa bits. ### `F8E4M3.MAX_FIN` ```kairo static MAX_FIN: f32 ``` Largest finite magnitude, 448.0. ### `F8E4M3.NAN_BITS` ```kairo static NAN_BITS: u8 ``` Encoding of NaN. ### `F8E4M3.bits` ```kairo var bits: u8 ``` The raw 8-bit encoding: sign, 4 exponent bits, 3 mantissa bits. ## `extend F8E4M3` ```kairo extend F8E4M3 ``` ### `F8E4M3.F8E4M3` ```kairo fn F8E4M3(self) ``` Constructs a zero (all bits clear). ### `F8E4M3.F8E4M3` ```kairo fn F8E4M3(self, v: f32) ``` Constructs the nearest E4M3 value to `v`, rounding to nearest even; overflow saturates to +/-448. **Parameters** - `v`: the value to encode ### `F8E4M3.from_f32_bits` ```kairo fn from_f32_bits(v: f32) -> u8 ``` f32 -> E4M3FN, round-to-nearest-even, saturating. Saturation rather than infinity is the whole point of the FN form: there is no inf encoding, so a value past 448 becomes 448, and only a NaN input produces a NaN output. ### `F8E4M3.to_f32` ```kairo fn to_f32(self) -> f32 ``` E4M3FN -> f32. Always exact: every E4M3 value is representable in binary32, so no rounding occurs and no mode is needed. ### `F8E4M3.is_nan` ```kairo fn is_nan(self) -> bool ``` Returns whether the value is NaN: exponent and mantissa all ones, the only NaN encoding. ### `F8E4M3.is_zero` ```kairo fn is_zero(self) -> bool ``` Returns whether the value is zero (positive or negative). ### `F8E4M3.op as` ```kairo fn op as (self) -> f32 ``` Converts to `f32` with `as`; same as `to_f32`. ## `F8E5M2` ```kairo struct F8E5M2 ``` OCP E5M2. 1 sign / 5 exponent / 2 mantissa, bias 15. IEEE-shaped: infinities AND NaN both present, unlike E4M3FN. ```text Layout: S EEEEE MM Max finite: 57344.0 (S.11110.11) Min normal: 2^-14 Min subnormal: 2^-16 Inf: S.11111.00 NaN: S.11111.xx with xx != 00 Range, not precision. The exponent field is IDENTICAL to f16's, which is why f16 <-> e5m2 is a shift rather than a renormalization. This is the gradients format. ``` ### `F8E5M2.BIAS` ```kairo static BIAS: i32 ``` Exponent bias. ### `F8E5M2.MANT` ```kairo static MANT: u32 ``` Number of mantissa bits. ### `F8E5M2.MAX_FIN` ```kairo static MAX_FIN: f32 ``` Largest finite magnitude, 57344.0. ### `F8E5M2.INF_BITS` ```kairo static INF_BITS: u8 ``` Encoding of positive infinity. ### `F8E5M2.bits` ```kairo var bits: u8 ``` The raw 8-bit encoding: sign, 5 exponent bits, 2 mantissa bits. ## `extend F8E5M2` ```kairo extend F8E5M2 ``` ### `F8E5M2.F8E5M2` ```kairo fn F8E5M2(self) ``` Constructs a zero (all bits clear). ### `F8E5M2.F8E5M2` ```kairo fn F8E5M2(self, v: f32) ``` Constructs the nearest E5M2 value to `v`, rounding to nearest even; overflow gives an infinity. **Parameters** - `v`: the value to encode ### `F8E5M2.from_f32_bits` ```kairo fn from_f32_bits(v: f32) -> u8 ``` f32 -> E5M2, round-to-nearest-even. Overflow produces INFINITY here, not saturation -- E5M2 has inf encodings and IEEE semantics. ### `F8E5M2.to_f32` ```kairo fn to_f32(self) -> f32 ``` E5M2 -> f32. Always exact. ### `F8E5M2.is_nan` ```kairo fn is_nan(self) -> bool ``` Returns whether the value is a NaN: exponent all ones and a nonzero mantissa. ### `F8E5M2.is_inf` ```kairo fn is_inf(self) -> bool ``` Returns whether the value is an infinity (either sign). ### `F8E5M2.is_zero` ```kairo fn is_zero(self) -> bool ``` Returns whether the value is zero (positive or negative). ### `F8E5M2.op as` ```kairo fn op as (self) -> f32 ``` Converts to `f32` with `as`; same as `to_f32`. ## `extend F8E4M3` ```kairo extend F8E4M3 ``` ### `F8E4M3.op +` ```kairo fn op + (self, const rhs: F8E4M3) -> f32 ``` Adds after promoting both operands to `f32`; the result is an `f32`, not an `F8E4M3`. Arithmetic returns `f32` on purpose: narrowing back to fp8 after every operation would round at each step. Narrow once, at the final assignment. ### `F8E4M3.op -` ```kairo fn op - (self, const rhs: F8E4M3) -> f32 ``` Subtracts after promoting both operands to `f32`; the result is an `f32`, not an `F8E4M3`. ### `F8E4M3.op *` ```kairo fn op * (self, const rhs: F8E4M3) -> f32 ``` Multiplies after promoting both operands to `f32`; the result is an `f32`, not an `F8E4M3`. ### `F8E4M3.op /` ```kairo fn op / (self, const rhs: F8E4M3) -> f32 ``` Divides after promoting both operands to `f32`; the result is an `f32`, not an `F8E4M3`. ### `F8E4M3.op ==` ```kairo fn op == (self, const rhs: F8E4M3) -> bool ``` Bitwise equality, NOT numeric. Two encodings of the same value do not exist in E4M3FN, so this differs from numeric equality only at NaN (which compares unequal to itself numerically) and signed zero (-0.0 == +0.0 numerically, different bits here). Compare through to\_f32() when IEEE comparison semantics are what you want. ## `extend F8E5M2` ```kairo extend F8E5M2 ``` ### `F8E5M2.op +` ```kairo fn op + (self, const rhs: F8E5M2) -> f32 ``` Adds after promoting both operands to `f32`; the result is an `f32`, not an `F8E5M2`. Arithmetic returns `f32` on purpose: narrowing back to fp8 after every operation would round at each step. Narrow once, at the final assignment. ### `F8E5M2.op -` ```kairo fn op - (self, const rhs: F8E5M2) -> f32 ``` Subtracts after promoting both operands to `f32`; the result is an `f32`, not an `F8E5M2`. ### `F8E5M2.op *` ```kairo fn op * (self, const rhs: F8E5M2) -> f32 ``` Multiplies after promoting both operands to `f32`; the result is an `f32`, not an `F8E5M2`. ### `F8E5M2.op /` ```kairo fn op / (self, const rhs: F8E5M2) -> f32 ``` Divides after promoting both operands to `f32`; the result is an `f32`, not an `F8E5M2`. ### `F8E5M2.op ==` ```kairo fn op == (self, const rhs: F8E5M2) -> bool ``` Bitwise equality of the encodings, not IEEE numeric equality: a NaN equals an identical NaN here, and `-0.0` differs from `+0.0`. Convert with `to_f32` for numeric comparison. ## `verify_e4m3_roundtrip` ```kairo fn verify_e4m3_roundtrip() -> bool ``` Every one of the 256 E4M3FN bit patterns survives bits -> f32 -> bits unchanged. ```text This is the half of the exhaustive test you can run WITHOUT APFloat. It proves the two conversions are mutual inverses; it does NOT prove either matches the OCP spec. For that, run the same 256 patterns through APFloat's semFloat8E4M3FN in the compiler and diff. Both halves are needed: mutually-inverse conversions can still both be wrong in the same direction. ``` ## `verify_e5m2_roundtrip` ```kairo fn verify_e5m2_roundtrip() -> bool ``` Checks that every non-NaN E5M2 bit pattern survives bits -> f32 -> bits unchanged. NaN payloads are skipped because they are not preserved. **Returns** `true` when every non-NaN encoding round-trips. ## `verify_e4m3_known` ```kairo fn verify_e4m3_known() -> bool ``` Spot-check the values the OCP spec names explicitly. Cheap, and it catches a bias or shift that is off by one -- which round-trip testing alone cannot, since a consistent off-by-one is still self-inverse. ## `verify_e5m2_known` ```kairo fn verify_e5m2_known() -> bool ``` Spot-checks the E5M2 encodings the OCP spec names: 0, 1, 2, max finite (57344), overflow to infinity, and -1. **Returns** `true` when every spot-check encodes to the expected bit pattern. --- ======================================================================== SECTION: BLOG ======================================================================== ## Kairo Benchmarks: 15 Programs vs C++ and Rust URL: https://www.kairolang.org/blog/first-benchmarks/ # Kairo Benchmarks: 15 Programs vs C++ and Rust Fifteen programs written in Kairo, C++ and Rust, plus one that measures a Kairo-only feature, timed on one machine. All results are below, losses included. One fact frames everything: Kairo compiles through Clang and LLVM. Kairo's frontend parses and type-checks the source itself, and its own Clang/LLVM 22 build is the backend. On plain arithmetic, Kairo, Clang and rustc therefore share an optimizer and a code generator, and a gap between them comes from what each frontend hands LLVM, not from the backend. Large Kairo wins come from the runtime (its mimalloc heap) or from how a language feature is lowered. Summary: on 9 of 15 programs Kairo is within 10% of the best C++ or Rust build. It's well ahead where the heap dominates, ahead on generators, closures and the interpreter loop, and behind on nbody and, against GCC only, on virtual dispatch. ## The toolchains - **kairo**: the Kairo compiler at `-O3`. - **gcc** and **clang**: the C++ version built by the system GCC and Clang. - **kcc**: the *same* C++ source built by Kairo's C++ driver. It links Kairo's runtime, including the [mimalloc](https://github.com/microsoft/mimalloc) heap that Kairo's global allocator uses. kcc is the control: when kcc closes a gap between Kairo and plain C++, the runtime caused the gap, not the language. - **rust**: the Rust version built by `rustc`. Kairo is red, kcc is dimmed red, the rest are gray. Every row is labeled. ## Results at a glance Kairo against the fastest of the other four toolchains on each benchmark. Bars right of center mean Kairo is faster. The scale is logarithmic, so 2× faster and 2× slower have the same length. Kairo has the fastest median on 9 of 15 and loses 6. Nine of the 15 are within 10% either way; with eight runs, treat those as ties. Each per-benchmark chart shows the median of eight runs as a bar and the fastest run as a tick. The right column is speed relative to Clang. Hover or focus a row for exact numbers. ## Numeric loops No allocation. These measure the code each frontend gives LLVM (or GCC) for arithmetic and array loops. nbody: five bodies, 30 million steps, `f64` math over a fixed array of structs. Rust is 1.88× faster than Clang. Kairo is 1.18× faster than Clang and 6% slower than GCC. fannkuch: permutations and prefix reversals over a 16-element integer array. All five are within 11%; Clang leads Kairo by under 1%. One Kairo run took 1.189 s, 26% under its median. Every other toolchain's fastest run is within 1% of its median. The median is the number. spectral (spectral norm, `f64`), wideint (64-bit Miller–Rabin with a 128-bit multiply-mod) and slices (sum, dot product and filter over a million `f64`s) are ties. The spreads are 7%, 6% and 3%. This is the expected result when three frontends hand LLVM equivalent loops. ## Memory The kcc column matters most here. btree builds and frees millions of small binary trees, one heap allocation per node. Kairo is 2.7× faster than Clang, and most of that is the allocator. `@create` goes to the [global allocator](/docs/language/allocators/#global-allocator), which is mimalloc's small-object path; the GCC, Clang and Rust builds use glibc `malloc`. kcc separates the two effects. The same C++ linked against Kairo's runtime drops from 5.3 s to 3.3 s, so most of the gap is the heap. Kairo is still 1.5× faster than kcc. Part of that is the free path: Kairo frees with the size and alignment it already knows (`destroy` calls mimalloc's sized small-object free directly, 3 instructions on the hot path), while C++ `delete` goes through `operator delete` to an unsized `free`, which has to look up the block's page first. alloc creates and destroys one 16-byte object 50 million times; the C++ is built once with `new`/`delete` and once with `malloc`/`free`. It's the cleanest allocator comparison in the set. Kairo and kcc-malloc are within 4% of each other and 1.6× faster than glibc `malloc`. A Kairo `create`/`destroy` pair is 49 instructions, against 146 for glibc `malloc`/`free` and 157 for `new`/`delete`. Through glibc, `new`/`delete` costs a third more than `malloc`/`free`; through Kairo's runtime, 7% more. nullable builds a 10-million-node linked list with nullable `next` links, walks and searches it 50 times, then frees it. kcc is within 4% of Kairo, and both are 1.5× ahead of the rest, so most of this one is the heap. The remaining few percent is the free path, as in btree. Kairo's `@destroy` frees each node with the size and alignment it already knows, through the runtime's sized free. The C++ list is a chain of `std::unique_ptr`: in kcc's build, `unique_ptr::reset` stays an out-of-line call (seven call sites in `main`), and each node goes through `operator delete` to an unsized `free`. ## Abstractions Stored closures, virtual calls, generators, generic code, and an interpreter loop over `match`. closures calls three capturing callbacks stored in an array, a billion times. All three languages use a type-erased callable: Kairo's `fn` values, Rust's `Box`, and `std::function` in C++, which is what C++ uses when a callback has to be stored. Kairo is 6% faster than Rust; `std::function` is 3.4× slower with Clang and 7.3× slower with GCC. A C++ template that takes the lambda directly would inline, but then the callback isn't stored. dispatch makes virtual calls over a mixed array of 1,024 shapes. GCC is 2.5× faster than Kairo, Clang and Rust, which all finish in 2.03 s. Kairo matching Clang here is expected, since Kairo classes share the C++ vtable ABI and their virtual calls go through the same backend as Clang's. GCC is the outlier because of speculative devirtualization: the derived classes are `final`, so GCC knows the complete set of three overriders and can replace the indirect call with type checks and inlined bodies. gen is a three-stage pipeline of nested generators summing a billion values: `-> yield T` in Kairo, C++20 coroutines in C++, iterator adapters in Rust. Kairo generators are built on the same coroutine machinery as C++20 coroutines, so Kairo and the Clang row share it. In both, Clang elides the coroutine frames' heap allocations and inlines the whole pipeline into the caller's loop. GCC doesn't perform that elision, which is why its row is 6.6× slower. Kairo is 1.2× ahead of Clang and 1.7× ahead of Rust. The difference between Kairo and Clang is Kairo's promise type and how `yield` is lowered. Like fannkuch, gen has one outlier run (0.451 s, 20% under the median). gsort is a hand-written generic sort over a comparison bound, with closures for the key. All five are within 3%: Kairo generics are monomorphized like C++ templates and Rust generics, so an interface bound adds nothing at runtime. gsort-lib swaps in each library's sort for reference. Rust's `sort_unstable` (pattern-defeating quicksort) is 2.9× faster than libstdc++'s `std::sort` (introsort), and that's the target for Kairo's. interp runs a small bytecode loop: an enum with payloads and `match` in Kairo and Rust, a tagged struct and `switch` in C++. Kairo and Rust tie, and both are at least 1.25× faster than every C++ build. Since Kairo and the Clang row share a backend, the difference is in the representation Kairo chooses for its enum and `match`, not in code generation. ## Errors and formatting Kairo's two largest wins. errpath makes 500 million calls, 1% of which fail: `panic`/`try`/`catch` in Kairo, exceptions in C++, `Result` in Rust. Kairo is 10× faster than C++ exceptions and 2.5× faster than Rust's `Result`. A Kairo `panic` is a returned value, not an unwind, so LLVM treats the failure path like any other branch. In the Kairo build `parse` and `fail` are inlined into the loop, `x % 100 == 0` becomes a multiply-and-rotate test, `x * 3` becomes a running `+= 3`, and no error value is ever built. Rust's `Result` gets the same treatment, so the gap to Rust is loop shape, not error handling. Rust's `1..=n` adds an exhaustion check to every iteration, and LLVM computes both outcomes and picks one with `cmov` instead of branching: 18 instructions per iteration against Kairo's 13 on the success path, and Kairo's branch is predicted right 99% of the time. The C++ builds pay for 5 million `throw`s, each one allocating the exception (`__cxa_allocate_exception`) and unwinding to the `catch`. The kcc row is a bug in kcc's link, not a cost of exceptions: the same code is 3.5× slower than GCC's build. fmt converts 10 million `f64`s and 10 million `i64`s to text: f-strings in Kairo, `std::to_chars` in C++, `write!` in Rust. Kairo is 2.2× faster than kcc and 3.0× faster than Clang. Kairo's f-strings format into a buffer with 128 bytes of inline storage, so short results never touch the heap, and floats with no format spec are written directly into that buffer. ## Scoped allocators (Kairo only) scopes has no C++ or Rust version; it measures Kairo's [scoped allocator](/docs/language/allocators/#scoped-allocator) stack. It opens `DEPTH` nested allocator scopes, then runs 50 million operations at the innermost level. Times per operation: | Operation | depth 1 | depth 16 | depth 64 | |---|---:|---:|---:| | allocate + free in the innermost scope | 2.5 ns | 2.5 ns | 2.7 ns | | free a global block inside the scopes | 3.1 ns | 3.1 ns | 3.1 ns | | free a block from the outermost scope | 1.4 ns | 7.2 ns | 21.6 ns | | open and close one more scope | 6.2 ns | 6.6 ns | 6.6 ns | `free` has to find which open scope, if any, owns an address. The scope stack keeps a bounding box over every open scope's memory, so an address outside it (a global block) is rejected with one range check, at any depth. An address inside the box is found by scanning the open scopes from innermost outward, so freeing a block that belongs to the outermost scope costs 0.3 to 0.4 ns for every scope above it: a few nanoseconds at realistic depths, 22 ns at 64. ## Method The code is in [`Tests/bench`](https://github.com/kairolang/kairo/tree/main/Tests/bench). Each program is written the way that language's code is normally written; the README lists what each version uses (`std::function` vs `Box`, exceptions vs `Result`, and so on). None is tuned for a particular compiler. - **Builds:** `-O3` for Kairo, GCC, Clang and kcc (`-std=c++20` for C++); `-C opt-level=3 -C codegen-units=1` for Rust. No `-march=native`, LTO or PGO. - **Timing:** `bench-seq.fish 8` builds and times one benchmark at a time. Toolchains are interleaved within a benchmark (each binary once, then each again) for eight rounds, so a background-load swing hits all of them. - **Measured:** wall-clock time of the whole process, startup and output included. - **Correctness:** each benchmark prints a checksum; the harness checks every toolchain prints the same one. All sixteen agreed. - **Machine:** AMD Ryzen 9 7900X (12 cores / 24 threads), Linux 7.2.11-zen1, GCC 16.2.1, Clang 23.1.3, rustc 1.98.1, Kairo at commit `f66b5057` (Clang/LLVM 22 backend). ## Limits - Eight runs. Most medians are within 1 to 2% of the fastest run (Kairo's fannkuch and gen are the exceptions). Don't rank differences under 5%. - Each language uses its default allocator and standard library. That's why btree, alloc and nullable look the way they do, and why kcc is in the table. - Some Kairo sources work around open compiler bugs: `gsort.k` wraps `i64` in a `Key` struct, `gen.k` yields only named variables, and `spectral.k` avoids one parameter name. The README lists them. - Single-threaded micro-benchmarks. No threads, I/O, or large programs. If you run the suite on other hardware, especially ARM, send me the results. --- ## How AI Is Used in Kairo URL: https://www.kairolang.org/blog/how-ai-is-used-in-kairo/ # AI Workflow/Usage in Kairo Kairo is being built by a small core team of university students. I (Dhruvan) do most of the compiler and language design work, so the AI usage described here is mine. I want to be upfront about where and how AI is used in this project. This was originally a snapshot as of May 2026. My usage has changed since then, so this post was updated in October 2026. See [Integration Work in the Compiler](#integration-work-in-the-compiler-october-2026-update), [Tests](#tests), [Audits](#audits), and [Git Commit Messages](#git-commit-messages) for what changed and why. ## Why I'm Writing This I know the systems programming community has a lot of opinions about AI in development. I'd rather be straightforward about exactly where it's used than have someone find out later and wonder what else I didn't tell them. ## What Is Not AI-Assisted To be clear: the language design, compiler architecture (Stage 0 and Stage 1), memory model, type system, ABI decisions, codegen pipeline, and build system are all designed by me. The core logic is written by hand. The one exception is mechanical integration work in Stage 1, explained [below](#integration-work-in-the-compiler-october-2026-update). ## Compiler The compiler is hand-written. The lexer, parser, AST, arena allocator, diagnostics engine, preprocessor, and codegen pipeline were all written by hand. Stage 0 contains no AI-generated code. The original version of this post said the same was true for Stage 1. That's no longer accurate. AI is now used in Stage 1, but not the way most people would assume. It doesn't design or write compiler logic; it does plumbing. Details in the next section. I don't use inline code completion for compiler code. Kairo is a new language, completion models are bad at predicting it, and the code I'm writing is novel logic, not boilerplate. There's nothing for autocomplete to autocomplete. ## Integration Work in the Compiler (October 2026 Update) The Stage 1 compiler has passed 130,000 lines of Kairo, and with two people maintaining it, sweeping changes have become a real problem. A concrete example: say primitive types are hardcoded in seven different places across the compiler, and I want to pull that logic into a single shared helper. Writing the helper is the easy part, and I still do that myself. The hard part is the integration: finding every call site and every slightly different copy of the same logic, and rewiring all of it to the helper without breaking anything. In a mature language, that's a few minutes of work. Your editor's LSP gives you find-all-references, go-to-definition, and rename, and the refactor is mostly mechanical. Kairo doesn't have that yet. Stage 1 is compiled by Stage 0, and Stage 0's tooling gives me error squiggles and not much else. I added a form of jump-to-definition, but it guesses rather than actually resolving symbols, and it's right about half the time. Without real tooling, a change that should take minutes takes days of grepping and manually tracing code across 130k lines. That gets old fast. So that's where Claude Code comes in. The split looks like this: - **I do:** the design, the decision to make the change, and the new code itself (the helper, the new abstraction, the actual logic). - **Claude Code does:** the plumbing. It finds the places that need to change and rewires them to the new code. - **Then I review everything.** Every change it makes is read, checked against what I intended, and tested before it lands. Anything that's wrong gets fixed or thrown out. It isn't writing the compiler. It's doing the job an LSP and a refactoring tool would normally do, which Kairo doesn't have yet. Once Stage 1 has a proper LSP, I expect most of this to go back to being done by hand. ## Tests Most of the compiler's lit tests are written by AI (Claude Code), under a strict process. The rule behind all of it: I decide what correct behavior is. The AI only expresses that behavior as a test. 1. **Ask first.** Before writing a test, it asks me what the expected behavior is, unless it's 100% sure that's the behavior the compiler is meant to have. "Probably" doesn't count. 2. **Get the test right.** It can iterate on the test itself: write it, watch it fail, read the diagnostic, and fix the test. The compiler is stable enough and the diagnostics are clear enough for that loop to work. This is about getting the Kairo source and the lit/FileCheck structure right, not about changing what the test expects. 3. **Check it against my criteria.** Once the structure is in place, it runs the test through lit. I have strict criteria for what a test should look like, and if anything seems off, it flags it and stops. 4. **Pass or stop.** If the test passes, it moves on to the next one. If it fails, it stops and brings it to me. It never works around the compiler to make a test pass. A failing test is either a compiler bug or a wrong expectation, and deciding which is my call. That last rule is the important one. The usual way AI-written tests go wrong is by quietly encoding a bug as expected behavior. Stopping on every failure is what prevents that. ## Audits I also use Claude Code, with subagents running in parallel, for codebase-wide audits. For example, checking every CLI flag against what the compiler actually does with it. Every finding points at a file and line, so I can verify it. I review the findings and decide what gets fixed. The audit reports stay internal, but the tests that come out of them (like the CLI tests in `Tests/CLI/`) are public, and they're written under the same process as above: anything flagged as a bug doesn't get a test that treats the current behavior as correct. Doing this by hand would take weeks of tracing. With subagents it takes minutes, and my time goes into reviewing the findings instead of finding them. ## Debugging When I hit deep bugs in the compiler, I use Claude as a debugging partner. Stage 0 compiles Kairo through C++, so every LLDB symbol is a mangled C++ name, and reading them is miserable. My process: I walk through the trace in LLDB and try to find and fix the issue myself. If, and only if, I can't, I give Claude the output with the relevant source context. It tells me what commands to run or what state to look at, I run them, feed the results back, and we figure out what's really going on. Then I write the fix. Recent example: empty source files crashed the compiler. The debugging session traced it to a `file.size() - 1` on a zero-length file. The subtraction underflowed a `usize` into `usize(-1)`, which blew out everything downstream, nulled a buffer, and segfaulted in a completely unrelated file that I thought was isolated. Nothing about the crash pointed back to the underflow. Fixing it took the compiler from crashing to working but slow (a spin-wait), which turned out to be another underflow, this time in `SourceLineTable`. After both fixes, it went to immediate execution. The bug itself was trivial. Finding it through mangled symbols and threaded execution was not. AI helped me find it faster. It did not write the fix. AI is a second pair of eyes on diagnostic output, not a code author. ## Doc Comments Within the Compiler Codebase This is the one place I use GitHub Copilot: drafting doc comments in the compiler source. The code itself is hand-written, but the prose explaining what it does is AI-assisted, and I review it. Honestly, it means far more of the codebase is documented than it would be if I wrote every comment myself, and future-me (and new contributors) will be grateful for that. I plan to replace these with hand-written comments eventually, ideally in Stage 2. ## Docs Every page on kairolang.org started as a raw technical dump: syntax examples, ABI lowering information, generated C++ output, invariants, edge cases. The kind of notes that make perfect sense to me and nobody else. I handed those dumps to Claude to turn them into something a human other than me can actually read. It structures sections, writes prose transitions, formats tables and code blocks, and smooths out phrasing. I do all the technical writing, review every page for correctness, and change anything that misrepresents the language semantics. The technical substance (the language itself, how it works, the invariants) is mine. AI helps with the prose. If you see a technical error in the docs, that's on me. ## Website I'm not a web developer. Web dev has never interested me, and I'm not going to pretend otherwise. Astro, CSS, HTML, and JS are not languages I work with. The kairolang.org website was built by Claude. I explained the theme, the layout, what the site should include, and what it's for. The AI wrote the Astro components, CSS, and front-end code. I looked over the output and corrected errors wherever I found them. The website source is publicly available at [github.com/kairolang/kairo-web](https://github.com/kairolang/kairo-web). ## Git Commit Messages Commit messages are AI-written. The commits are mine; the messages are generated from my diffs. I originally used GitLens AI for this. I still use it, but I now also use Claude Code, because GitLens gives an overview and Claude Code gives a detailed, exact message: what changed, where, and why. I keep commits small enough to stay bisectable, and the message records enough detail that when someone else is tracing a bug through the history, the log tells them what each commit actually did without having to reverse-engineer the diff. The verbosity is on purpose. ## LSP and VS Code Extension (Stage 0) The Stage 0 compiler is written entirely by hand, but the LSP integration and VS Code extension were AI-assisted. I implemented a pseudo-LSP mode in the compiler: pass it `--lsp-mode` and it returns diagnostics as JSON. Then I gave Claude the LSP protocol spec, and it built the Python (pygls) server that connects the compiler output to VS Code, plus the extension code to wire it up. It's held together with tape, but it unblocked Stage 1 development without me spending weeks on the LSP protocol and the VS Code extension API. The Stage 1 LSP server and extension will be written from scratch. If you have questions, open an issue on [GitHub](https://github.com/kairolang/kairo/issues). --- ## Pointers Without References: Kairo's Pointer Model URL: https://www.kairolang.org/blog/kairo pointer-model/ # Pointers Without References: Kairo's Pointer Model C++ has pointers and references. Rust has raw pointers, references, mutable references, and smart pointers. Go has pointers but no pointer arithmetic. Every systems language ends up with some combination of indirection types, each with its own rules, its own syntax, and its own mental overhead. Kairo has one: `*T`. One pointer type, 8 bytes, non-null, with full compile-time safety analysis. No references. No borrow syntax. No lifetime annotations. ## The Problem with Splitting Pointers and References C++ has `T*` and `T&`. In theory, references are "safe pointers that can't be null and can't be reseated." In practice, you can absolutely create dangling references, null references through casts, and references to dead stack frames. The compiler doesn't stop you. The "safety" is convention, not enforcement. Rust fixed the enforcement problem. `&T` and `&mut T` are genuinely safe. The borrow checker proves at compile time that references don't dangle and that mutable access is exclusive. But the cost is complexity. You now have `&T`, `&mut T`, `*const T`, `*mut T`, `Box`, `Rc`, `Arc`, `Weak`, and lifetime annotations (`'a`) to connect them all. The programmer has to choose the right indirection type at every point and annotate lifetimes when the compiler can't infer them. This is a real barrier. Not a skill issue, a complexity issue. Lifetime annotations are the number one complaint from developers learning Rust, and they exist because the borrow checker is function-local: it needs the programmer to describe how lifetimes relate across function boundaries. ## Kairo's Answer: One Pointer, Compile-Time Safety `*T` is the only safe pointer type in Kairo. It's 8 bytes, just an address, same size as a C pointer. No runtime metadata, no fat overhead. Non-null by construction. ```kairo var x = 42 var p: *i32 = &x *p = 100 // guaranteed valid, no null check needed var bad: *i32 = &null // compile error: *T is non-null ``` The safety comes from AMT (Automatic Memory Tracking), which performs whole-program analysis at compile time. AMT tracks every pointer's lifetime, provenance, and usage across the entire program, not just within a single function. It knows where a pointer was created, what it points to, whether the target is still alive, and whether any aliasing violations exist. Because AMT sees the whole program, it doesn't need the programmer to annotate lifetimes. There are no `'a` parameters, no borrow syntax, no distinction between "I'm borrowing this" and "I'm pointing to this." You write `*T`, and the compiler figures out the rest. ## AMT Auto-Promotion: Debug vs Release AMT can automatically promote a `*T` to a smart pointer (`std::Unique`, `std::Shared`, or `std::Weak<*T>`) when it determines the pointer needs to outlive its original scope: ```kairo fn make_config() -> *Config { var cfg = @create Config(8080) return cfg } ``` **In debug builds,** AMT warns and promotes `cfg` to whichever smart pointer fits the usage pattern. This keeps you moving; you don't have to think about ownership while you're iterating on logic. **In release builds,** AMT does not auto-promote. Instead, it emits a compile error that tells you exactly where promotion would have happened, what smart pointer type is needed, and how to fix it: ``` error[AMT]: pointer 'cfg' escapes its scope and requires ownership annotation --> src/config.k:3:12 3 | return cfg | ^^^ escapes function scope note: AMT would promote to: std::Unique 2 | var cfg: std::Unique = @create Config(8080) fix: annotate the type explicitly ``` This is deliberate. Debug builds are for getting things working. Release builds are for getting things right. If your code is going to ship, the ownership model should be explicit in the source, not inferred by the compiler behind your back. If AMT can't find any safe promotion path, debug or release, it's a hard compile error in both modes. The program doesn't compile until the ownership is unambiguous. ## Nullable Pointers Are Opt-In `*T` can't be null. If you need a pointer that might not exist, you opt into nullability explicitly with `*T?`, which wraps the pointer in Kairo's standard `Nullable` system: ```kairo var p: *i32? = find_pointer() if p? { std::println(*p) // compiler verified non-null } var val = p ?? &fallback // null coalescing var forced = unwrap!(p) // panics if null ``` Null pointer dereferences are impossible on `*T`: the type can't hold null, so there's nothing to check. On `*T?`, the compiler forces you to handle the null case before you can dereference. Null bugs become compile errors. For raw C-style pointers with no safety and no tracking, there's `unsafe *T`: ```kairo var raw: unsafe *i32 = &null // nullable, no checks, no tracking ``` Three types, clear roles: | Type | Null | Tracked | Use case | |---|---|---|---| | `*T` | No | Yes (AMT) | Default, safe, non-null | | `*T?` | Yes | Yes (AMT) | Optional pointer, might not exist | | `unsafe *T` | Yes | No | FFI, hardware, custom allocators | ## Why Not References? Because they don't add anything, and they hide information. In C++, references exist partly for safety (non-null, can't be reseated) and partly for convenience: pass-by-reference avoids copies, auto-deref hides the indirection, and the syntax is cleaner than pointer syntax. In Rust, references exist because the borrow checker needs syntactic markers to distinguish borrows from ownership. Kairo rejects the convenience argument. A reference that auto-dereferences abstracts away the fact that you're working through a pointer. That abstraction hides something significant: you are accessing memory you don't own, through an address that points somewhere else. Kairo's philosophy is explicitness at the syntax level. If you're using a pointer, the code should look like you're using a pointer. The performance argument, "references avoid copies", is handled by the compiler, not by a language feature. Kairo has an optimization pass that automatically promotes value parameters to pointer parameters when the type is larger than a pointer: ```kairo fn process(data: string) { std::println(data) } ``` If the compiler sees that `data` is larger than 8 bytes and you don't alias it, modify it, mark it `volatile`, or use the function in an `async` context, it silently rewrites the parameter to `data: *const string` and inserts dereferences where needed. You get pass-by-pointer performance with value semantics in the source code: no reference type required, no syntax change, no programmer decision. The safety argument is handled by AMT. `*T` is already non-null and lifetime-tracked. A separate `&T` would be a second spelling of the same guarantee. Three reasons languages have references. Kairo handles all three without adding a type. ## The `const` Model Mutability is controlled by `const`, not by pointer type. `const` binds left-to-right, one level at a time: ```kairo var p: *i32 = &x // mutable pointer, mutable target var p: *const i32 = &x // mutable pointer, const target const p: *i32 = &x // const pointer, mutable target const p: *const i32 = &x // const pointer, const target ``` No `&T` vs `&mut T`. No `const T&` vs `T&`. One pointer type, one const rule, applied uniformly. The `const` applies to the thing immediately to its right. No C++ ambiguity about whether the pointer or the pointee is const. ## What This Costs **Whole-program analysis is expensive.** AMT needs to see the entire program to make its safety guarantees. This is more expensive than Rust's function-local borrow checking. Kairo mitigates this with `.amt` artifacts, precomputed ownership summaries for each translation unit that AMT can consume without re-analyzing dependencies. But it's still more work than a local analysis. **No lifetime polymorphism.** Rust's lifetime parameters let you write functions that are generic over lifetimes: the function works regardless of how long the references live, as long as the constraints are satisfied. Kairo doesn't have this. AMT analyzes concrete lifetimes, not abstract ones. In practice, this hasn't been a limitation because AMT's auto-promotion handles the cases where Rust would need lifetime parameters, but it's a theoretical expressiveness gap. **Learning curve for C++ devs.** C++ developers expect to write `T&` for references. Kairo says "just use `*T`." The pointer syntax carries baggage: C++ devs associate `*` with unsafety. The reality is that Kairo's `*T` is safer than C++'s `T&`, but the syntax doesn't signal that. This is a communication problem, not a technical one. ## The Design Principle Kairo's pointer model follows the same principle as `match` replacing `switch`: if you can get the same safety guarantees with less complexity, do it. References are a patch for unsafe pointers. If the pointer is already safe, you don't need the patch. One pointer type. Compile-time safety. Zero runtime cost. No annotations. --- ## Why Kairo Has match Instead of switch URL: https://www.kairolang.org/blog/match-replacing-switch/ # Why Kairo Replaced `switch` With `match` Kairo doesn't have `switch`. It has `match`. This wasn't a cosmetic rename. It's a different construct with different semantics that eliminates an entire class of bugs that `switch` has carried forward for fifty years. ## What's Wrong with `switch` The core problem with C-style `switch` is fall-through. Every case falls into the next unless you explicitly `break`. This is the default behavior, and it's almost never what you want. ```cpp // C++ switch (status) { case 200: handle_ok(); // forgot break falls through to 404 handling case 404: handle_not_found(); break; } ``` This is a real bug that has shipped in real software for decades. The "fix" is discipline: remember to write `break` at the end of every case, every time, forever. Languages have been patching around this with warnings, linters, and attributes like `[[fallthrough]]`, all to compensate for a default that should never have been the default. Kairo's answer is simple: don't have fall-through at all. Each case in a `match` is an isolated block. There's nothing to fall through to, so there's nothing to forget. ```kairo match status_code { case 200 { handle_ok() } case 404 { handle_not_found() } case 500 { handle_server_error() } default { handle_unknown() } } ``` If you want multiple values to hit the same code, list them: ```kairo match priority { case 1, 2, 3 { handle_high() } case 4, 5 { handle_medium() } default { handle_low() } } ``` No fall-through. No `break`. No ambiguity. ## Exhaustiveness Checking `switch` in C++ doesn't care if you miss a case. You can switch on an enum, forget a variant, and the compiler says nothing (unless you turn on specific warnings, and even then it's not an error). `match` in Kairo enforces exhaustiveness. The compiler verifies every possible value is handled: | Type | Rule | |---|---| | Plain enum | All variants covered, or `default` present | | ADT enum | All variants covered, or `default` present | | Booleans | `true` + `false` covers it | | Integers / strings | `default` required | Add a variant to an enum and every `match` on that enum becomes a compile error until you handle the new case. The compiler catches it, not your users. ## ADT Destructuring This is where `match` earns its name. Kairo has ADT enums, variants that carry structured payloads: ```kairo enum ParseResult { Success { value: T, bytes_consumed: i32 }, Error { message: string, position: i32 }, EndOfInput, } ``` `match` destructures these directly. You bind payload fields with `var` or `const` and the compiler checks that your field names match the declaration: ```kairo match result { case .Success(var value, var bytes_consumed) { std::println(f"parsed {value} from {bytes_consumed} bytes") } case .Error(const message, const position) { std::println(f"error at {position}: {message}") } case .EndOfInput { std::println("nothing left to parse") } } ``` You can omit fields you don't need; exhaustive field extraction isn't required. And you can add `where` guards for conditional matching: ```kairo match result { case .Success(var value) where value > 0 { process_positive(value) } case .Success(var value) { process_non_positive(value) } default { } } ``` Try doing this with `switch`. You can't: `switch` dispatches on a single value. Destructuring a tagged union in C++ means pulling out the tag, switching on it, then manually casting or accessing the payload. It's verbose, error-prone, and the compiler can't verify you got the fields right. ## `match` as an Expression `match` produces a value. Every branch returns the same type, and the compiler enforces it: ```kairo var label = match level { case .Debug => "debug" case .Info => "info" case .Warning => "warning" case .Error => "error" case .Fatal => "fatal" } ``` This works with ranges too: ```kairo var severity = match code { case 200..=299 => 0 case 400..=499 => 1 case 500..=599 => 2 default => -1 } ``` No need for a ternary operator or a separate variable initialized before the switch. ## Struct Matching `match` isn't limited to enums. Structs can be destructured the same way, combined with `where` guards: ```kairo match response { case Response(var status, var body) where status == 200 { process(body) } case Response(var status) where status >= 400 { log_error(f"HTTP {status}") } default { } } ``` ## What About `break` in Loops? Since `match` cases don't fall through, there's nothing to `break` out of inside a match. So when a `match` is nested inside a loop, `break` does what you'd expect and exits the loop: ```kairo for item in items { match item.kind { case .Sentinel { break // exits the for loop } case .Data(var payload) { process(payload) } default { } } } ``` No more wondering whether `break` exits the switch or the loop. ## The Design Principle Kairo's general approach is: if the default behavior of a construct causes bugs, change the default. Don't add warnings, attributes, or linter rules to patch over a broken default. Fix it. `switch` with fall-through is a broken default. `match` with isolated cases, exhaustiveness checking, destructuring, and expression form is the fix. --- ## Why Kairo Has Bidirectional C++ Interop Instead of Bindings URL: https://www.kairolang.org/blog/why-native-interop-instead-of-bindings/ # Why Kairo Has Bidirectional C++ Interop Instead of Bindings If you're building a new systems language in 2026, you have to answer one question before anything else: how does it talk to C++? The entire systems programming ecosystem runs on C and C++ libraries. Your language is dead on arrival if it can't use them. The standard answer is bindings. Write your language, then build a tool that reads C/C++ headers and generates wrapper code your language can call. Rust has `bindgen` for C, `cxx` and `autocxx` for C++. Every language in this space has some version of this. Kairo doesn't. Kairo parses C++ headers directly, makes every declaration available as a native Kairo symbol, and goes the other direction too: C++ can `#include` Kairo files. No binding generator, no wrapper code, no serialization layer. The interop is the compiler. ## The Problem with Bindings Binding generators are a translation layer between two type systems. That translation is where things break. **Build complexity.** `bindgen` is a separate tool in your build pipeline. It reads headers, generates Rust code, and that code has to be compiled alongside your project. Your build system now has an extra step that can fail independently, and debugging build failures means understanding what the generator produced, not just what you wrote. `cxx` requires you to write a bridge definition in a DSL that describes the interface between Rust and C++, a third language in your project that you have to keep in sync with both sides. **Type mismatches.** C++ has a rich type system: classes with inheritance, templates, concepts, operator overloading, move semantics, vtables. Binding generators have to map all of this into the target language's type system, and the mapping is always lossy. Templates are particularly painful: `bindgen` can only generate bindings for concrete template instantiations you explicitly request. You can't write generic code over a C++ template from the Rust side without manually instantiating every specialization you need. **Pointer semantics.** This is where bindings get dangerous. C++ uses raw pointers, references, `const` references, `unique_ptr`, `shared_ptr`, and move semantics. The generated bindings have to express all of this in the target language's pointer model, and the generator doesn't always get it right. You end up with `unsafe` blocks wrapping binding calls where the safety contract is "trust that the generator understood the C++ lifetime semantics correctly." **Maintenance burden.** Every time a C++ header changes, the bindings need to be regenerated. If the API changes in a way the generator doesn't handle cleanly, you're debugging generated code you didn't write to figure out why the types don't line up anymore. In large codebases with hundreds of C++ dependencies, this is a constant tax. **One-way by default.** Most binding generators only go in one direction: call C++ from your language. Going the other way, letting C++ call your code, is either unsupported, requires manual `extern "C"` exports that throw away your type system, or needs yet another tool. ## How Kairo Does It Kairo's approach is: skip the translation layer entirely. ### Kairo calling C++ `ffi "c++" import` invokes Clang's frontend internally to parse the header. Every exported declaration (functions, classes, enums, templates, concepts) becomes a native Kairo symbol with its original name and signature. No generated code, no bridge file. ```kairo ffi "c++" import "my_code.hh"; fn main() { var obj = MyClass("Kairo") std::println(f"name = {obj.get_name()}") my_function(42) } ``` That's it. If the C++ header compiles with Clang, Kairo can use it. ### C++ calling Kairo The `kcc` driver, a libclang-based compiler wrapper, makes `#include "file.k"` work transparently in C++ translation units: ```cpp #include "my_code.k" #include int main() { MyKairoClass obj("C++"); std::cout << obj.get_name() << std::endl; my_kairo_function(42); return 0; } ``` `kcc` intercepts the `#include`, invokes the Kairo compiler in-process to produce a C++-compatible header and object file, and links everything together. From the C++ side, Kairo types look like native C++ types because they are. Kairo emits ABI-compatible object code following the platform's native C++ ABI (Itanium on Unix, MSVC on Windows). ### Templates cross the boundary This is where the binding approach falls apart completely, and where Kairo's approach pays off the most. C++ concepts and Kairo generic constraints are interchangeable: ```kairo ffi "c++" import "my_code.hh"; fn add(a: T, b: T) -> T { return a + b } ``` `T impl Addable` in Kairo maps directly to `requires Addable` in the generated output. The constraint crosses the boundary without erasure. A Kairo generic type can satisfy a C++ concept, and a C++ concept can constrain a Kairo generic parameter. Try doing this with `bindgen`. You can't; you'd need to manually instantiate every template specialization and generate separate bindings for each one. ## Pointer Safety Across the Boundary Kairo doesn't pretend the interop boundary is safe. Any pointer or reference passed to C/C++ requires an explicit `unsafe` block, because the compiler can't enforce safety guarantees on the C++ side: ```kairo ffi "c++" import "my_code.hh"; fn main() { var x = 41 unsafe { add_one(unsafe &x) } std::println(f"x = {x}") // 42 } ``` `unsafe &` strips bounds tracking and hands a raw pointer to C++. The caller owns the memory contract from that point. This is explicit, visible, and greppable: you can search a Kairo codebase for every FFI boundary crossing in seconds. The difference from bindings: when you call a generated binding function, the `unsafe` is there but the actual pointer conversion happened inside generated code you didn't write. In Kairo, the conversion is in your code, where you can see exactly what safety guarantees you're giving up. ## What This Costs Nothing is free. Kairo's interop approach has tradeoffs: **Clang dependency.** Kairo's `ffi "c++"` uses Clang's frontend to parse headers. The compiler ships with a Clang frontend embedded. This is a large dependency, but it's the same tradeoff as any tool that needs to understand C++, including `bindgen`, which also uses `libclang`. **C++20 modules not yet supported.** The interop layer relies on header-based inclusion. Consuming pre-compiled C++ module interfaces (BMIs) is on the roadmap but not shipped yet. **Exception direction.** Kairo can catch C++ exceptions, but throwing Kairo panics into C++ isn't supported yet. For Kairo-to-C++ error signaling, use return types. ## Why This Matters The systems programming world has decades of C++ libraries. Physics engines, game engines, database kernels, OS APIs, networking stacks - all C++. A new language that can't use these fluently is a toy. Bindings are a tax you pay on every library, every API change, every template instantiation. Kairo's position is that the compiler should handle this natively, the same way it handles everything else: parse it, type-check it, emit code. No extra tools, no extra steps, no extra languages in your build. That's the bet. So far, it's working. ---