# Landin 0.2.11, for whoever has to write it One systems language from a 32 KB microcontroller to a hosted application. Manual memory with arenas as the idiom and no garbage collector, reference counting or destructors; separate reference permission and binding mutability; local origin and escape analysis rather than a borrow checker; concepts with evidence tables for both static generics and runtime dispatch; no compile-time execution and no macros. Native backends emit assembly for hosted systems and microcontrollers; the capabilities page lists the current targets. This half of the file is generated from the compiler's own tables and the specification's own grammar. The documents follow it in full. The one thing to know first: the kernel the compiler enables is narrower than the language the tour describes, and the compiler says which is which by name rather than guessing ([1830]). Section 4 is that list. A program written against the whole tour fails with it, not with a parse error. ## 1. Install, compile and run `refine` is Landin's compiler, and the command you run for everything else too: checking, running and compiling programs, formatting source, and the language server and debug adapter your editor starts. An install gives you `refine`, a few further commands you run through it, and Landin's standard library. There are six ways to get it: with the install script, with Homebrew, from a release, in a container, with nix, or from source. Use 0.2.9 or later: [the first program](https://www.701.dev/readme.html#your-first-program) needs `refine run` and `hosted/blocking`, both newer than 0.2.8. ### With the install script On Linux x86-64 or arm64, or on a Mac with Apple Silicon: ```sh curl -fsSL https://www.701.dev/install.sh | sh ``` It downloads the newest release's archive for your platform, the one [From a release](https://www.701.dev/readme.html#from-a-release) describes, checks it against the `.sha256` published beside it and unpacks it into `~/.landin`. On Linux that is the static archive unless you ask for the other one. It edits none of your files and needs no root: it prints the line that puts `~/.landin/bin` on your `PATH`, which you add to your shell's startup file. Run it again to replace that install with the newest release. Options follow `sh -s --`. To install a named release into a directory of your choosing: ```sh curl -fsSL https://www.701.dev/install.sh | sh -s -- --version 0.2.11 --dir ~/opt/landin ``` From the release after 0.2.11 a release has two archives for each Linux architecture, and `--variant static` or `--variant dynamic` chooses between them. Without the option you get the static one, which starts on any Linux. The dynamic one uses your system's glibc and needs glibc 2.38 or later: ```sh curl -fsSL https://www.701.dev/install.sh | sh -s -- --variant dynamic ``` The option is for Linux only. On a Mac the script refuses it, because macOS has one archive. `--list` names the archives a release has, both Linux ones among them. `--help` lists the options. The script is [`install.sh`](install.sh) in this repository, served unchanged; read it before you run it if you like. It refuses a host no archive serves, Intel Macs, FreeBSD, Windows and other CPU architectures among them. It also refuses an archive whose `refine` does not start on your host, after downloading and checking it. That is what the dynamic archive, and every archive of 0.2.11 and earlier, does on NixOS, on musl distributions and with a glibc older than 2.38. In both cases it says so, installs nothing, and names nix and the source build instead. For `--variant dynamic` it also says that the dynamic archive needs glibc 2.38 and that the static one starts on any Linux. With the GitHub CLI installed it also prints the commands that check the archive's attestation, as [From a release](https://www.701.dev/readme.html#from-a-release) describes. To remove the install, delete `~/.landin`. ### With Homebrew Homebrew installs `refine` on a Mac with Apple Silicon, and on Linux x86-64 and arm64. An Intel Mac is not covered. ```sh brew install 701-dev/tap/landin ``` `brew upgrade landin` updates it and `brew uninstall landin` removes it. To move an install from the earlier tap `janhaan/tap`, run `brew uninstall landin`, then the command above. The formula moves to a new release within a day of its publication. This installs the release archive for your platform, the one [From a release](https://www.701.dev/readme.html#from-a-release) describes; on Linux, from the release after 0.2.11, that is the static one. Its `bin/refine`, `libexec/landin` and `lib/landin` stay together in Homebrew's own directory for the package, and Homebrew puts `refine` on your `PATH`. Linking, and so `refine run`, needs Xcode's command-line tools on macOS and the system's GCC driver on Linux. See [the linker on Linux and macOS](https://www.701.dev/readme.html#the-linker-on-linux-and-macos). The `library: ` line of `refine version` then names the library inside that directory, for example `/opt/homebrew/Cellar/landin/VERSION/lib/landin` on a Mac. ### From a release The archive for your platform on [the releases page](https://github.com/701-dev/Landin/releases) holds `bin/refine`, the commands it runs from `libexec/landin` and the library under `lib/landin`, with no top-level directory. Unpack it into a directory of its own and put its `bin` on your `PATH`. From the release after 0.2.11, a release publishes two archives for each Linux architecture, x86-64 and arm64. macOS has one archive, as before, and FreeBSD x86-64 one, `landin-VERSION-x86_64-freebsd.tar.gz`, whose `refine` needs only the base system and links with its `cc` and binutils' `as` (`pkg install binutils`). The static archive has the platform's name: `landin-VERSION-x86_64-linux.tar.gz` and `landin-VERSION-aarch64-linux.tar.gz`. Its `refine` and the commands it runs have glibc linked in. It asks for no loader and no shared library, so it runs on any Linux: musl distributions such as Alpine, NixOS, and distributions whose glibc is older. The dynamic archive is beside it: `landin-VERSION-x86_64-linux-dynamic.tar.gz` and `landin-VERSION-aarch64-linux-dynamic.tar.gz`. Its `refine` uses the system's glibc, so it takes the system's glibc fixes. It needs glibc 2.38 or later and its standard loader, `/lib64/ld-linux-x86-64.so.2` on x86-64 and `/lib/ld-linux-aarch64.so.1` on arm64. It does not start on Debian 12 (glibc 2.36), Ubuntu 22.04 (2.35) or RHEL 9 (2.34), nor on NixOS or a musl distribution. 0.2.11 and earlier have one Linux archive for each architecture, and those stay published. It has the platform's name but is a dynamic one, linked against the glibc of Ubuntu 24.04, with the same needs as the dynamic archive above. Where it does not start, install with nix or build from source. The static archive holds two more files at its top level, which the dynamic one does not have. `LICENSE-GLIBC` is the copyright file of the Debian or Ubuntu `libc6-dev` package whose `libc.a` was linked in, with glibc's licence, the LGPL, version 2.1 or later. `NOTICE-GLIBC` names that glibc by its package version and distribution, says where its source is, and says how to relink `refine` with a modified glibc from Landin's public source. Beside each archive is `landin-VERSION-PLATFORM.tar.gz.sha256`, one line in `sha256sum`'s own format: `SUM landin-VERSION-PLATFORM.tar.gz`. For a dynamic archive, `PLATFORM` here and below ends in `-dynamic`, as in `x86_64-linux-dynamic`. Download it into the same directory as the archive and check the archive against it: ```sh sha256sum -c landin-VERSION-PLATFORM.tar.gz.sha256 # Linux shasum -a 256 -c landin-VERSION-PLATFORM.tar.gz.sha256 # macOS ``` It prints `OK` after the file name when the archive arrived whole and unchanged. It does not say who built it. The attestation does: the release workflow built each archive from its tag. With the GitHub CLI, check a downloaded archive before you unpack it: ```sh gh attestation verify landin-VERSION-PLATFORM.tar.gz --repo 701-dev/Landin \ --signer-workflow 701-dev/Landin/.github/workflows/release.yml \ --source-ref refs/tags/vVERSION --deny-self-hosted-runners ``` Releases up to 0.2.10 were built before the repository moved from the account `JanHaan` to the organisation `701-dev`, and their attestations name the old owner: for those, write `JanHaan` for `701-dev` in both options. Each archive leaves the compiler's debug information out and publishes it beside it as `landin-VERSION-PLATFORM-debug.tar.gz`, which for a dynamic archive ends in `-dynamic-debug.tar.gz`. You need that file only to read a crash of the compiler itself. ### In a container Each release publishes an image on GitHub's container registry, `ghcr.io/701-dev/landin:VERSION`. The tag is the release's version without the `v`: release `vVERSION` is tag `VERSION`. There is no `latest` tag, so name the version. Each tag holds Linux amd64 and arm64, and Docker or Podman picks the one for your host. Images start with the first release after 0.2.11; 0.2.11 and earlier have none. The image is Debian 13 with the static release archive for its platform unpacked in `/usr/local`: `refine` in `/usr/local/bin`, its commands in `/usr/local/libexec/landin` and the library in `/usr/local/lib/landin`. It also holds Debian's `gcc` and `libc6-dev`, which `refine` links with. Its working directory is `/work`. Mount your directory there and run as your own user, so the files `refine` writes are yours: ```sh docker run --rm -v "$PWD:/work" --user "$(id -u):$(id -g)" \ ghcr.io/701-dev/landin:VERSION refine run main.ldn ``` Compile and run a program the same way: give `refine compile main.ldn -o main` as the command, and then `./main`. `podman` takes the same arguments. With no command the image runs `refine version`, whose `library: ` line then says `/usr/local/lib/landin`. The release workflow attests each image. With the GitHub CLI, check one: ```sh gh attestation verify oci://ghcr.io/701-dev/landin:VERSION --repo 701-dev/Landin \ --signer-workflow 701-dev/Landin/.github/workflows/release.yml \ --source-ref refs/tags/vVERSION --deny-self-hosted-runners ``` The image links only for Linux on its own architecture. It holds no toolchain for firmware (Cortex-M, RISC-V, Xtensa) or for the other Linux architecture. Add one from Debian in an image of your own, for example for Cortex-M: ```dockerfile FROM ghcr.io/701-dev/landin:VERSION RUN apt-get update \ && apt-get install --no-install-recommends --yes gcc-arm-none-eabi libnewlib-arm-none-eabi \ && rm -rf /var/lib/apt/lists/* ``` `refine` also finds these Debian packages: - `gcc-riscv64-unknown-elf`, for RV32 firmware; - `gcc-aarch64-linux-gnu` and `libc6-dev-arm64-cross`, to link Linux arm64 programs on amd64; - `gcc-x86-64-linux-gnu` and `libc6-dev-amd64-cross`, to link Linux amd64 programs on arm64. Espressif's Xtensa compiler is not in Debian; it comes from Espressif. When a driver is missing, `refine`'s error names the package to install. To debug inside a container, install `gdb` the same way. It needs no extra capability. It warns that it cannot turn off address randomisation, which Docker's default security profile refuses, so a program's addresses can differ from one run to the next. An image moves only at a release: the Debian packages inside are the ones of the day the release was built. A second image, `ghcr.io/701-dev/landin-contributor:VERSION`, is for building the compiler itself. See [Building and checking](https://www.701.dev/readme.html#building-and-checking). ### With nix This command installs the prebuilt compiler and puts `refine` on your `PATH`: ```sh nix --extra-experimental-features 'nix-command flakes' \ profile install github:701-dev/Landin ``` It works on Linux x86-64, Linux arm64 and macOS arm64. It fetches the latest release archive, about 17 MB, and compiles nothing, so it takes seconds. On Linux, from the release after 0.2.11, that is the static archive. You can leave the `--extra-experimental-features` option out once `experimental-features = nix-command flakes` is in `~/.config/nix/nix.conf`. To run `refine` without installing it, use `nix run`. Everything after `--` goes to `refine`: ```sh nix run github:701-dev/Landin -- version nix run github:701-dev/Landin -- run main.ldn ``` The second line runs [the first program](https://www.701.dev/readme.html#your-first-program). To build from source instead, for example to get unreleased changes from main, install `#refine`. The first source build also fetches the pinned toolchain, which takes a few minutes: ```sh nix profile install github:701-dev/Landin#refine ``` In a clone, `nix build .#refine` builds the checkout into `result/`, and `nix build` alone fetches the release. ### From source On Linux x86-64, Linux arm64 or a Mac, you can fetch the pinned GNAT and GPRbuild and build from a clone. Any other host needs nix. `environments/pins.sh` holds the versions, URLs and SHA-256 sums of GNAT and GPRbuild. Its `landin_install_toolchain` downloads both archives and checks each against its sum. The archives are about 500 MB together. You need these tools first: - `curl`, `sha256sum` and `tar` for `landin_install_toolchain`; - `python3` and `git` for the build; - on a Mac, Xcode's command-line tools as well. ```sh git clone https://github.com/701-dev/Landin cd Landin . environments/pins.sh landin_install_toolchain "$HOME/landin-toolchain" x86_64-linux export LANDIN_GNAT_HOME="$HOME/landin-toolchain/gnat-$LANDIN_GNAT_VERSION" export LANDIN_GPRBUILD_HOME="$HOME/landin-toolchain/gprbuild-$LANDIN_GPRBUILD_VERSION" ./scripts/build.sh --compiler-only ``` These commands name `x86_64-linux`. Name `aarch64-linux` on Linux arm64 instead, and `aarch64-darwin` on a Mac. The build prints where it put `refine`. On Linux x86-64 that is `compiler/ada/build/linux-amd64/debug/bin/refine`, where `linux-amd64` is the build tag that keeps each host's objects apart. That is the debug build, which keeps the compiler's own internal checks on. `LANDIN_BUILD_MODE=release` builds the faster release one beside it. On Linux the release build links statically and needs glibc's static library, `libc.a`: `libc6-dev` has it on Debian and Ubuntu, and on Fedora you install `glibc-static`. The debug build does not need it. A static `refine` linked against musl and the jemalloc allocator has been built once, as a test, and the project does not build or publish one. It was built on Alpine 3.24, for x86-64 only, with Alpine's GNAT 15.2 and a GPRbuild 26.0.0 built from its sources. The pinned GNAT 16.1 has no musl build. Run with jemalloc's thread cache off (`MALLOC_CONF=tcache:false`), it passed the whole test program, 1279 of 1279 cases. On the scaling corpus it compiled about 6 % slower than the static glibc build. arm64 was not built. Making one needs source changes that are not in this repository, so you would have to make them yourself: two musl portability fixes in the C adapters, about twenty workarounds for GNAT 15.2, the jemalloc link and its heap figure, and accepting a musl host triple as Linux. Without the last, a `refine` built for musl refuses every compile that does not pass `--target=linux-x86-64`. The static glibc archive is the supported way to run `refine` on a musl distribution. This `refine` reads the clone's library, so put its directory on your `PATH` rather than copying it elsewhere. ### The linker on Linux and macOS Linking on Linux uses GCC as the linker driver, even when the program links no C library. `refine run` links, so it needs GCC too. The GCC is the one your distribution installs. `refine` looks for it under these names, in this order, and runs the first one it can start, so any one of them is enough: - `x86_64-pc-linux-gnu-gcc`, the name a GCC built from its own sources takes; - `x86_64-linux-gnu-gcc`, on Debian and Ubuntu; - `x86_64-redhat-linux-gcc`, on Fedora; - `gcc`, which `nix-shell -p gcc` provides on NixOS and `apk add gcc` on Alpine. On an arm64 machine the names are `aarch64-linux-gnu-gcc`, `aarch64-redhat-linux-gcc`, `aarch64-unknown-linux-gnu-gcc` and `gcc`, in that order. `--toolchain=NAME` names a driver yourself, and then `refine` tries that one alone. On Alpine, a program that links the C library, with `--link=libc`, also needs the `musl-dev` package. Without one, `refine` names each driver it looked for, in the same order, and says what to install. Checking, formatting, the language server and emitting assembly or the intermediate representation (IR) need none. macOS links through the Xcode command-line tools. ### Checking the install Run `refine version`. It names the compiler: a release, or `refine dev (01234567)` for a build from a clone. Its `library: ` line names the directory the standard library is read from: the archive's `lib/landin`, the one in Homebrew's directory for the package, or the clone. The lines under it name the `citations.txt` that `refine explain` reads, say whether it can be read, and list each command shipped beside `refine` with its path. Install `refine` as [the README](https://www.701.dev/readme.html#installing) describes. Copy a program into a file called `main.ldn` in a directory of its own, then compile and run it there: ```sh refine compile main.ldn -o fizzbuzz ./fizzbuzz ``` `refine` compiles for the computer it runs on unless `--target` names another. Each program prints what it computes and returns 0 when it succeeds. Its output is shown under its listing. A program that reads its standard input or takes an argument says so in its section. Every program here is compiled and run, and what it prints is checked, on Linux, macOS and FreeBSD. The `Fixture source:` line above each listing says where the program lives in the repository. [The firmware example](https://www.701.dev/readme.html#firmware-for-a-microcontroller) is the exception to both paragraphs: it is built for a microcontroller, runs in an emulator and has its own commands. ## 2. The vocabulary of the enabled kernel 48 reserved words. Reserved everywhere, including in ordinary name positions (D225), so `begin: i32 = 10` is invalid and `begin_value` is not. addr alignof and any atom begin break continue dec defer do else elsif end escaping extern fail false fixed for from if import in inc inout loop match mut none not or ptr public return sink sizeof struct then true try type unchecked undo uninit when while zeroed 13 scalar type names. Not keywords: they are ordinary declared names the kernel predeclares, so nothing stops a program shadowing one. u8 u16 u32 u64 i8 i16 i32 i64 usize isize f32 f64 bool 3 text type names, on the same footing. utf8 utf16 cstring Words a production recognises that nothing reserves. Each is an ordinary identifier wherever its own production does not meet it, which is the commonest way to misread the grammar. align as assembler at boot_stage c caller compiler concept distinct held interrupt into is keep layout lenof link linker naked noreturn of offsetof option out packed region section symbol thread through u16 u32 u64 u8 variant vector ## 3. The grammar of the enabled kernel, in one piece The 172 productions of [1740] to [1830], with the prose that explains them removed. A name in lower case is a rule, a quoted word is itself, `?` is optional, `*` is none or more, `+` is one or more, `...` between two quoted bytes is every byte from one to the other, and parentheses group. This is what the hand-written parser is written against, and `check.py` derives the whole fixture corpus from it. ``` program ::= import_declaration* declaration* import_declaration ::= "import" import_path ("as" identifier)? import_path ::= identifier ("/" identifier)* declaration ::= "public"? (atom_declaration | binding | function | external_function | machine_function | linked_binding | type_declaration | concept_declaration) | conformance_declaration | fixed_conditional | option_declaration | tool_directive option_declaration ::= "option" identifier ":" type "=" expression tool_directive ::= tool_namespace "." identifier "(" (expression ("," expression)*)? ")" tool_namespace ::= "compiler" | "assembler" | "linker" fixed_conditional ::= "fixed" "if" expression "then" declaration* ("elsif" expression "then" declaration*)* ("else" declaration*)? "end" "if" atom_declaration ::= identifier ":" "atom" identifiers ::= identifier ("," identifier)* space ::= " " | "\t" | line_end | comment line_end ::= "\n" | "\r\n" | "\r" identifier ::= lower (lower | digit | "_")* | "_" (lower | digit | "_")+ lower ::= "a" ... "z" digit ::= "0" ... "9" keyword ::= "addr" | "alignof" | "and" | "any" | "atom" | "begin" | "break" | "continue" | "dec" | "defer" | "do" | "else" | "elsif" | "end" | "escaping" | "extern" | "fail" | "false" | "fixed" | "for" | "from" | "if" | "import" | "in" | "inc" | "inout" | "loop" | "match" | "mut" | "none" | "not" | "or" | "ptr" | "public" | "return" | "sink" | "sizeof" | "struct" | "then" | "true" | "try" | "type" | "unchecked" | "undo" | "uninit" | "when" | "while" | "zeroed" literal ::= integer | float | character | text | raw | "true" | "false" | "zeroed" | "uninit" character ::= "'" (character_escape | unicode_scalar) "'" unicode_scalar ::= any Unicode scalar except apostrophe, backslash or line_end character_escape ::= "\\" ("n" | "r" | "t" | "e" | "\\" | "\"" | "'" | "u" "{" hex_digit+ "}") text ::= "\"" (text_escape | text_byte)* "\"" text_byte ::= any byte except quote, backslash or line_end text_escape ::= "\\" ("n" | "r" | "t" | "e" | "\\" | "\"" | "'" | "x" hex_digit hex_digit | "u" "{" hex_digit+ "}") raw ::= quote_run raw_content quote_run quote_run ::= "\"" "\"" "\"" "\""* raw_content ::= any byte+ integer ::= decimal | hex | octal | binary float ::= decimal_fraction decimal_exponent? | hex_fraction binary_exponent decimal_fraction ::= decimal_digits "." decimal_digits decimal_exponent ::= ("e" | "E") ("+" | "-")? decimal_digits hex_fraction ::= "0x" hex_digits "." hex_digits binary_exponent ::= ("p" | "P") ("+" | "-")? decimal_digits decimal_digits ::= digit ((digit | "_")* digit)? hex_digits ::= hex_digit ((hex_digit | "_")* hex_digit)? decimal ::= digit ((digit | "_")* digit)? hex ::= "0x" hex_digit ((hex_digit | "_")* hex_digit)? octal ::= "0o" octal_digit ((octal_digit | "_")* octal_digit)? binary ::= "0b" binary_digit ((binary_digit | "_")* binary_digit)? hex_digit ::= digit | "a" ... "f" | "A" ... "F" octal_digit ::= "0" ... "7" binary_digit ::= "0" | "1" comment ::= block_comment | doc_comment | line_comment block_comment ::= "--(" block_item* ")--" block_item ::= block_comment | any byte that begins neither "--(" nor ")--" doc_comment ::= "---" (any byte except line_end)* line_comment ::= "--" (any byte except line_end)* binding ::= "mut"? identifier ":" declared_type ("=" expression)? | "mut"? identifier ":=" expression declared_type ::= type | atom_union type ::= function_type | array_type | pointer_type | slice_type | any_type | type_application | scalar_name | packed_unsigned | text_name | declaration_reference function_type ::= signature | c_convention c_signature | machine_convention c_signature array_type ::= "[" expression "]" type pointer_type ::= "ptr" "mut"? type slice_type ::= "[" "]" "mut"? type any_type ::= "any" concept_reference type_application ::= declaration_reference "(" type_argument ("," type_argument)* ")" type_argument ::= type | expression scalar_name ::= "u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64" | "usize" | "isize" | "f32" | "f64" | "bool" text_name ::= "utf8" | "utf16" | "cstring" type_declaration ::= identifier ":" "type" ("=" (encoded_union | atom_union | distinct_body | type | struct_body) | type_formals "=" (encoded_union | atom_union | distinct_body | type | struct_body)) distinct_body ::= "distinct" type concept_declaration ::= identifier ":" "type" "=" concept_body concept_body ::= "concept" type_formals ("is" concept_reference ("," concept_reference)*)? concept_entry* "end" identifier? concept_entry ::= identifier ":" signature conformance_declaration ::= type_formals? conformance_target "is" concept_reference (conformance_entries conformance_field? | conformance_field) conformance_entries ::= "(" conformance_argument ("," conformance_argument)* ")" | "(" ")" conformance_field ::= "through" identifier conformance_target ::= array_type | pointer_type | slice_type | any_type | type_application | declaration_reference conformance_argument ::= identifier ":" argument_rhs concept_reference ::= declaration_reference declaration_reference ::= identifier | qualified_reference qualified_reference ::= identifier ("." identifier)+ type_formals ::= "(" type_formal ("," type_formal)* ")" type_formal ::= identifier ":" "type" constraint? | "fixed" identifier ":" type constraint ::= "is" concept_reference atom_union ::= union_member "|" union_member ("|" union_member)* union_member ::= declaration_reference | type_application | pointer_type encoded_union ::= packed_unsigned? "(" encoded_member ("|" encoded_member)* ")" encoded_member ::= declaration_reference "=" exclusion packed_unsigned ::= "u1" | "u2" | "u3" | "u4" | "u5" | "u6" | "u7" | "u8" | "u9" | "u10" | "u11" | "u12" | "u13" | "u14" | "u15" | "u16" | "u17" | "u18" | "u19" | "u20" | "u21" | "u22" | "u23" | "u24" | "u25" | "u26" | "u27" | "u28" | "u29" | "u30" | "u31" | "u32" | "u33" | "u34" | "u35" | "u36" | "u37" | "u38" | "u39" | "u40" | "u41" | "u42" | "u43" | "u44" | "u45" | "u46" | "u47" | "u48" | "u49" | "u50" | "u51" | "u52" | "u53" | "u54" | "u55" | "u56" | "u57" | "u58" | "u59" | "u60" | "u61" | "u62" | "u63" | "u64" struct_body ::= ("layout" "(" ("c" ("," "packed")? | "packed" ("," ("u8" | "u16" | "u32" | "u64"))?) ")")? "struct" member+ "end" identifier? member ::= field | variant_part field ::= identifier ":" declared_type ("at" expression (".." expression)?)? variant_part ::= identifier ":" "variant" variant_case ("|" variant_case)* "end" identifier variant_case ::= identifier (":" "(" payload_field ("," payload_field)* ")")? payload_field ::= identifiers ":" declared_type function ::= (link_attributes "public"?)? identifier ":" declared_signature "=" body "end" identifier? external_function ::= (link_attributes "public"?)? c_convention link_symbol? identifier ":" c_declared_signature ("=" body "end" identifier?)? machine_function ::= (link_attributes "public"?)? machine_convention link_attributes? identifier ":" declared_signature "=" body "end" identifier? linked_binding ::= link_attributes "public"? binding c_convention ::= "extern" "(" "c" ")" machine_convention ::= "extern" "(" ("interrupt" | "naked") ")" link_symbol ::= "link" "(" "symbol" ":" text ")" link_attributes ::= "link" "(" link_attribute ("," link_attribute)* ")" link_attribute ::= ("symbol" | "section" | "region") ":" text | ("align" | "vector") ":" integer | "keep" | "thread" | "boot_stage" c_signature ::= "(" (parameters ("," "...")?)? ")" "->" returns errors? c_declared_signature ::= "(" (routine_formals ("," "...")?)? ")" "->" returns errors? signature ::= "(" parameters? ")" "->" returns errors? declared_signature ::= "(" routine_formals? ")" "->" returns errors? routine_formals ::= routine_formal ("," routine_formal)* routine_formal ::= parameter | type_formal errors ::= "!" (declaration_reference ("|" declaration_reference)* | "...") parameters ::= parameter ("," parameter)* parameter ::= "caller" identifiers ":" declared_type | ("escaping" ("into" identifier)?)? parameter_convention? identifiers ":" declared_type parameter_convention ::= "inout" | "sink" returns ::= "(" named_return ("," named_return)* ")" | "none" | "noreturn" named_return ::= identifiers ":" declared_type ("from" return_source ("," return_source)*)? return_source ::= "held"? identifier body ::= block block ::= statement* | value_statement* expression value_statement ::= binding | destructuring_binding | assignment | increment | discard | call | labeled_application | defer | undo | try | "return" "when" expression | "fail" expression "when" expression | break | continue | loop | while | for | if | match | bare_block | labeled_block destructuring_binding ::= "(" destructured_field ("," destructured_field)* ")" ":=" expression destructured_field ::= identifier (":" (identifier | "_"))? | "_" statement ::= binding | destructuring_binding | assignment | increment | discard | call | labeled_application | defer | undo | try | return | fail | break | continue | loop | while | for | if | match | unchecked | bare_block | labeled_block assignment ::= place assignment_operator expression assignment_operator ::= "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "+%=" | "-%=" | "*%=" increment ::= ("inc" | "dec") place discard ::= "_" "=" expression defer ::= "defer" call undo ::= "undo" call return ::= "return" ("when" expression)? fail ::= "fail" expression ("when" expression)? break ::= "break" identifier? ("when" expression)? continue ::= "continue" identifier? ("when" expression)? loop ::= "loop" "do" block "end" "loop" | identifier ":" "loop" "do" block "end" identifier condition ::= expression | condition_declaration condition_declaration ::= "mut"? identifier ":=" expression | "mut"? identifier ":" declared_type "=" expression while ::= "while" condition "do" block "end" "while" | identifier ":" "while" condition "do" block "end" identifier for ::= "for" identifier ("," identifier)? "in" expression ((".." | "..<") expression)? "do" block "end" "for" | identifier ":" "for" identifier ("," identifier)? "in" expression ((".." | "..<") expression)? "do" block "end" identifier try ::= "try" (call | labeled_application) if ::= "if" condition "then" block ("elsif" condition "then" block)* ("else" block)? "end" "if" match ::= "match" expression match_arm+ "end" "match" match_arm ::= (match_label | "_") ("(" match_binding ("," match_binding)* ")")? ":" (statement | expression) | match_label ("," match_label)+ ":" (statement | expression) match_label ::= declaration_reference | "ptr" match_binding ::= ("inout" | "sink")? identifier unchecked ::= "unchecked" "begin" block "end" "unchecked" bare_block ::= "begin" block "end" labeled_block ::= identifier ":" "begin" block "end" identifier place ::= indexed primary ::= literal | array_literal | array_repetition | struct_literal | empty_slice | labeled_application | indexed | call | address | pointer_conversion | any_construction | measurement | try | if | match | bare_block | "(" expression ")" array_literal ::= "[" expression ("," expression)* "]" array_repetition ::= "[" integer "of" expression "]" | "[" "of" expression "]" | "[" expression ("," expression)* "," "of" expression "]" struct_literal ::= "(" field_value ("," field_value)* ("," "of" expression)? ")" field_value ::= identifier ":" expression labeled_application ::= indexed "(" labeled_arguments ")" recovery? labeled_arguments ::= (expression ",")* labeled_argument ("," labeled_argument)* ("," "of" expression)? labeled_argument ::= identifier ":" argument_rhs argument_rhs ::= expression | type indexed ::= selection (index | slice_selection | ("." identifier))* index ::= "[" expression "]" slice_selection ::= "[" expression (".." | "..<") expression "]" selection ::= identifier ("." identifier)* call ::= indexed "(" arguments? ")" recovery? | written_conversion recovery ::= "else" expression | "else" "none" | "else" "(" identifier ")" block "end" address ::= "addr" place written_conversion ::= conversion_type "(" expression ")" conversion_type ::= function_type | array_type | pointer_type | slice_type | any_type | type_application pointer_conversion ::= "ptr" "(" expression ")" any_construction ::= "any" "(" expression ")" empty_slice ::= "[" "]" measurement ::= ("sizeof" | "alignof") type | "lenof" (call | labeled_application | indexed) | "lenof" "(" array_literal ")" | "offsetof" qualified_reference arguments ::= expression ("," expression)* ("," assembly_operand)* assembly_operand ::= ("in" | "inout") identifier ":" type "at" identifier "=" expression | "out" identifier ":" type "at" identifier | "out" "_" "at" identifier unary ::= ("-" | "~" | "not")* primary product ::= unary (("*" | "/" | "%" | "*%") unary)* sum ::= product (("+" | "-" | "+%" | "-%") product)* shift ::= sum (("<<" | ">>") sum)* conjunction ::= shift ("&" shift)* exclusion ::= conjunction ("^" conjunction)* alternation ::= exclusion ("|" exclusion)* comparison ::= alternation (("==" | "<>" | "<" | "<=" | ">" | ">=") alternation)? logical_and ::= comparison ("and" comparison)* expression ::= logical_and ("or" logical_and)* ``` ## 4. Spellings the compiler refuses by name Read this before writing anything the tour shows. Each row is a form the compiler recognises and declines, with the paragraph that describes it and what it is. None is pending work: [1830] separates a source form an implemented construct does not admit from a form the language withdrew and one a successor roadmap owns, and `spec.md`'s register says why for each. [0100] Several names in one declaration the parser refuses `shared declaration`; a recorded source-form boundary [0120] Declaring a type the parser refuses `declared type`; a recorded source-form boundary [0150] Integer types the checker refuses `wide integer type`, spelled i128, u128; transferred to Language evolution [0170] Floating point the checker refuses `narrow float type`, spelled f16; transferred to Language evolution [0520] Arrays are values the checker refuses `array value`; a recorded source-form boundary the checker refuses `array element`; a recorded source-form boundary [0540] `zeroed`: the all-zero value the checker refuses `zeroed value`; a recorded source-form boundary [0560] Filling an array with one value the parser refuses `array repetition`; a recorded source-form boundary [0570] Slices are views the parser refuses `indexing`; a recorded source-form boundary [0670] Structs the parser refuses `struct type`; a recorded source-form boundary the checker refuses `struct value`; a recorded source-form boundary [0680] Structs with a variant part the checker refuses `variant value`; a recorded source-form boundary [0720] Filling the remaining fields with `of` the parser refuses `struct all of`; a recorded source-form boundary [0820] Arenas are ordinary allocators you give storage to the parser refuses `arena block`; withdrawn the checker refuses `arena region`, spelled arena; withdrawn [0850] Volatile access sits outside the borrow rules the parser refuses `volatile reference`; withdrawn [1290] Writing a generic function the parser refuses `type parameter`; a recorded source-form boundary [1350] Generic types the checker refuses `parameterized type alias`; a recorded source-form boundary [1630] Inline assembly, for what has no builtin the checker refuses `float operand`; a recorded source-form boundary ## 5. Every diagnostic code What `refine` prints, and the rule behind it. `Retired` means the code is spent and never issued. Generated from the catalogue that owns them; nothing else writes a code. ``` L0001 Retired a source was read and no frontend is wired to the driver L0002 Live an option or argument the driver does not define L0003 Live a source that is missing or cannot be read L0004 Live a target no description names L0005 Live an output file that cannot be written L0006 Live [1420]: no ordered import root contains the requested module L0007 Live [1410], [1420]: a module directory is invalid or unreadable L0015 Live D267: an imported source namespace is unavailable for the target L0016 Live D275: a project root holds a module the compiler's library supplies instead L0017 Live D1357: the citations file names compiler sources other than the compiler's L0532 Live D563: an import's first directory holds no source and a later root holds its module L0616 Live D1055: an import selects the directory of a source the request named as the entry module L0008 Live D252: a source `refine fmt --check` finds out of the layout L0009 Live D255: a CPU feature level the selected target does not have L0010 Live [1830]: the tour describes this and the kernel omits it L0011 Live [1770]: an integer with missing digits, misplaced underscores, an invalid base digit, or an adjacent name L0012 Live [1750]/[1760]: a run of bytes no rule spells, or a word with a capital L0013 Live [1780]: a block comment that is never closed L0014 Live [0250]/[0260]/[0280]: a quoted or raw literal that is never closed L0100 Live [1760]: a name position holds something that is not a name L0101 Live [1790]: a type position holds no type the kernel enables L0102 Live [1820]: an expression was required and none begins here L0103 Live [1810]: a terminal the production spells is absent L0104 Live [1800]: a construct whose closing `end` never arrives L0105 Live [0390]: assignment is a statement, never an expression L0106 Live [1820]: comparison takes at most one operator L0107 Live [1810]: `return` carries no value; assign the named return L0108 Live [1740]: `public` rides on a declaration, not a statement L0109 Live [1800]: the name on `end` is not the name declared L0110 Live [1740]: a run of tokens beginning no declaration or statement L0111 Live an implementation limit on how deeply a construct nests L0112 Live [0980]: a positional call argument precedes every named argument L0200 Live [1850]: one scope gives one name to one thing L0201 Live [1860]: a name used and declared in no visible scope L0202 Live [1410]: a module-internal declaration used across modules L0203 Live [1560]: a builtin tool namespace binding or use is unavailable L0300 Live a compile-time magnitude its context or target does not hold L0398 Live [0740]: a known register image violates its reserved-bit write policy L0301 Live [1890]: a value's type is not the one its context or operation requires L0302 Live [1910], [0910], [0930]: a place unassigned at a read or exit L0303 Live [1900]: a place that may not be written L0304 Live [1830]: a known form used where the language does not permit it L0305 Live [1940]/D136/D202: a required static value or initial image that the compiler cannot establish before runtime L0306 Live [1950]: an operand the operation cannot take, where the compiler knows it L0324 Live [1510]: a compile-time assertion is false L0307 Live [1795]: a chain of aliases that reaches no type L0308 Live [0750]: a field a struct was not declared with L0309 Live [0670]/[0710]/D74/D76: each field is named at most once in a struct declaration or literal, or a variant case declaration or construction L0310 Live [0710]/D76: every field in a struct literal or variant case construction is named or covered by `of` L0311 Live [1210]: a match names each variant case at most once L0312 Live [1210]: an exhaustive match names every variant case L0313 Live D137: a nominal value layout cannot contain itself by value L0314 Live [0770]/[0780]: retention requires live storage and permission from the reference's origin L0315 Live [0800]/[0830]: a live derived view keeps its source still L0316 Live [0790]: a returned reference derives from exactly its declared source parameters L0317 Live a whole-program conformance key has two declarations L0318 Live a concrete type actual lacks the required concept conformance L0319 Live a user attempts to declare the compiler-owned concept or one of its supplied conformances L0320 Live [0270] [1750]: a text literal contains a malformed escape or invalid source encoding L0321 Live [0210] [0220] [0230] [1770]: a float has a complete fraction and exponent when required, and ends before a name L0322 Live [0250] [0270]: a character literal spells exactly one Unicode scalar value L0323 Live [0280] [1750]: raw content is UTF-8 and every nonblank line has the closing delimiter's indentation L0325 Live D247: an implementation limit on declarations in a routine or fields in a struct body or variant case L0390 Live [1530]/D202: an option must be unconditional, have an available name and use a supported scalar type L0391 Live [1510]/[1590]/D202: a tool directive needs one argument; linker.library needs a quoted portable library name L0326 Live D251: a local declared `mut` that nothing writes L0327 Live [1920]/D138: call arguments match the parameters and the callee's static formals L0328 Live [0540]: zeroed or an implicit initializer has no complete zero image L0329 Live [0940]/[0960]: failures obey the declared error set and call handling L0330 Live [1630]/[1990]: assembly operands, registers and template slots obey the block contract L0331 Live [1020]/[1930]/[0990]: a call's results are used, discarded or bound as the signature allows L0332 Live D1651/D124: a loop is a statement and a break carries no value; value-producing fallthroughs supply one L0333 Live [1210]/[0480]/[0640]: each match arm names a case of its subject in an admitted form L0334 Live [0700]/[0720]: struct, variant and array values are built and used in their admitted forms L0335 Live [0480]: a pointer union is matched before its pointer is read L0336 Live [0730]: a packed image is used through its fields and declared layout L0337 Live [0430]/[0900]/[0910]: an operation needing a distinct addressable place lacks one L0338 Live [1795]/[1350]: a type position or declaration is not well formed L0339 Live [0790]/[0980]/[0990]/D192: a written signature is not well formed L0340 Live D138: a generic call deduces and instantiates one concrete routine L0341 Live [1230]-[1270]: a concept or conformance declaration is not well formed L0342 Live [1370]-[1390]/D145-D147: an `any` value or dispatch outside its erased contract L0343 Live [0890]: a noreturn routine is infallible and never returns L0344 Live [1620]/D227: a memory intrinsic outside its explicit contract L0345 Live [1570]: an interrupt or naked routine outside its machine-entry contract L0346 Live [1580]: a C boundary signature, layout or variadic call the C ABI cannot carry L0347 Live [1610]/[1640]: a link symbol, helper import or placement outside its contract L0348 Live [1150]/D180: a for source is a range, a traversable value or one exact iterable conformance L0399 Live D542: a device description directive whose arguments are not the forms its row says L0513 Live D542/D543: a description directive outside one description, a repeated or missing one, or a second description L0514 Live D543: regions that overlap, or a placement, vector table or stack its regions cannot hold L0515 Live D543: a description whose core is not the request's target and level L0516 Retired retired: a reserved boot image kind refine did not build L0517 Live D547: a link(region: ...) the selected description cannot hold L0518 Live D543: firmware or a placement that needs a profile, with no description reached and none in the library L0533 Live D587: link(boot_stage) on anything but a naked routine with no other link attribute L0534 Live D587: a boot stage outside the device description the program selects L0535 Live D587: a boot stage in a description whose boot kind takes none L0536 Live D587: a second boot stage in one description L0537 Live D587: a description whose boot kind begins with a second stage, holding none L0545 Live D615: a float unit refine does not build, or one the description's core cannot have L0546 Live D615: a description with a float unit, built at a level whose architecture lacks it L0610 Live D971: a cache refine does not build, or one the description's core cannot have L0611 Live D971: a described cache whose line is not its core's L0560 Live D653: a vector-table description's stage that does not name compiler-owned reset L0561 Live D653: a vector-table description's stage that uses the stack L0576 Live D681: a boot image kind another family's boot ROM reads L0575 Live D683: an esp-app-image description without compiler.esp_image, or compiler.esp_image without an esp-app-image L0578 Live D688: a .ramtext routine in a profile whose data region code does not run in L0349 Live D251: an unused local with an effect-free literal initializer L0350 Live D760: an untyped float literal converted to an integer that its f32 rounding changes L0600 Live D949: compiler.utf8_unvalidated outside an unchecked region L0628 Live D1077: a bidirectional control character in a comment or a literal L0684 Live D1261: a call-site `else` that binds an error its block never reads L0692 Live D1342: a declaration that takes a predeclared type's name L0693 Live D1367: a body ends with a value after its named result was assigned L0500 Live [1550]: the requested output cannot be made with the target, settings or available toolchain L0501 Live [1550]: assembler or linker refusal, or executable output lifecycle failure L0502 Live [1970] [1990]: a missing or invalid hosted main or explicitly selected firmware entry L0503 Retired retired: the register-only internal calling limit L0504 Live a verified frame larger than the target's backend can address L0505 Live D537: static images exceed the image budget of the target or the firmware profile L0506 Live [1670]: invalid panic handler or unrepresentable site space L0507 Live [1990]: one firmware frame exceeds the selected stack reservation L0508 Live [1670]: a selected panic handler in a program that prepares a stack exceeds or cannot be measured against the target's stack margin L0509 Live [1590]/D525: a failed link's library that no named directory and none of the C driver's own holds L0519 Live D546: a linked firmware image that breaks a clause of the linker script contract L0538 Live D588: an assembled boot stage that outgrows its slot or that a relocation reaches L0555 Live D638: an assembled image block that is not the IMAGE_DEF block its boot kind gives, or that a relocation reaches L0577 Live D685: a linked image no ESP application image can hold, or one whose written bytes do not read back L0525 Live D555: an SVD that is not XML in the subset refine svd reads L0526 Live D556: a selection policy refine svd cannot read L0527 Live D556: an SVD that is not the one its policy was reviewed against L0528 Live D557: an SVD form refine svd does not read, for a selected register L0529 Live D557: a selected register the SVD describes in a way that cannot be generated as it says L0530 Live D556: a policy that selects what its SVD does not have L0531 Live D558: outputs refine svd will not replace L0579 Live D820: a binding policy refine bindings cannot read L0580 Live D820: a Clang that cannot be run as asked, fails, or describes another ABI L0581 Live D820: a selected C declaration, or its policy, that cannot be bound L0582 Live D820: outputs refine bindings will not replace L0587 Live D924: a firmware image whose C archives bring constructors, thread-local storage or a dynamic linkage L0688 Live D1292: a source table refine site cannot read L0689 Live D1292: a build that is not the one its source table was written with L0690 Live D1292: a site or a caller's file the table does not hold L0694 Live D1384: a split command refine was built with that its installation lacks L0695 Live D1387: an external command whose description refine cannot accept L0696 Live D1847: the language removed this form, and the refusal names the one that replaces it L0697 Live D2175: an atom set names one member twice ``` ## 6. What follows `tour.md` teaches the language, construct by numbered construct. `spec.md` decides it: the grammar above, the rules the tour leaves unsaid, and a register of every decision with the alternative it was chosen over and the fixture that pins it. `examples.md` holds complete programs that print what they compute, which the gate runs. Where the tour and the specification could be read differently, the specification decides. ======================================================================== tour.md ======================================================================== # Learn Landin in Y minutes Ada, but small. Zig, but sweeter. One systems language from 32 KB to 32 TB*. Move fast, keep the pointers, and let the compiler tell you when you are being an idiot. Named after Peter Landin, who coined the term "syntactic sugar" and wrote "The Next 700 Programming Languages". This one is the 701st. Coming from C? [Landin for C programmers](docs/from-c.md) maps each habit you bring to its Landin form. ## Hello, world Make a directory, `mkdir hello && cd hello`, and save this in it as `main.ldn`: ```landin import core/io import hosted/blocking public main: () -> (code: i32) = host := blocking.new() io.write(host, io.out(host), "Hello, world!\n") else none code = 0 end main ``` Run it with `refine run main.ldn`, or keep an executable with `refine compile main.ldn -o hello`. - `core/io` is the interface for reading and writing; `hosted/blocking` provides it over the operating system. - `main` is a function; the compiler's messages also say routine for one. It returns one named result, `code`, the exit status, and sets it by assigning it. - `host` is your handle on the operating system: pass it to whatever needs to read or write. - `io.write` can fail, and a failure cannot pass unnoticed; `else none` says it does not matter here ([1030]). ## Reading a file This program counts the lines of the file named by its first argument. Save it as `main.ldn` in a directory of its own: ```landin import core/failure import core/io import core/mem import hosted/blocking --- How many lines the file named by the first argument has. count_file_lines: (host: blocking.host) -> (lines: usize) ! mem.not_found | io.no_access | io.is_a_directory | io.io_failed | mem.out_of_memory = path := try io.argument(host, 0) source := try io.open_read(host, path) defer io.close(host, source) else none mut buffer: [4096]u8 = zeroed mut reader := io.lines_over(host, source, buffer) lines = 0 loop do line := try io.read_line(reader) break when line.at_end inc lines end loop end count_file_lines public main: () -> (code: i32) = host := blocking.new() lines := count_file_lines(host) else (problem) words: []u8 = failure.words(problem) io.write_format(host, io.err(host), "error: {}\n", [any(addr words)]) else none code = 1 return end io.write_format(host, io.out(host), "{} lines\n", [any(addr lines)]) else none code = 0 end main ``` - The `!` list says every way `count_file_lines` can fail, and `try` passes a failure on to the caller ([0960]). - `defer` closes the file however the function ends ([1100]). - `main` decides what a failure means: `else (problem)` handles it in place. - `io.write_format` fills each `{}` with the next value. ```sh refine compile main.ldn -o lines printf 'one\ntwo\nthree\n' > notes ./lines notes ./lines missing echo $? ``` ```text 3 lines error: not found 1 ``` A program that writes many lines gathers them in a [buffered writer](docs/library.md#the-buffered-writer). [`examples.md`](examples.md) has complete programs that list directories, run commands and talk over sockets. ## How to read this tour - Read it in order up to the end of MODULES and you can write ordinary programs; the rest is reference. - The bracketed numbers, such as [0430], never change: when the compiler refuses a program, its error ends with the entry that explains the rule. - Everything is implemented unless marked DEFERRED or *not yet*. - [`spec.md`](spec.md) is the specification and decides wherever the two could be read differently. *32 TB is an unverified goal. What it measures at the hosted end, and what evidence would prove it, are still open, and nothing hosted today establishes it. Terabytes may vary. --- ## COMMENTS Each example in this section is itself a comment, exactly as it appears in a program: the marker at its start is what makes it one. ### [0010] Line comments `--` starts a comment that runs to the end of the line. ```landin -- [0010] Line comment, to end of line. ``` ### [0020] Block comments, which nest `--(` opens a block comment and `)--` closes it. A block comment may sit between two tokens on one line. ```landin --( [0020] Block comment. Nests properly. --( so this inner one is fine )-- )-- ``` Because block comments nest, you can comment out a region that already contains one. A block comment that is never closed runs to the end of the file, and the compiler reports it there. ### [0030] Doc comments `---` starts a doc comment, which documents the declaration on the next line. ```landin --- [0030] Doc comment. Attaches to the declaration that follows. ``` A doc comment changes nothing about what the program means. Spec [2000] says which lines count as a declaration's doc comment. ## DECLARATIONS ### [0040] Declaring a name A declaration gives a name, a type and a value, in that order. The name is immutable unless you say otherwise ([0060]). ```landin greeting: utf8 = "hello" ``` ### [0050] Letting the type come from the value Leave out the type and write `:=`, and the name takes the type of its value. ```landin count := 7 ``` ### [0060] Mutable variables `mut` makes a binding you can assign again. ```landin mut total: u32 = 0 ``` ### [0070] Two separate questions about a reference A reference raises two independent questions. May the name be pointed somewhere else? `mut` on the binding answers that. May the thing it points at be written? `mut` inside the type answers that. Nothing else answers either. ```landin two_questions: () -> (seen: u32) = mut first_reading: u32 = 1 mut dial_setting: u32 = 2 mut cursor: ptr u32 = addr first_reading -- re-pointable, reads only knob: ptr mut u32 = addr dial_setting -- fixed, writes cursor = addr dial_setting -- allowed: the binding is mut knob.val = 3 -- allowed: the type is ptr mut seen = cursor.val -- 3 end two_questions ``` `addr` takes an address and `.val` is the thing pointed at. [0430] explains pointers properly, and [0460] points one at a fixed hardware address. ### [0080] Declaring now, assigning later A declaration may leave out the value. The name must then be assigned before anything reads it. ```landin mut result: u32 ``` ### [0090] Making a name public `public` exports a name to other modules. Without it, the name is private to its module. ```landin public version: u32 = 3 ``` `public` is about modules, not the linker. A public function or datum is still a local symbol inside the program's image, so no C library or linked object can collide with it. To give C or the linker a name, see [1600] and [1610]. Exact rules: spec [1975]. ### [0100] Several names in one declaration A declaration introduces one name. A binding, a struct field and an atom each take a line of their own: ```landin public red: u8 public green: u8 public blue: u8 mut low_mark: u32 = 10 mut high_mark: u32 = 10 ``` Several names may share one type in three places only: a parameter list, a list of named results and a variant's payload list. ```landin clamp: (value: i32, low, high: i32) -> (clamped: i32, below, above: bool) = below = value < low above = value > high clamped = value if below then clamped = low end if if above then clamped = high end if end clamp ``` The shared form means the same as one entry per name, written in the same order. Each name gets what is written before the list, so `inout low, high: i32` makes both parameters `inout`. The fine print: - `a, b: u32 = 10` is refused in a binding, a struct field and an atom declaration: write a line for each name. - `low, high := bounds()` is not a shared declaration. It takes apart a multiple result ([0990]). - These take one name each as well: type declarations, functions, type and fixed formals, variant parts and condition bindings. ### [0110] The name is always on the left Left of `:` is always the name being introduced. Right of `:` is what fills it: a type, or, with `=`, a value. In a local declaration, the written type and the value both see only the names visible before the declaration. If an outer `t` names a type, `mut t: t = value` uses that type and then introduces the local `t`, and the statements after it see the local. A binding in a condition follows the same rule ([1070]). Module declarations and function signatures see all their names at once ([0130], [1290]). Control words are reserved everywhere a name could go (spec [1760]). `begin`, `match`, `loop`, `break` and `unchecked` cannot be variables, parameters, fields or labels, so `begin = 10` is an error. Call it `begin_value` instead. There is no escape for using a keyword as a name: writing `(begin)` does not make one. ### [0120] Declaring a type A type is declared like any other name, with `type` as its type. ```landin point: type = struct x: f32 y: f32 end point ``` ### [0130] Order does not matter in a module Inside a module, you may use a name above the line that declares it. The compiler collects every name before resolving any. ```landin twice_answer: () -> (n: i32) = n = 2 * answer_value -- answer_value is declared below end twice_answer answer_value: i32 = 21 ``` The one exception is `linker.library` directives, which keep their source order for linking ([1590]). ### [0140] Shadowing A name in an inner scope may hide the same name from an outer one. ```landin step_limit: u32 = 100 shadow_demo: (extra: u32) -> (result: u32) = result = step_limit begin step_limit := extra -- a new local; the module's step_limit is untouched result += step_limit end end shadow_demo ``` Two declarations of one name in the same scope are an error (spec [1850]). ## NUMBERS AND LITERALS ### [0150] Integer types The integer types are `u8`, `u16`, `u32` and `u64`, and the signed `i8`, `i16`, `i32` and `i64`. 128-bit integers are not in Landin yet. They are planned, for when a program needs them (Language evolution, in [the roadmap](ROADMAP.md)). Odd widths such as `u4` or `u12` exist only as fields of packed register images ([0730]): - Reading one gives you the next ordinary width up, so a `u1` field reads as a `u8` holding 0 or 1. - A one-bit flag is spelt `bool`, and a `u1` does not convert to or from `bool` on its own. ### [0160] Pointer-sized integers `usize` and `isize` are as wide as a pointer on the target. ### [0170] Floating point The float types are `f32` and `f64`. There is no `f80`. There is no `f16` yet either: neither baseline x86-64 nor Cortex-M0 has a half-precision instruction. It is planned (Language evolution, in [the roadmap](ROADMAP.md)). ### [0180] Booleans `bool` holds `true` or `false`. ### [0190] Integer literals take their type from where they are used An integer literal has no type of its own. It takes the type its context expects, and the compiler checks that it fits. ```landin tiny: u8 = 5 large: u64 = 5 -- bad: u8 = 300 is a compile error ``` Spec [1880] says exactly what counts as a context. ### [0200] With no context, an integer is an `i32` When nothing says what type an integer literal should be, it is an `i32`. ```landin plain := 5 ``` ### [0210] Float literals always have a point A float literal always looks like one, so an integer never quietly becomes a float, nor a float an integer. ```landin ratio: f32 = 5.0 -- bad: f32 = 5 is a compile error half := 1.0 / 2.0 -- 0.5 zero := 1 / 2 -- 0, integer division ``` When nothing says what type a float literal should be, it is an `f32`. ### [0220] Bases, separators and exponents Integers may be written in hex, binary or octal, and long numbers may use `_` to group digits. A float may carry an exponent. ```landin hex_value: u32 = 0xDEAD_BEEF -- too big for the default i32 bin_value := 0b1010_0101 oct_value := 0o755 big_value := 1_000_000 sci_value := 1.5e10 neg_exp := 1.0e-6 ``` The fine print: - A digit run starts and ends with a digit of its base. Underscores go only between digits, and may repeat, as in `1__000`. - A base prefix alone, such as `0x`, and a trailing underscore are errors. - In a float, both sides of the point and a written exponent need digits, with the same underscore rule. - A number has no suffix. A letter directly after one is part of it, so `1u64` is an error: put the type on the binding, as in `mask: u64 = 1`. ### [0230] Hex floats, for exact values A hex float literal states a float's bits exactly, subnormals included. ```landin pi_exact: f64 = 0x1.921fb54442d18p+1 smallest_subnormal: f32 = 0x1.0p-149 smallest_normal: f32 = 0x1.0p-126 ``` ### [0240] Infinity, NaN and negative zero The IEEE special values are named values of the float types, and unary minus gives their negative forms. ```landin neg_zero: f64 = -0.0 pos_inf: f64 = f64.infinity neg_inf: f64 = -f64.infinity quiet_nan: f64 = f64.nan neg_nan: f64 = -f64.nan ``` Constant folding keeps a literal's sign. The sign of a NaN that arithmetic produces is not specified. ### [0250] Character literals A character literal is one Unicode scalar, and its type is `u32`. ```landin letter_a := 'a' ``` A byte is a `u8`, so comparing one with a character takes a conversion: ```landin is_newline: (byte: u8) -> (yes: bool) = yes = byte == u8('\n') end is_newline ``` ### [0260] Text literals take their type from where they are used Like integers, a text literal takes its type from its context: `utf8`, `[]u8`, `utf16` or `cstring`. With no context, it is `utf8`. ```landin name: utf8 = "hello" cname: cstring = "hello" ``` Every text literal ends with a NUL byte that its length does not count, so passing one to C costs nothing. A literal lives in read-only storage, so you can never write through a reference to one, however the binding is declared ([0070]). For writable text, copy it into storage you asked for. ```landin -- greeting: []u8 = "abc" -- greeting[0] = 0x78 -- error, the literal is static ``` ### [0270] Escapes A backslash starts an escape. The set is small and closed: | escape | means | |---|---| | `\n` `\r` `\t` `\e` | newline, carriage return, tab, escape | | `\\` `\"` `\'` | the character itself | | `\xNN` | one byte, exactly two hex digits | | `\u{...}` | one Unicode scalar, any number of hex digits | ```landin line := "col\tsep\n" smile := "\u{1F600}" byte: []u8 = "\xFF" -- byte escapes require []u8 context ``` There is no octal escape and no `\0`; write `\x00`. An unknown escape is a compile error, never silently the character. `\xNN` is allowed only where bytes are meant, in a `[]u8`, and `\u{...}` only where text is meant, so a text literal can never hold invalid UTF-8. ### [0280] Raw text literals A raw literal sits between runs of at least three quotes, and nothing in it is escaped. If the text itself contains three quotes in a row, use four. ```landin help := """ usage: tool [options] -v verbose """ ``` The closing quotes' indentation is stripped from every line, so the block can sit indented in your code and still start at the left margin. Every line end between the quotes is part of the text. That includes the one just after the opening quotes and the one before a closer on its own line, so `help` begins and ends with a line end: `"\nusage: tool [options]\n -v verbose\n"`. For text that should start with its first line, as expected output usually should, start it on the opener's line. Nothing is stripped from that line, and the closer's indentation is still stripped from the lines after it. ```landin expected := """usage: tool [options] -v verbose """ ``` The fine print: - The whole opening run of quotes sets the count. Six quotes in a row are one opener of six, not an empty literal, and a matching closer must follow later. - For empty text, write `""`. ## OPERATORS ### [0290] Arithmetic The arithmetic operators are `+`, `-`, `*`, `/` and `%`. Integer division truncates toward zero, and the remainder takes the sign of the dividend, as in C. ```landin q := -7 / 2 -- -3 r := -7 % 2 -- -1 ``` ### [0300] Overflow traps; wrapping is a separate operator Integer overflow traps. When you want wrap-around, say so with `+%`, `-%` or `*%`. Each has an assignment form, such as `+%=` ([0390]). ```landin wrap_demo: () -> (ticks: u8) = ticks = 255 ticks +%= 1 -- wraps to 0 end wrap_demo ``` ### [0310] Conversions are written out Nothing converts implicitly, except that a writable reference passes where a read-only one is expected ([0440]). To convert, apply the type to the value, like a call. - If the value is known at compile time, an impossible conversion is a compile error; otherwise it traps at run time. - A float converts to an integer by truncating toward zero. - An integer converts to a float by rounding, and that never traps. ```landin -- bad: u8 = u8(300) compile error narrow_reading: (reading: u32) -> (small: u8) = small = u8(reading) -- traps if reading is above 255 end narrow_reading greeting_bytes: []u8 = []u8(greeting) -- the same bytes, not a copy whole_part := i64(45.7) -- 45: truncates toward zero ``` You can write the type directly, as `[]u8(greeting)` does here, rather than declaring an alias for it first. Either spelling means the same conversion. The fine print: - Type prefixes nest as they do in declarations: `[][2]u8(value)` converts to a slice of two-byte arrays, and `tag(u32, 7)(value)` to a parameterized type with every parameter given. The last parentheses hold the one value. - As with a call result, bind the result before you index it, select a field or call it. - A converted reference still refers to the same storage, and keeps its origin: where that storage lives, and so how long ([0770]). - `ptr u8(value)` applies the type `ptr u8`: it can take the pointer out of a distinct type ([0650]), but it never turns an integer into a pointer. `ptr(address)` does that, taking its pointer type from the declaration ([0460]). - A conversion does not say what type a float literal is, so the literal is an `f32` ([0210]). `u64(1.0e18)` would truncate the `f32` nearest 10^18, which is 999,999,984,306,749,440, so the compiler refuses it; write `u64(f64(1.0e18))` for the number written. `i64(45.7)` gives 45 at either width and is converted as it stands. ### [0320] Shifts `<<` and `>>` shift. Bits shifted out are gone and zeros come in, and a signed `>>` keeps the sign. There is one form of each. ```landin z: u32 = 1 << 40 -- 0 in a u32 context ``` The fine print: - The amount has the same type as the value being shifted. - An amount at or past the width gives zero on every shift, signed `>>` included; the amount never wraps around. - A negative amount is refused when the compiler knows it and traps when it does not. Exact rules: spec [1950]. ### [0330] Bitwise operators The bitwise operators are `&`, `|`, `^`, `~`, `<<` and `>>`. Unlike in C, they bind tighter than comparisons, so the usual mask test needs no parentheses. ```landin count_is_even := count & 1 == 0 -- means (count & 1) == 0 ``` ### [0340] Logical operators The logical operators are words: `and`, `or` and `not`. That leaves `!` free for errors. ```landin finished: bool = false keep_going := count < 10 and not finished ``` ### [0350] Comparison The comparisons are `==`, `<>`, `<`, `<=`, `>` and `>=`. Inequality is `<>`, not `!=`. Comparisons do not chain (spec [1820]). ### [0360] Ranges A range is written in a `for` header or a slice: `0..9` includes 9, and `0..<10` stops before 10. ```landin digit_sum: () -> (total: i32) = total = 0 for i in 0..9 do total += i end for end digit_sum ``` The same bounds select part of a slice, as in `items[0..<10]`. A range is not a value: you cannot store, pass or return `0..<10` on its own. There is no form that excludes the left end. For custom stepping, a library supplies an iterable value ([1330]). ### [0370] `sizeof`, `alignof`, `lenof` and `offsetof` These four measure things: the size of a type, its alignment, a length, and where a struct field begins. ```landin w1 := sizeof u32 -- 4 a1 := alignof u64 -- 8 o1 := offsetof reading_head.value -- 2: one byte of padding after sensor reading_head: type = struct sensor: u8 value: u16 end reading_head roll_die: () -> (face: u8) = face = 4 end roll_die measure_demo: (words: []u32) -> (total: usize) = samples: [8]u16 = zeroed total = lenof samples -- 8, known at compile time total += lenof words -- the slice's length, at run time total += lenof ([roll_die(), roll_die()]) -- 2; roll_die is not called end measure_demo ``` The fine print: - `lenof` measures a name, a field or element reached through it, or what a call returns. - A call whose result is measured runs. The elements of a measured literal, like the `roll_die()` calls above, are checked to have one type but not evaluated. - An array that a name or path reaches is not read, because its type holds its length. - `offsetof` gives a field's offset in bytes from the start of its struct type, through nested structs. - `lenof` and `offsetof` are not reserved: everywhere else, they are ordinary names. ### [0380] `addr` and `.val` `addr` takes an address, and `.val` is the thing a pointer points at. On the right of an assignment `.val` reads it, and on the left `.val` writes it. [0430] shows both. ### [0390] Assignment is a statement Assignment is a statement, never an expression, so it cannot hide inside a condition. The assignment operators are `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=` and `>>=`, plus the wrapping `+%=`, `-%=` and `*%=` ([0300]). ### [0400] No `++` and no `--` There is no `++` or `--`. The statements `inc` and `dec` do the job, though `x += 1` says the same thing. ```landin inc total dec total ``` ### [0410] Evaluation order is fixed Landin fixes the order in which things are evaluated, so you can see where costs happen: - operands and call arguments, left to right; - a struct's fields, in the order you write them, whatever order the layout puts them in; - `and` and `or`, left to right, stopping as soon as the answer is known; - an assignment, its destination first, then the value. A deferred call is the one thing not evaluated where it is written; [1100] says when it runs. ### [0420] What the dot means The dot always selects a member of something: | example | selects | |---|---| | `p.val` | what a pointer points at | | `t.less` | an entry of a concept | | `http.get` | a member of a module | | `f64.nan` | a named value of a type | The tokens `..` (a range), `...` (an inferred error set) and the decimal point are separate things. ## FUNCTIONS ### [0870] Declaring a function A function is a name bound to a value of a function type. There is no `fn` keyword. In every function, `=` opens the body and `end` closes it. ```landin double: (x: i32) -> (r: i32) = r = x * 2 end double ``` Results have names, as parameters do. The body sets `r` by assigning it, and the caller gets whatever `r` holds when the body ends. ### [0880] One-line functions When the body is a single expression, write that expression after `=`. Its value fills the named result. The function still takes an `end`. ```landin triple_it: (x: i32) -> (r: i32) = x * 3 end ``` A longer body may end with a value too ([1080]), and that value is the result, whatever the body assigned to it before: `code = 0 1` is two statements and returns 1. The compiler warns of a value written after the result was assigned (L0693). ### [0980] Calling: positional, then named A call gives its positional arguments first and its named arguments after them. Every parameter gets exactly one argument: there are no default values. ```landin volume_of: (width: u32, height: u32, depth: u32) -> (v: u32) = v = width * height * depth end volume_of volumes: () -> (total: u32) = a := volume_of(2, 3, 4) b := volume_of(2, depth: 4, height: 3) c := volume_of(width: 2, height: 3, depth: 4) total = a + b + c end volumes ``` The positional arguments fill parameters in order. The named ones may come in any order after them. An unknown or repeated name is an error. Arguments are evaluated in the order you wrote them. Named arguments work in a call statement as well as in a call expression. The fine print: - A call through a stored function uses the parameter names of that value's type. Those names are not part of function-type identity ([1000]). - A generic call may name its compile-time arguments in the same list: `copy(t: u8, n: 4, source: bytes)`. Name one and you name them all ([1290]). - A C variadic call adds an unnamed tail ([1580]). It does not add optional parameters. ### [0890] Returning nothing, and never returning `none` means the function returns normally with no value. `noreturn` means it never returns at all. ```landin log_it: (m: utf8) -> none = end log_it halt_it: () -> noreturn = loop do end loop end halt_it ``` A function that returns nothing still writes `-> none` after its parameters: leaving the returns out, `f: (x: i32) =`, does not spell it, and neither do empty parentheses, `-> ()`. The body of a `noreturn` function has to diverge on every reachable path: an unconditional `loop` with no exit, or a call to another `noreturn` function. A conditional loop does not count, even if you expect it to run forever. A call to a `noreturn` function ends the path it is on, so a branch that calls `halt_it()` needs no value of its own. The fine print: - `noreturn` is part of the function's type. A `() -> none` function cannot stand in for a `() -> noreturn` one, and a `() -> noreturn` function cannot stand in for a `() -> none` one. - A `noreturn` function declares no errors ([0940]), because failing would return to the caller. - Calling a `noreturn` function does not unwind `defer` ([1100]). A deferred `noreturn` call stops the cleanup that would follow it, and the original exit. - C declarations may use `noreturn`. Interrupt and naked handlers stay `() -> none`. ### [0920] Several results A function can return several named results. ```landin divide: (a: i32, b: i32) -> (quot: i32, rem: i32) = quot = a / b rem = a % b end divide ``` Two or more results travel together as one anonymous struct, laid out in the order you wrote them. A single result is its own type, with no struct around it. ### [0930] Every result is assigned before returning A function must assign each named result on every path that returns. The compiler checks this, so there is no "uninitialised return value". A path that fails ([0940]) need not assign the results, and the caller cannot read them on that path. ### [0990] Using a multiple result The results of a call form an anonymous struct ([0920]). Bind it whole and read its fields, or take it apart by name. You never take it apart by position. ```landin whole := divide(10, 3) sum := whole.quot + whole.rem (quot, rem) := divide(10, 3) (quot: q2) := divide(20, 3) (quot, _) := divide(30, 3) ``` The call runs once. When you take the result apart, you can pick names in any order, leave some out, or rename one after `:`. `_` says that you ignore the rest on purpose. A whole result can also be the value of an `if`, `match` or block when every branch gives the same names and types. The names belong to the call, not to the function's type. Two function types with the same result types in the same order agree, whatever the results are called ([1000]). ### [1020] Throwing a result away You cannot ignore a result silently. To throw one away, say so with `_ =`. ```landin _ = double(5) ``` A function that returns `none` gives the caller nothing to discard. Write its call on its own: `_ =` in front of it is an error (spec [1930]). ### [0900] Three parameter conventions A convention says what the function may do with the value you hand it. It is about the argument itself, never about what the argument points at: the pointer type says that ([0450]). | convention | what it promises | | --- | --- | | nothing written | I will not change the value: the parameter is read-only. | | `inout` | I may replace it, and the change comes back to the caller. The argument must be mutable. | | `sink` | I consume it. The place the caller named is dead afterwards ([0910]). | The read-only convention has no word. Writing `in` on a parameter is refused: leave it off. There is no `out` convention either: outputs are named results. In this example, `[]u8` is a slice of bytes, a view of someone else's bytes ([0570]): ```landin process: (source: []u8, inout target: []u8, sink owned: []u8) -> (written: u32) = written = 0 end process ``` Because a convention is about the argument itself, a function that writes device registers through a pointer, but never re-points it, takes the pointer read-only. The `mut` lives in the pointer type ([0430]). `escaping` is a separate word that can go with any of the three conventions. It says that the function may keep what a pointer, slice or `any` refers to after the call returns, so the caller has to show that it lives long enough ([0780]). `sink` and `escaping` do different jobs: `sink` makes the caller's place unusable afterwards, and `escaping` lets the callee keep a reference. The two can go together. On a type parameter, `escaping` asks nothing when the type holds no references ([0840]). The fine print: - An `inout` argument need not be a binding: a pointer target such as `c.inner.val` is fine. - One call may not pass the same variable, or a field of it, to two `inout` parameters. - Two different pointer or computed-index paths may still alias. The compiler cannot see that, and does not promise to ([1720]). ### [0910] `sink` consumes a place A `sink` argument is a place. After the call, that place is dead until you assign it again. A field of a binding is a place, so consuming a struct's field needs no temporary. ```landin message: type = struct body: []u8 size: u32 end message release: (sink bytes: []u8) -> none = end release clear_message: (inout m: message) -> none = release(m.body) -- m.body is dead from here m.body = [] -- and live again from here m.size = 0 end clear_message ``` Reading `m.body` between those two lines is an error. The check closes the window between releasing storage and repointing the field, which a temporary binding would have left open. This is a use-after-consume check on one place, not ownership. The value is still copyable: a copy made before the sink stays live, and the compiler does not catch consuming through both. The fine print: - The place is a path from a binding through fields and literal fixed-array indexes. The compiler refuses a path through a pointer (`p.val.items`), a computed index (`xs[i].items`) or a slice index. A whole slice may be sunk. - A field sunk out of an `inout` parameter must be assigned again before every return, failure included. A `defer` or `undo` may do it. - Arguments are evaluated left to right first, and the places are consumed as the call begins. So `use(value, value.count)` is fine when `use` sinks its first parameter. - The compiler refuses a call that sinks one place twice, or that sinks a place it also passes `inout`. Exact rules: spec [1910]. ### [1040] Passing the call site: `caller` The compiler fills in a `caller` parameter with where the call was written, so assertions and logging need no macros. The parameter's type is a struct you declare, with exactly these three `u32` fields, in this order: ```landin site: type = struct file_id: u32 line: u32 column: u32 end site report_failure: (where: site) -> none = end report_failure assert: (cond: bool, caller where: site) -> none = if not cond then report_failure(where) end if end assert ``` A call looks like this: `assert(count > 0)`. The caller leaves the parameter out. Inside the function, the parameter is an ordinary immutable struct that you can read, copy and store. It is 12 bytes on every target. Line and column count from one. The file number is only a number. The table that maps it to a filename is written beside the program and need not ship with it, which keeps names out of firmware ([1670]). A wrapper that wants to report its own caller's position passes its `caller` parameter on by name: ```landin checked: (cond: bool, caller where: site) -> none = assert(cond, where: where) end checked ``` Leave out `where:` there and the report points at the wrapper's own call instead. Only a `caller` parameter can fill a `caller` position: a copied or constructed `site` cannot. A check that stops the program gives its `caller` parameter to `compiler.unreachable` ([1560]). The stop is then reported at the call, through any wrappers that passed the parameter on, and not at the check: ```landin require: (cond: bool, caller where: site) -> none = if not cond then compiler.unreachable(where) end if end require ``` `core/panic` declares this struct as `panic.call_site` and this check as `panic.require`, so a program that wants one imports it rather than writing its own. This `site` is not the `site` that a panic handler receives at [1670]. That one is a single `u32` number, which the compiler gives a failing check. Exact rules: spec [1920]. ### [1000] Functions are values A function type is an ordinary type, written the way a signature is. A function is a value of that type: a code address. There is no separate function-pointer type, and you never write `addr` on a function. ```landin default_handler: () -> none = end default_handler handler: type = () -> none mut current: handler = default_handler ``` Two function types agree by their parameter and result types, in order: - The names inside them only describe the positions. - The comparison is recursive when a parameter or result is itself a function. - Calling convention and variadicness count too. A C callback type is written `extern(c) (parameters) -> returns`, and a Landin function never matches it. A module binding set to a declared function is a fixed code address. A mutable binding may later take any function with the same complete signature. A `ptr` to a function type points at a cell that holds the address, not at the code. A function captures nothing ([1010]), so a callback is a function and an explicit state pointer: ```landin on_byte: type = struct call: (state: ptr u8, b: u8) -> none state: ptr u8 end on_byte ``` Call it through the field: `callback.call(callback.state, byte)`. The field keeps its full signature through every copy, assignment, variant payload and array. Whether the field may be replaced depends on the binding that holds the struct. The callee is evaluated before the arguments. ### [1010] A callback is a named function There are no anonymous functions. A function value is always a declared function, passed by its name. Declare the callback beside the code that uses it: ```landin less_i32: (a: i32, b: i32) -> (yes: bool) = a < b end less_i32 pick: (a: i32, b: i32, before: (a: i32, b: i32) -> (yes: bool)) -> (first: i32) = first = b if before(a, b) then first = a end if end pick smaller: (a: i32, b: i32) -> (first: i32) = pick(a, b, less_i32) end smaller ``` Naming a function makes a value of its address; it does not run the body. A function captures nothing: inside, it sees module declarations and its own parameters, results and locals, and nothing of the function that passes it. State travels as an explicit argument: ```landin add_to: (total: ptr mut u32, b: u8) -> none = total.val += u32(b) -- `.val` is what a pointer points at ([0430]) end add_to each_byte: (bytes: []u8, total: ptr mut u32, visit: (total: ptr mut u32, b: u8) -> none) -> none = for b in bytes do visit(total, b) end for end each_byte ``` `each_byte(bytes, addr sum, add_to)` adds every byte to `sum`. To keep the function and its state together, store both in a struct, as the callback at [1000] does. ## TYPES YOU DECLARE This section covers atoms, structs, variants, and types made from other types. Device register images are also types you declare; they are with the machine-level material at [0730] and [0740]. ### [0630] Atoms An atom is a name that is its own value and its own type. Declaring one gives you both at once, because for an atom the value and the type are the same thing. ```landin not_found: atom no_access: atom ``` Atoms compare with `==` and `<>`, and nothing else. Two atoms are equal when they are the same declaration, even when the values come from two different atom sets: ```landin is_missing: (outcome: not_found | no_access) -> (missing: bool) = missing = outcome == not_found end is_missing ``` As far as your program can tell, an atom has no number behind it: it is not ordered, and it does not convert to or from an integer. ### [0640] Enumerations are unions of atoms An enumeration is a union of atoms. Declare the atoms, one a line ([0100]), then the union. ```landin north: atom south: atom east: atom west: atom compass: type = north | south | east | west ``` You may also write the union in place, as the type of a binding, a parameter, a return or a field. It is then the same type as the declared name: `facing: (way: north | south) -> (ahead: bool)` takes a `compass` value that is north or south. As the element of an array, a slice or a pointer, the union needs its name. An atom set can be an array element, a struct field or a variant payload, and it stays that set there. A write needs one of its members, and reading it back gives you an atom, not an integer. ### [0650] Distinct types `distinct` makes a new type that has its base's representation and never mixes with its base or any other type. Comparison comes along, and so do the bit operations of an unsigned base. Arithmetic does not. ```landin meter: type = distinct f32 second: type = distinct f32 ``` You cannot add a `meter` to a `second`. You cannot even add two `meter` values, because `f32`'s arithmetic stays with `f32`. To get a value in or out, apply the type, as for any conversion ([0700]): ```landin length: meter = meter(2.5) raw: f32 = f32(length) ``` That separation is the whole point: the compiler keeps the type apart from its base and from every other distinct type, at no runtime cost. Generic deduction and conformances tell it apart too, and an alias of it keeps its identity. A few things do carry over, because they ask nothing of what the value means: - Equality. `==` and `<>` work when the base has them: a scalar, an atom set, a pointer or a function value. A descriptor compares without taking its number out. - Ordering, when the base is a scalar. `<`, `<=`, `>` and `>=` order as the base does. - Flags, when the base is an unsigned integer. `&`, `^`, `|` and `~` give the same distinct type, and `&=`, `^=` and `|=` update in place, so a set of flags stays one. - The zero image. A record that holds a distinct value may be `zeroed` ([0540]), though `zeroed` written for the distinct type itself does not construct it. ```landin farther: (a: meter, b: meter) -> (yes: bool) = yes = a > b end farther ``` The fine print: - Shifts stay with the base, as arithmetic does. - A distinct value meets its base or any other type only through a conversion, and that includes comparing with it. - A wrapped reference keeps its origin. Exact rules: spec [1890]. ### [0660] A value inside a range Landin has no range type. A value known to lie in a range is a `distinct` type ([0650]) over its base, made by a function that checks the range. ```landin percent: type = distinct u8 out_of_range: atom to_percent: (raw: u8) -> (p: percent) ! out_of_range = fail out_of_range when raw > 100 p = percent(raw) end to_percent ``` The check runs once, where the value is made. Whatever takes a `percent` afterwards trusts it and checks nothing ([1730]). No constant is refused at compile time for being out of range: `to_percent(200)` fails when it runs. To do arithmetic on a `percent`, or to compare it with a plain integer, convert it back with `u8(p)`. A check that should stop the program rather than fail can call `compiler.unreachable` ([1560]) instead of `fail`. The language does not enforce the range. A distinct type's conversion from its base is open to any code, so nothing stops another function writing `percent(200)`. Keeping that conversion inside the checking function is a habit, not a rule the compiler checks. Writing `u8 range 0..100` is refused, and the report names this replacement: the `distinct` declaration and a checking function. It offers no automatic fix. Every place that stored a `u8` into a `percent` has to change too, and only the program knows whether a value out of range fails, traps or cannot happen there. ### [0670] Structs A struct type is declared as a block: `struct`, a field a line, and `end` with the type's name. ```landin size2: type = struct w: u32 h: u32 end size2 ``` A struct is nominal: two separately declared structs with the same fields are different types. An alias keeps the original identity. The fine print: - There is no one-line spelling: `size2: type = (w: u32, h: u32)` is refused. Parentheses with named entries write parameter lists, result lists and payloads, which are not type declarations. - Each field takes its own line and one name ([0100]). - A struct may take type and fixed parameters, and `layout` ([0750]) goes before `struct`. The parameters are compile-time names: they add no field and no hidden runtime argument. - Each fully applied instance of a parameterized struct is its own type. The declaration and all its arguments identify it, even an argument the fields do not use. Aliases of the arguments make no new type. A different argument does, even when the fields and layout come out equal. - A struct may mention itself, or another struct that mentions it back, in a function parameter or result. A function field is one code address, so the layout stays finite. ### [0680] Structs with a variant part A struct may end in a variant part: one of several cases, each with its own fields. The fields that every case shares are ordinary fields of the struct. ```landin figure: type = struct label: utf8 area: f32 kind: variant circle: (radius: f32) | rectangle: (width: f32, height: f32) end kind end figure ``` ### [0690] Cases with no payload A case with no fields is written bare. A bare case is an atom, like any other ([1700]), so a variant part reads as a union of its cases. ```landin node_kind: type = struct kind: variant leaf | branch: (first: u32, count: u32) end kind end node_kind ``` You write a case where its variant part is the context: when you construct into that part, and when you name an arm of a match on it. A case is not a value apart from its part, and the part is not a value apart from its struct: copy the struct, or match it. Selecting a case costs the size of that case, not the size of the largest one, because of what it writes: - Selecting a bare case writes only its tag. - Selecting a case with fields zeros that case's fields first, then writes the ones you gave. - The bytes of the inactive cases and the padding are unspecified afterwards, though `zeroed` still writes the whole struct as zeros. ### [0700] Constructing values and converting them Construction and conversion look the same: a type applied to arguments. ```landin origin := point(x: 0.0, y: 0.0) metres := meter(1.5) ``` A variant case is built the same way, with the case name applied to its fields. To read a case back, use `match` ([1210]). ```landin mut f: figure = (label: "disc", area: 0.0, kind: circle(radius: 2.0)) f.kind = rectangle(width: 3.0, height: 4.0) ``` ### [0710] Struct literals take their type from context A struct literal has no type of its own, like a number literal. It takes the named struct type that its context wants. A struct type written inline is not yet such a context: declare the type and use its name (spec [1830]). ```landin here: point = (x: 1.0, y: 2.0) ``` What does not convert is a value that already has an anonymous struct type, such as a call's results. `divide(10, 3)` gives `(quot: i32, rem: i32)`, and that value never becomes a named struct with the same fields. Two anonymous types match when their field names, types and order all match. At module scope, a struct literal is a static image that the compiler builds, not code run before the entry point ([1460]). Exact rules: spec [1940]. ### [0720] Filling the remaining fields with `of` `of` at the end of a struct literal fills every field that the literal did not name. It is the same word in the same place as in array literals ([0560]). ```landin window: type = struct width: u32 height: u32 visible: bool resizable: bool end window main_window: window = (width: 640, height: 480, of false) tiny_window: window = (width: 1, of zeroed) ``` The fill has to typecheck for each field it fills: `of false` works where the rest are `bool`, and `of zeroed` ([0540]) wherever the rest have a zero image. This is not a default value. Declarations have none ([0980]), because a new parameter would then fit every existing call silently. Here whoever writes the literal makes the choice. The trade is theirs too: a literal with `of` picks up a field added later without a word, and one without it breaks loudly. The fine print: - A fill other than `zeroed` needs at least one omitted field, and all of the omitted fields must then have exactly the same type, array length and reference permission included. - The fill is evaluated once, after the named values, and copied into each remaining field in declaration order. ### [0750] Field order and layout Fields stay in the order you wrote them, with natural alignment and padding in between. A hexdump matches the source, and the layout does not shift under a new compiler or an optimization flag. ```landin packet: type = layout(c) struct kind: u8 length: u16 -- big-endian as the wire sent it id: u32 end packet from_big_u16: (wire: u16) -> (value: u16) = value = (wire << 8) | (wire >> 8) -- on a little-endian target end from_big_u16 ``` You ask for another layout by name: | layout | what it does | |---|---| | no `layout` | source order, natural alignment | | `layout(c)` | the selected target's C rules (spec [1975]) | | `layout(c, packed)` | C's byte-packed record: every field at alignment one, no padding | | `layout(packed)` | a register image of bits ([0730]) | Byte order is not a property of a field. A field holds the target's own order, which `compiler.byte_order` names ([1560]). When your program reads or writes another order, it converts where the bytes cross, with shifts ([0320]) or an ordinary function, as `from_big_u16` does above. That way the cost is visible where it is paid. The fine print: - No layout reorders fields. For the smallest struct, write its fields largest alignment first. - `layout(c)` does not choose a function's calling convention. A C record holds native-endian scalars, fixed arrays, nested nonempty C structs and callback fields declared with C's convention. - A `layout(c, packed)` record's fields are read and written by copy and have no address of their own. C takes such a record through a pointer. - A C record's last field may be `[0]T`, C's flexible array member, whose elements follow the record in memory. - Every byte count comes from the selected target, 32-bit targets included. Initializers still run in the order you wrote them ([0410]). ### [0760] Attributes Attributes are prefix words from a closed set. Their arguments are always in parentheses. Where an argument is one of a fixed set of values it is an atom; a linker name is a string. These are the words, with the arguments each takes: | word | arguments | where it is described | |---|---|---| | `mut` | none | [0060] | | `public` | none | [0090] | | `layout` | `c`, `packed`, or `c, packed` | [0730], [0750] | | `escaping` | none | [0780] | | `caller` | none | [1040] | | `fixed` | none | [1490] | | `option` | none; it implies `fixed` | [1530] | | `link` | `symbol: "..."`, `thread`, `section: "..."`, `region: "..."`, `align: 16`, `vector: 16`, `keep`, `boot_stage` | [1610], [1615], [1640] | | `extern` | `c`, `interrupt`, `naked`, and others | [1570] | `at` gives a field its bit position ([0730]). `at`, `of` and `align` are contextual: a field or an entry may still be called one of them, because nothing reads the word as an attribute there. Placement alignment is `link`'s `align` label ([1640]), not a word of its own. `from` and `with` are reserved and cannot name anything. Landin has none of these attributes: - `volatile`: a device access is an operation ([0740]). - `big` or `little`: byte order is converted where bytes cross ([0750]). - `inline` or `noinline`: inlining is the optimizer's decision ([1310]). - `weak`: a whole program links one definition per name, and the compiler-owned vector image does what weak default handlers do in C ([1640]). ## CONTROL FLOW Every construct opens with its own word and closes with `end`, so you never count braces. The short snippets in this section are statements. Read them as standing inside a function that has a parameter `x: i32`, a writable slice `items: []mut i32`, a path `path: utf8` and a result `out: i32`. Helpers such as `is_ready()`, `expensive()` or `cleanup()` stand for functions that do what their names say. ### [1050] Branching with `if` `if` takes a condition, and `then` begins the body. `elsif` and `else` are optional, and `end if` closes the whole thing. ```landin if x > 0 then out = 1 elsif x < 0 then out = -1 else out = 0 end if ``` The condition has type `bool`. No integer or pointer stands in for a `bool`. ### [1060] Every construct fits on one line No construct needs a newline. `end` is what closes a construct, so you can write any of them on one line. ```landin if x > 0 then out = 1 end if ``` `refine fmt` leaves a one-line form on one line. It never joins lines and never breaks them. ### [1070] Declaring a name in a condition An `if`, `elsif` or `while` condition may declare a binding, inferred or with a written type. The binding's value is the condition, so it must be a `bool`; anything else is an ordinary type error. ```landin if ok := is_ready() then out = 1 end if while mut more: bool = has_more() do consume_next() more = false end while ``` - The name exists only in the body that its condition guards. It does not exist in a later `elsif`, in the `else`, or after the construct. - The initializer runs before the name exists, so it cannot refer to the name it initializes. - A `while` runs the initializer again before every iteration. Exact rules: spec [1840]. ### [1080] Blocks have values `if`, `match`, bare blocks and loops are expressions as well as statements. The value is the last expression of the block that ran. ```landin sign := if x > 0 then 1 else -1 end if doubled := begin a := expensive() a * 2 end ``` Rust needs a semicolon to tell a block's value from a statement. Landin does not: you always write `_ =` to throw a value away ([1020]), so a bare expression at the end of a block can only be its value. The details, arm by arm: - Every arm that falls through must end with a value of one complete type and shape. An `if` used as a value therefore needs its `else`. - An arm that leaves by `return`, `fail`, `break` or `continue` supplies no value and needs no placeholder. - When the compiler decides whether a name is assigned after the construct, only the arms that fall through count. An arm that has left proves nothing for the others. - Statements and the final expression run in source order. They run after the `if` condition or the `match` subject, and only in the selected arm. - In a construct used as a statement, an arm may not end with a value: nothing would take it. Exact rules: spec [1910]. ### [1090] Bare blocks: `begin ... end` `begin ... end` opens a scope: names declared inside are gone after its `end`. ```landin begin tmp := x * 2 out = out + tmp end ``` Give the block a label, `name: begin ... end name`, and a `break name` can leave it early. Its cleanups then run as a loop's do ([1180]). ### [0940] Errors: what can fail is in the signature A function that can fail lists, after `!`, the atoms it can fail with, and `fail` leaves with one of them. An atom is a declared name that is its own value, such as `port_zero: atom` ([0630]). A caller cannot ignore a failure: at every call to a failing function, it either passes the failure on or handles it. Here is all of it at once. `port_from` reads a port number with the library's `text.to_u32`, which fails on bad digits, and adds a failure of its own. Its two callers then deal with the result in different ways: ```landin import core/text port_zero: atom port_from: (digits: utf8) -> (port: u32) ! text.invalid_number | text.number_overflow | port_zero = port = try text.to_u32(digits) fail port_zero when port == 0 end port_from listen_port: (setting: utf8) -> (port: u32) = port = port_from(setting) else 8080 end listen_port port_or_complaint: (setting: utf8) -> (port: u32, complaint: utf8) = complaint = "" port = port_from(setting) else (problem) match problem port_zero: complaint = "port 0 is reserved" _: complaint = "not a port number" end match 8080 end end port_or_complaint ``` - `try` passes a failure on: if `text.to_u32` fails, `port_from` fails with the same atom, which is why its `!` lists them ([0960]). - `listen_port` cannot fail. Whatever went wrong, 8080 stands in for the result. - `port_or_complaint` binds the atom to `problem`, looks at it, and ends the block with the value that stands in ([1030]). A call to something that can fail takes one of four forms: | you write | when the call fails | |---|---| | `try f()` | your function fails with the same atom | | `f() else value` | `value` stands in for the result | | `f() else (e) ... end` | the block runs with the atom bound to `e` | | `f() else none` | nothing; the next statement runs | The next entries use a shorter declaration. Its atoms, `not_found` and `no_access`, are the ones declared at [0630]: ```landin open_file: (path: utf8) -> (handle: u32) ! not_found | no_access = fail no_access when lenof path == 0 handle = 1 end open_file ``` Three facts about error sets and their atoms: - An error set is a set. Aliases flatten, order does not matter, and a function that fails with `a` passes where `a | b` is expected. - The atoms carry no payload. - The atoms travel in a register of their own, so failing costs about what returning does. Exact rules: spec [1980]. ### [0960] Passing a failure on: `try` `try f()` calls `f`. If `f` fails, your function runs its cleanups ([1100]) and then fails with the same atom. Every atom you might pass on must be in your own `!` set. ```landin read_config: (path: utf8) -> (data: []u8) ! ... = h := try open_file(path) data = [] end read_config ``` The `try` sits at the call, so you can see in the source every place a function may leave early. `! ...` means "whatever my callees can fail with": the compiler works the set out from every `fail` and `try` in the body. An inferred set that comes out empty means the function cannot fail. Use `! ...` inside a module, where the compiler sees every caller anyway. These must write their set out: - Anything public, because a public signature is a promise, and a change three modules down must not rewrite it silently. - Function types, concept entries ([1260]) and anything exported to C, because their complete signature is their type. A traversal whose steps can fail is a `while` whose body takes each item with `try` ([1150]). The enclosing function must declare or infer the atoms, and its caller handles them with the ordinary `else` on that call. Exact rules: spec [1980]. ### [1030] Handling a failure: `else` An `else` after a call handles its failure on the spot. The handler either supplies a value in place of the result, or leaves. Leaving is `return`, `fail`, `break` or `continue`, written in a block, as `else begin return end`. ```landin h1 := open_file(path) else 0 h2 := open_file(path) else (e) fail e end h3 := open_file(path) else (e) match e not_found: 0 _: fail e end match end ``` `try f()` is short for the second line's form. A handler that leaves needs no value, the same rule an arm of an `if` follows ([1080]), so nobody invents a placeholder to satisfy the type. The handler supplies the value; it does not assign the binding being initialized. - `else (e)` binds the atom. `e` has the call's whole error set and exists only inside the block. A `match` on it must cover every atom, or end with one `_` arm for the rest ([1210]). - A name the block never reads draws a warning. To run statements without naming the atom at all, give `else` a bare block as its value: `else begin ... end`. The compiler refuses `else (_)`; leave the parentheses out instead. - A call that returns nothing has no value to supply. Its block only handles the error, and the statement after the call runs next. - The result may have any shape, from a scalar to a struct or several named results. A failing call needs `try` or `else` even when you throw its result away. `else` handles only declared failure: a result that is a union, such as [0480]'s maybe-pointer, is taken apart with `match`. Inside an `if` arm, `else value` after a call is the `if`'s own `else`, which is how `if c then a() else b() end if` reads. To handle the call's failure there, parenthesize it, `(open_file(path) else 0)`, or bind the error: `else (e)` always belongs to the call, wherever it is written. The same holds for `else begin ... end`. When an arm's lines go on after it, as in `count := encode(c) else begin fail bad end` followed by more lines of the arm, the compiler reports that `else`: the layout shows you meant the call's recovery, and the fix is the same, bind the error or parenthesize the call. A handled call is an expression, so it also works inside a larger one, as an operand or an argument: ```landin next_handle := (open_file(path) else 0) + 1 ``` When a call returns nothing and its failure does not matter where the call is made, one word says so. Here `flush` writes out a buffer and returns nothing: ```landin flush(out) else none ``` `else none` is the bound block with nothing in it, minus the name nobody would read: what the call did before it failed stays done, and the next statement runs. On a call that returns a value, `else none` is allowed only when the whole call is discarded with `_ =`. Anywhere else, a failure would leave a result unset that something reads. Here `parse_header` returns a value: ```landin _ = parse_header(input) else none ``` Used any other way, that call needs `else value`, a block, or `try`. ### [0970] Leaving early: `return` and `fail` `return` leaves the function with its named results as they stand, and `fail` leaves with an error. Each takes an optional `when condition`. ```landin clamp_low: (x: i32, floor: i32) -> (r: i32) = r = floor return when x < floor r = x end clamp_low ``` Only exits take `when`: `return`, `fail`, `break` and `continue`. ### [0950] What deserves an error, and what does not A failure ends the operation without a result, and the caller handles it. A diagnostic is reported while the work goes on. Choose by what the caller needs: no result at all, or a result with notes about what was wrong. Where you can see a problem in what you already hold, prefer checking for it and working around it to failing. `sum_digits` notes a problem instead of failing on it. It adds the digits in a line and counts what it had to skip, so every line still gets a sum: ```landin --- Adds up the digits in a line and counts what is not a digit. sum_digits: (line: []u8) -> (sum: u32, skipped: u32) = sum = 0 skipped = 0 for b in line do if b >= u8('0') and b <= u8('9') then sum += u32(b - u8('0')) else inc skipped -- noted, and the work goes on end if end for end sum_digits ``` - A parser is the usual case: a syntax mistake is entirely in the bytes it is reading, so it records a diagnostic and carries on. One that stops at the first mistake hides the other twelve. - Input with no usable answer may well be a failure: [0940]'s `port_from` fails on text that is not a port, because its caller has no port to use. - Out of memory, a missing file, an unplugged device: these depend on the world, not on your data, and checking first would only be a race. They are failures. Collecting diagnostics needs somewhere to put them, and that is an ordinary parameter. The library's destination for diagnostics is the concept `core/diag.log`. A function takes it as `inout log: any diag.log`, meaning any kind of log at all ([1370]). Its `note` entry takes a position in the text, a severity and the message bytes. Recording a note is a diagnostic; failing to record it is an operation failure. So `note` declares `io.io_failed`, and a function that records notes lists it too. - A bounded logger never fails. When it is full it stops keeping entries, counts them in `dropped`, and still records whether an error was reported. - A streaming logger writes as it goes, and fails with `io_failed` when a write does. - Both pass as `any diag.log`, so the producer does not know which policy its caller chose. The sink is a capability ([1680]): passing one makes the destination explicit, though the parameter list alone does not prove that the function cannot make another sink or reach the host. ### [1100] Cleanup on the way out: `defer` `defer call` runs the call when its block is left: by falling off the end, `return`, `break`, `continue` or a failure. Entries run in reverse order, inner blocks before outer ones. ```landin defer cleanup() ``` There are no destructors, so this is how anything gets closed, flushed or freed. The call's arguments are read when it runs, not when the `defer` is written. Here `walk_steps` leaves `trail` at 2, not 1: ```landin record_step: (inout trail: i32, step: i32) -> none = trail = step end record_step walk_steps: (inout trail: i32) -> none = mut step: i32 = 1 defer record_step(trail, step) step = 2 end walk_steps ``` - At exit, the callee is evaluated first, including a function field, then the arguments, reading the places they name at that moment. So a `defer` that sinks something sinks it at the end, and the thing stays usable in between. If a place was re-pointed meanwhile, the `defer` sees what is there now. - Registering an entry evaluates nothing, costs nothing and reserves nothing. - An entry counts only once control has reached it. A `return` above the `defer` does not run it. - The block's value, or its failure atom, is settled before the deferred calls run. - A trap stops the program and runs no cleanup. ### [1110] Cleanup only on failure: `undo` `undo call` is a `defer` that runs only when a declared failure leaves its block: a `fail`, a `try` that passes a failure on, or a failure arriving from a deeper call. ```landin undo release(handle) ``` It is its own word, not a flavour of `defer`: to defer is to do it later, and this may never be done at all. It is a compensating action. - Falling off the end, a successful `return` and `break` skip it. So does a trap: it stops the program and unwinds nothing. - A caller's `else` that handles the failure does not leave the caller's block, so the caller's `undo` entries do not run. The failing callee's own entries have already run on the way out. - In one block, `defer` and `undo` entries share one order: on failure they run interleaved, in reverse order of writing, inner blocks first. - Like `defer`, an `undo` evaluates its callee and arguments only when it runs, and sees their values then. ### [1200] Cleaning up several acquisitions An entry exists only once control reaches it. A run of fallible acquisitions therefore cleans up exactly what it got: if the first fails, nothing is released; if the second fails, one is; if the third fails, two are. ```landin close_file: (handle: u32) -> none = -- hand the handle back to the system end close_file open_three: (a: utf8, b: utf8, c: utf8) -> (first: u32, second: u32, third: u32) ! not_found | no_access = first = try open_file(a) undo close_file(first) second = try open_file(b) undo close_file(second) third = try open_file(c) end open_three ``` The same shape holds for memory. This version is generic over the allocator, which [1290] and [1360] explain: ```landin new_buffers: (provider: type is mem.allocator, memory: provider, count: usize) -> (first: mem.byte_buffer, second: mem.byte_buffer, third: mem.byte_buffer) ! mem.out_of_memory = first = try mem.allocate_bytes(memory: memory, count: count) undo mem.release_bytes(memory, first) second = try mem.allocate_bytes(memory: memory, count: count) undo mem.release_bytes(memory, second) third = try mem.allocate_bytes(memory: memory, count: count) -- All three owners are published by the successful return. end new_buffers ``` `undo` cleans up what is still yours. Once you hand a resource on, its cleanup is somebody else's, but your entry is still registered, and there is deliberately no way to call one off. So acquire everything fallible first, commit afterwards, and let nothing fallible stand between the commit and the end of the block. The usual alternative is a flag and a conditional `defer`. Forget to set the flag and you free storage that is still in use. Under an arena, where freeing does nothing, that mistake stays silent until the same code runs on a real allocator. ### [1130] Repeating: `loop` `loop do ... end loop` repeats until something leaves it: `break`, `return` or `fail`. A labelled loop closes with its label. ```landin counter: loop do break when x == 0 end counter ``` ### [1140] Repeating while a condition holds: `while` `while` tests its condition before every iteration. `continue` goes straight to the next test. ```landin mut i: u32 = 0 while i < 10 do inc i continue when i == 3 end while ``` ### [1150] Walking a range or a collection: `for` `for` binds each item of its source in turn. An optional second name is a `usize` index counting from zero. ```landin for item in items do out += item end for for item, idx in items do item = item + i32(idx) -- items is writable, so this writes end for for k in 0..<10 do out += k end for ``` | source | each item is | |---|---| | `a.. none = for x in xs do x = x * 2 end for end double_all ``` Over anything else that satisfies `iterable`, the binding is a copy, since `item` ([1320]) hands out a value. Assigning to it is an error rather than a silent write to nothing. Text likewise yields a copied `u32` that cannot be written. - The cursor and item keep their exact declared types. An `any C` item is still an `any C`: it carries its evidence ([1690]), which is its type's table of C's entries. An `any C` source is handed as it is to its `iterable` entries. Neither is treated as a slice. - When the element is a fixed array, slice or `any C`, replacing the whole element follows the same rule. Writing through an inner slice follows that slice's own `mut`. ### [1170] When a loop runs out A loop is a statement. Every way out of it reaches the statement after it: a `while` whose test became false, a `for` whose source ran out, and each `break`. Nothing runs only because the loop ran out. Code that should is written after the loop, behind a flag that the loop's breaks clear. ```landin mut ran_out: bool = true for item in items do if item == 42 then ran_out = false break end if end for if ran_out then out = -1 end if ``` A function of its own needs no flag. It returns from inside the loop, so whatever follows the loop runs only when the loop ran out ([1190]). ### [1180] Labels A loop or a bare block may carry a label, written like any other name. `break` and `continue` may name one. An unlabelled `break` or `continue` means the innermost loop. ```landin outer: for a in items do for b in items do break outer when a == b end for end outer ``` A `break` naming a bare block leaves it, and whatever loops it crosses, running their cleanups on the way out. ```landin search: begin for item in items do break search when item == 0 end for out = 1 -- no item was zero end search ``` A bare block has no next iteration, so `continue` can target only a loop. ### [1190] A loop that searches A loop has no value. A search writes what it finds to a mutable local and leaves with a plain `break`. ```landin mut found: i32 = 0 for item in items do if item > 40 then found = item break end if end for out += found ``` `found` starts as the answer for a loop that runs out, so no flag is needed. A search that is a function of its own writes the named result and returns. ```landin first_above: (items: []i32, limit: i32) -> (found: i32) = for item in items do if item > limit then found = item return end if end for found = 0 end first_above ``` - `break` takes a label or nothing, never a value. - A loop cannot be the right-hand side of an assignment, an initializer or an argument. - Earlier versions of Landin had loops with values. The compiler refuses those forms and names the replacement, and `refine fix` rewrites the ones that have a mechanical one. ### [1210] Pattern matching: `match` `match` picks the arm whose case or atom the subject holds. There is no fallthrough, and a missing case is a compile error. This uses `figure` from [0680]: ```landin area: (f: figure) -> (a: f32) = a = 0.0 match f.kind circle(radius): a = 3.14159 * radius * radius rectangle(width, height): a = width * height end match end area ``` An arm runs one statement or one expression. For several, make the arm a bare block: ```landin area_and_corners: (f: figure) -> (a: f32, corners: u32) = corners = 0 match f.kind circle(radius): a = 3.14159 * radius * radius rectangle(width, height): begin a = width * height corners = 4 end end match end area_and_corners ``` - The subject is an atom set ([0640]), a variant part ([0680]) or a pointer union ([0480]). An arm names an identity, and a case arm may bind the payload, as `circle(radius)` does. - Several labels share one arm, `north, south:`, and each counts toward covering every case. An arm that binds a payload names one case. - `_` is an arm of its own and covers whatever is left of an atom set or a pointer union. On an atom set, `_ (rest):` binds the remaining atoms as a set of their own, so they can be passed on where only those are wanted. A union of atom sets is split the same way: name one side's atoms, which may share one arm, and end with `_ (rest):`, which binds the other side's as a set. An arm cannot name a set. - A variant part takes no `_`: its match names every case, and the cases that share what an arm runs are listed on that arm. - A number has no identity to name, so you compare it with `if` and `elsif` instead of matching it. ### [1220] Writing into a matched payload A pattern binding takes a parameter convention ([0900]). It is read-only unless marked; `inout` writes into the payload that was matched. ```landin store: type = struct kind: variant inline: (buf: [4]i32) | spilled: (heap: []mut i32) end kind end store spill: (inout s: store, v: i32) -> none = match s.kind inline(inout buf): buf[0] = v spilled(heap): heap[0] = v end match end spill ``` `spilled(heap)` needs no `inout`: it writes through the slice, whose own `mut` allows it, and never replaces the slice. A plain binding reads the payload in place, without copying it; `inout` adds permission to write it, where the matched value may itself be written: `s` above is an `inout` parameter. On a pointer union's `ptr` arm, `ptr (sink p):` passes the pointer on to a `sink` parameter ([0910]), which consumes the matched place. `describe` matches the `compass` of [0640], two directions in one arm: ```landin describe: (c: compass) -> (name: utf8) = match c north, south: name = "along" _: name = "across" end match end describe ``` The rules for the bindings: - Both plain and `inout` bindings alias the matched storage, scalars included. So an arm may replace the variant, or an object containing it, only after the aliases' last use ([0830]). Writing through an `inout` alias is a use, as is reading an address derived from it or evaluating a pending cleanup argument. - A scalar copied out of a binding keeps no borrow of the payload. - Matching a computed value matches a temporary copy, so replacing the original does not change what the arm sees. - Assigning a new case selects its tag before evaluating the new payload, so the payload's initializer cannot use an alias of the old one. When constructing a whole containing value, save the scalars you need first. Exact rules: spec [1910]. ### [1120] Switching checks off for a region: `unchecked` An `unchecked` region drops the run-time checks the compiler would emit inside it, and says so where you read it. ```landin unchecked begin out = out + items[0] end unchecked ``` The region is an ordinary block: it has its own scope, `defer` still runs on the way out, and nesting one inside another changes nothing. These checks go: - integer overflow; - an element index or a slice range; - the destination range of an integer conversion. Two things stay: - Everything the compiler decides at compile time: types, definite assignment, permissions, origins. - The checks whose absence would not mean the same thing on every machine: a zero divisor, a negative shift count, a conversion to `bool` or from a float, a text boundary, and converting an integer that is zero at the target's width into a pointer. A region reaches only the code written inside it. A function called from it is checked as that function is written. A deferred call is checked where you wrote it, not where the exit that runs it stands. ## ARRAYS, SLICES AND TEXT Three kinds of value do most of what other languages use pointers for: - An array holds its elements inline and is copied like any other value. - A slice is a view of someone else's elements: a pointer and a length. - Text is a view with a promise about its encoding. Storage that has to outlive a function comes from an allocator you pass in; [1360] shows how. ### [0520] Arrays are values `[n]t` is `n` elements of type `t`, stored inline. Assignment copies the whole array. The length is part of the type, so `[4]f32` and `[8]f32` are different types. ```landin grid: [4]f32 = [1.0, 2.0, 3.0, 4.0] mut next: [4]f32 next = [grid[0], grid[1], grid[2], grid[3]] ``` **Assigning a literal.** Assigning a literal to an existing array, as `next = [...]` does, evaluates the elements in written order, and each one reads the array as it was before the assignment: `row = [row[1], row[0]]` swaps two elements. The array changes only once the whole value is formed, so an element that fails, or leaves through an `else`, leaves it as it was. The repeated forms of [0560] and struct literals [0710] follow the same rule. When nothing in the literal can observe the destination, the compiler writes straight into it. When something can, because the literal reads the destination, reads through a pointer or calls something that could reach it, the value is built in a temporary the size of the destination and copied once. That copy is a visible cost, in the frame, like the copies whole-array arithmetic makes ([0590]). **The length.** The length must be a constant the compiler works out without running anything. You may write: - integer literals; - fixed parameters ([1520]); - compiler facts such as `compiler.word_size` [1500]; - `sizeof` or `alignof` of a built-in scalar type, such as `sizeof usize`; - immutable module integers; - parentheses, unary `-` and plain `+`, `-`, `*`, `/` and `%` to combine them. Calls, wrapping operators, bitwise operators, shifts and measurements of your own types are not allowed. A fact and a scalar's size and alignment are the selected target's, so `[sizeof usize]u8` is `[8]u8` on a 64-bit target and `[4]u8` on Cortex-M0. A module integer counts only when its own value is such a constant. A `mut` one never counts, because the program may write it. With `path_max: usize = 4096`, `[path_max]u8` is the same type as `[4096]u8`. Fine print: - The compiler refuses a negative length. A length of zero is fine and gives a zero-length array, but there is no empty array literal, and the repeated forms of [0560] cannot fill a zero-length array. - An index is a `usize`, and the array's size in bytes must fit the target's `usize`. - A computed index is evaluated and bounds-checked once, before the element is used. Indexing exposes no pointer and does not change how arrays are copied. - An array keeps its complete element type, permissions included, through a pointer, a slice, a generic call or a stored field. An `any C` element keeps its own data and its evidence for `C`. ### [0530] Letting the literal set the length With `:=`, the literal supplies both the length and the element type. ```landin triple := [1.0, 2.0, 3.0] -- [3]f32 ``` The first element decides the element type, whether it is a number, a slice, a pointer or a struct. Every later element must have that type. ### [0560] Filling an array with one value `[n of v]` is an array of `n` copies of `v`. It suits fixed patterns, which an immutable module binding can keep in flash. ```landin pattern: [256]u8 = [256 of 0xFF] filled: [256]u8 = [of 0xFF] -- length from the type read_header: () -> none = header: [8]u8 = [0x7F, 0x45, of 0] end read_header ``` There are three forms. They differ in where the length comes from: | form | where the length comes from | |---|---| | `[n of v]` | the count `n`; it can also give a local or module binding its type, whatever `v`'s type | | `[of v]` | the destination's written type | | `[e1, ..., ek, of v]` | the destination's written type, with `1 <= k < N` | `v` is evaluated once, not once per element. The last form is the mixed form: it writes the prefix left to right, then evaluates `v` once and fills the rest. An assignment to an existing array may use any of the three forms: ```landin header_image: [8]u8 = [0x7F, 0x45, of 0] refill: (seed: u32) -> (row: [4]u32) = row = [of seed] -- the length comes from row row = [seed, seed + 1, of 0] -- the prefix first, then the fill copies := [4 of seed] -- [4]u32 row = copies end refill ``` Fine print: - The mixed form needs one of three destinations: an explicitly typed local or module binding, an assignment to a mutable fixed array, or a fixed-array argument of the same length, which it fills. It cannot be inferred, nested or returned. At module level every element must be a compile-time known scalar [1460]. - An inferred `[n of v]` takes `v`'s type, of any kind, and an untyped integer becomes `i32`. Its size must fit the target's `usize`. - Refused: `row := [of 0]`, which has no length to give, and a zero count or a zero-length destination. - `of` is a contextual word: if `of` names a binding, `[of, other, of]` and `[of + 1]` are ordinary literals. ### [0540] `zeroed`: the all-zero value `zeroed` is the value of a type whose bits are all zero. In this example `point` is [0120]'s struct and `compass` [0640]'s enumeration: ```landin mut buffer: [256]u8 = zeroed buffer = zeroed -- clear the existing array as a whole corner: point = zeroed -- fine: both fields are floats -- facing_now: compass = zeroed -- error, write 'north' -- p: ptr u32 = zeroed -- error, no zero image ``` Two separate questions decide where you may write `zeroed`. **Does the type have a zero image?** It does when all-zero bits are a valid value of it. That is what lets a surrounding struct or array be zeroed. Pointers and `any` have none, because there is no null ([0480]), and neither does a function address. A struct or an active variant payload that contains a function address must spell that field out instead of using whole or trailing `zeroed`. **Does the type accept the word?** Only when its zero has one obvious reading: - Numbers, `bool`, ranges that contain zero, and aggregates of those accept it. - Named value sets do not: write the name. - A distinct type [0650] has its base's zero image, so a record holding one zeroes fine. But an identity such as a user id has no obvious zero, so write `user_id(0)` rather than `zeroed` for it. Where the destination gives the context, `zeroed` writes the complete zero image as one value, as the assignment to `buffer` does. A packed struct ([0730]) is a raw image, so `zeroed` is allowed even when an encoded field's zero pattern has no name. Reading that field then traps; copying the image keeps its bits. Library code has a narrow cousin, `uninit`, which leaves a private array field unwritten. It is not another spelling of `zeroed` and cannot initialize a stand-alone array. ### [0550] Asking for a zero image: `zeroable` `zeroable` is the concept that says a type has a zero image, the first of [0540]'s two questions. Generic code can therefore require it. Concepts come in [1240]; for now read one as a named property a type can have. ```landin -- compiler-owned; a program does not repeat this declaration zeroable: type = concept (t: type) end zeroable ``` Only the compiler knows a type's bit patterns, so only the compiler supplies conformances to `zeroable`, and a program cannot declare one. It is the one concept like that. These types conform: - the enabled scalars; - a fixed array exactly when its element is zeroable, even at length zero; - a struct exactly when its all-zero shape, recursively, has a zero image; - a distinct type exactly when its base is zeroable. Atoms, functions, pointers and slices do not. It is a closed list, not reflection over arbitrary types. Requiring `zeroable` is how a container that needs a filler value for storage it has not used yet says so, instead of pretending: see `cleared` at [1350] and the reason at [0510]. ### [0570] Slices are views A slice `[]t` is a pointer and a length. It copies nothing. `mut` inside the type says its elements may be written. ```landin mut cells: [4]f32 = [1.0, 2.0, 3.0, 4.0] view: []f32 = cells[0..<2] -- read-only elements edit: []mut f32 = cells[0..<2] -- writable, since cells is mut ``` You can pass an array straight to a slice parameter. The array lends a slice of all its elements: - A named array lends its own storage. - An array literal is built in the caller's frame for the duration of the call, so a list of values needs no binding of its own. A literal lends read-only elements only, so it cannot go to a `[]mut t` parameter. ```landin added: (values: []f32) -> (sum: f32) = sum = 0.0 for value in values do sum += value end for end added both_sums: () -> (both: f32) = both = added(grid) + added([1.0, 2.0]) end both_sums ``` ### [0580] The empty slice `[]` is the empty slice. Its length is zero, and a `for` over it runs no iteration. It is never null. Its base is the lowest positive address aligned for the element type: 1 for bytes and 4 for a `u32`. Indexing checks the length first, so that base is never dereferenced. ### [0590] Arithmetic on whole arrays Fixed arrays are also Landin's vector type: arithmetic on numeric arrays works element by element. There is no second type with the same shape and different rules. ```landin sum_four: (values: [4]f32) -> (sum: f32) = sum = 0.0 for value in values do sum += value end for end sum_four array_example: () -> (sc: [4]f32, s: f32) = va: [4]f32 = [1.0, 1.0, 1.0, 1.0] vb := va * va sc = va * 2.0 -- a scalar on either side is fine s = sum_four(vb) -- ordinary function, not a reduction builtin end array_example ``` The rules: - `+`, `-`, `*`, `/` and unary `-` work on numeric arrays; `%`, `+%`, `-%` and `*%` on integer arrays. - Two arrays must have the same element type and length. A scalar of the element type is applied to every element; an array of another length is not. - Each operand is evaluated once, left to right, as a complete value before any element is computed. So `a += a` and other overlapping assignments see the old values, not their own earlier writes. - Elements go in ascending index order under the ordinary scalar rules for traps, wrapping and floating point. Nothing is reassociated, so `sum_four` adds in order starting from positive zero. Arrays do not compare, not even with `==` or `<>`. Whole-array equality and per-element masks are both plausible meanings, so write the function you mean. The cost is visible in the type: `[4096]f32 + [4096]f32` needs a 16 KB result and may keep copies of its operands as well. Vector instructions are an optimisation, never needed for a correct result. ### [0600] Text: `utf8`, `utf16` and `cstring` Landin has no single string type. It has three distinct views over plain storage: | type | view over | holds | |---|---|---| | `utf8` | `[]u8` | validated shortest-form UTF-8 | | `utf16` | `[]u16` | UTF-16 code units | | `cstring` | `ptr u8` | bytes up to a NUL; no length | The three types stay distinct from each other and from their backing types through calls, structs and generics. `lenof` on `utf8` and `utf16` counts code units, not characters. **Literals.** A quoted or raw literal can be any of the three, and is `utf8` when nothing says otherwise. Every literal has one trailing zero code unit, which slice lengths leave out. Equal literals of the same width may share one read-only copy. A `cstring` literal is valid UTF-8; a `cstring` that comes from C promises only readable bytes up to its first NUL, with its encoding unchecked. **Converting.** Conversion between text and bytes is the ordinary explicit conversion, and these are all there are: | from | to | what it does | |---|---|---| | `[]u8` (read-only) | `utf8` | validates, and traps on invalid UTF-8 | | `utf8` | `[]u8` (read-only) | nothing: same base, same length | | `cstring` | `[]u8` (read-only) | scans to the first NUL | | `cstring` | `utf8` | scans to the first NUL and validates | There is no conversion from a pointer to `cstring`, none with a writable result, and none for `utf16`. An empty result keeps its source's base and origin. `compiler.utf8_unvalidated(bytes)` [1560] is for bytes a program knows are UTF-8, because it has just checked them or wrote only whole characters. They become `utf8` without being read again, with the same base, length and origin. The call is allowed only inside `unchecked` [1120], and bytes that are not UTF-8 then go unnoticed. **Slicing.** `utf8` and `utf16` slice by range, as `word[3..3]` in [0610] does. The result is the same text type, read-only, over the same storage. - The `usize` bounds count bytes or UTF-16 code units, not characters. - Both bounds must fall where a Unicode scalar starts; a bound out of range or inside an encoding traps. - A half-open range may end at the length; an inclusive range takes the whole scalar that starts at its upper bound. - A `cstring` has no length and cannot be sliced. **Traversal.** `for c in text` yields each Unicode scalar as a `u32` [1320]; on a `cstring` it stops before the first NUL. Traversal declares no error, so text from C is validated as it is decoded and malformed encoding traps, even inside `unchecked`. **`core/text`.** When invalid text is input to handle rather than a bug, `text.from_bytes` and `text.from_c` validate the same way but fail with `invalid_text` instead of trapping; call them before traversing. The module also has exact byte equality, substring search, decimal parsing and bounded writing into a buffer you supply. It never normalizes or silently truncates. It allocates only in a builder made by `text.growing`, which takes an allocator. `core/text` counts positions as byte offsets of the opaque type `text.position`: - On plain `[]u8`, the functions are `first`, `at_end`, `next`, `advance`, `offset`, `byte` and `slice`. Reading a byte at the end fails with `mem.out_of_bounds`, and a slice keeps its source's origin. - On `utf8`, the same positions step a whole scalar with `start`, `step`, `utf8_at_end` and `scalar_length`. `find` returns where a match begins, so the text around it slices out by range with nothing copied. ### [0610] Indexing text by scalar or by position Indexing a `utf8` gives the Unicode scalar there as a `u32`, the type a character literal [0250] and a traversal [1320] already give it. The index type picks the operation: - a `usize` counts scalars from the start, so `word[2]` is the third one; the compiler finds it by scanning; - a `core/text.position` is a byte offset, decoded directly in O(1). ```landin word: utf8 = "\u{e9}t\u{e9}" last := word[2] -- 233, the u32 of é, found by scanning same := last == '\u{e9}' -- true bytes: utf8 = word[3..3] -- é again, at byte 3: two bytes, no copy ``` A count past the end traps, and so does a position at the end or on a continuation byte. Neither index type converts implicitly to the other. The scalar is decoded, so it is a value, not a place: `addr word[2]` and `word[2] = 'e'` are errors. To get its bytes, take a one-scalar range as [0600] describes: its bounds count bytes, and the result is still `utf8`. A `utf8` converted to `[]u8` loses scalar indexing and has the ordinary slice operations instead. ## MODULES ### [1410] A module is a directory Every `.ldn` file directly inside one directory belongs to one module. Those files see each other's declarations without importing anything. Everything is private to its module unless it is marked `public`. There is no separate interface file. ```text geometry/area.ldn geometry/shapes.ldn geometry/solid/volume.ldn ``` Here `geometry` is one module of two files, and `geometry/solid` is a second module. Fine print: - The compiler reads a module's files in bytewise filename order. It ignores other files, and an empty directory is a legal empty module. - Declaration order never affects what is visible. File order does fix identities, the order of diagnostics and the order of active `linker.library` directives [1590]. - An importer can name public functions, bindings, atoms, types and concepts. A variant case is public when its type is. - A public declaration may mention a private one. The private identity flows through the public surface, but an importer cannot name it. ### [1420] Importing a module by its path `import net/http` finds a directory `net` holding a directory `http`, under the import roots the compiler was given. It binds the last segment, `http`, as a namespace in this file. ```landin import net/http ``` **Finding the module.** The compiler searches the roots in order, and the first that has the directory wins; a later root is not merged in. From that directory the compiler takes every source file, not recursively, and follows their imports. A subdirectory is a module of its own, reached by its own path. Each module is loaded once, so import cycles are legal. **Using the namespace.** After the import, `http.get`, `http.response` and `http.drawable` name that module's public declarations. Qualification works wherever a value, type, type application, concept, conformance, error atom or match case is named. The first dot after the namespace selects a public declaration; later dots are ordinary value selections. The namespace itself is not a value, type or place. **Spelling the path.** A path segment is a plain identifier: lowercase letters, digits and underscore, not starting with a digit. - It is lowercase because a case-sensitive and a case-insensitive filesystem must agree on what a name is. The directory entry must have exactly that spelling even on a case-insensitive host. - It is an identifier because the last segment becomes a name in your file, so a hyphen would need an alias every time. The separator is always `/` in source, on every host. ### [1430] Renaming an import `as` gives the namespace another name, for when two imports collide. ```landin import net/http as h ``` This binds `h` only, not `http`. `as` is a contextual word, so outside an import it is an ordinary identifier. ### [1440] A module is imported whole An import binds the module's namespace and nothing else. There is no list of selected names and no wildcard: `import net/http (get, post)` is refused. Import the module and name its members through it. ```landin import net/http -- then http.get, http.post ``` So every name from another module shows its module where it is used. When the qualifier is long, or two imports collide, rename the module with `as` ([1430]) and write `h.get`. ### [1450] Imports belong to one file Each file has its own imports, so every file reads on its own. - Imports come first, before every declaration. - One file's imports are not visible in its siblings and are never re-exported. - Binding one name twice in a file's imports is an error, whether it is the same import twice or an alias colliding with another import. Shadowing goes like this: - A parameter or local may shadow an import. - A namespace import shadows a same-named module declaration only for qualified lookup; the module's unqualified value stays visible. The compiler reports naming a private member differently from naming one that does not exist, and the report points at the private declaration. ### [1460] Module-level values are known at compile time A value at module level must be known when the compiler reads it, because nothing runs before the entry point. So it cannot call a function. Immutable values can stay in flash; mutable ones cost RAM, and the `mut` makes them conspicuous. ```landin table: [4]u32 = [1, 2, 4, 8] mut call_count: u32 = 0 ``` **Arithmetic.** Integer arithmetic here is worked out in a wide range first, and only the final value is checked against its type. So a module `value: u8 = 200 + 100 - 100` holds 200, while the same `u8` addition inside a function overflows and traps before the subtraction. **Values from other modules.** A value another module exports is known in the same way, named through that module: `limit: u32 = sizes.page * 4`, `ready: flags.state = flags.idle`. Qualifying a name changes where it is found, not whether it is known. **Functions in a struct.** A module struct may hold a function. The field names a declared function ([1010]). What is stored is the function's address; nothing is called. There is no all-zero function address [0540], so such a struct must be written out in full. Exact rules: spec [1940]. ### [1470] Packages and versions A package is a named collection of modules with a version and an origin. Its name has two levels, owner and package, and a directory under a search root is the package it names. A program holds one version of each package name. Two copies of a package would do three things: - cost space a 32 KB part does not have; - be different types, since types are nominal; - put conflicting entries in the single list the whole program keeps of which types conform to which concepts ([1240]). The companion tool ([1480]), once it exists, will solve versions and report a conflict as a hard error that asks for an upgrade. The current compiler reads no versions or origins. It takes the first matching module directory from the ordered roots [1420], even when a later root holds another version. ### [1480] Where modules come from: the roots You tell the compiler where modules are. `refine` takes repeated `--root=DIR` options and then the entry module: its directory, or its source files, which together form one module. With no `--root` you name the source files, and they form one module in the same way. The roots are searched in the order you give ([1420]), and that order alone decides: the compiler consults no home directory and adds no system root of its own choosing. **The library root.** The compiler does add one root: the library it ships with, found beside its executable. `core`, `hosted` and `platform` always come from there and from nowhere else, so a root you name cannot replace them. Every other module is searched for in your roots, project first, so a project can override an ordinary module by putting its own copy in its first root. Vendoring a package is just that. **The companion tool.** Fetching packages, solving versions, lock files and naming authority belong to a companion tool. It will ship alongside the compiler but stay separate from it: a compiler you can read is worth more than one that can download things. - Arranging the roots so that only one version of each package is reachable is that tool's job. So until it exists, the compiler does not enforce [1470]'s one-version rule. - The intended root order is the project, then the user's Landin home, then a system-wide one. - Whether a path's leading segments name an owner and a package is a convention for people and that tool. The compiler only sees directories. **The compiler's namespaces.** Four source namespaces come with the compiler: | namespace | holds | available | |---|---|---| | `core` | the shared freestanding library: `core/mem`, `core/text`, `core/vec` | every module and interface on every target | | `hosted` | hosted providers such as `hosted/heap`, `hosted/system` and `hosted/blocking` | on hosted systems | | `platform` | interfaces scoped to a target or a system: `platform/c`, the CPU modules, the POSIX layer and `platform/windows` | each as the next table says | | `landin` | the toolchain modules of [1560]: `landin/compiler`, `landin/assembler`, `landin/linker` | everywhere, without an import | Within `platform`, availability goes by module: | `platform` module | available | |---|---| | `platform/c` | wherever a C ABI (application binary interface) is enabled: the hosted LP64 targets and Cortex-M's AAPCS32 | | a CPU module: `platform/cortex_m`, `platform/riscv` or `platform/xtensa` | everywhere, with its operations, submodules and reference descriptions only on its own targets: Cortex-M at any level, `rv32`, `xtensa` | | the POSIX layer: `platform/posix` over `platform/linux`, `platform/libc` and `platform/kqueue` | on every hosted system, with its declarations only on Linux, macOS and FreeBSD | | `platform/windows` | on every hosted system, with its declarations only on Windows | | a `platform` module the compiler gives no scope | nowhere | Fine print: - An import outside its target's scope is refused by name when the target is checked, for example `hosted/heap` in firmware. - The POSIX layer and `platform/windows` are hosted-only and still under `platform`, not `hosted`: each is its system's own interface, which the `hosted` providers are written over, rather than a provider of its own. A provider written for every hosted system imports both, and a call to the one that declares nothing on the target is refused. - A module that declares nothing on some targets can be imported on all of them: a program for every target imports `platform/cortex_m` and calls it from a `fixed if compiler.arch == cortex_m0` arm ([1500]). - The toolchain modules are always there, so the bare names `compiler`, `assembler` and `linker` cannot be declared or bound by an import, and an explicit `import landin/compiler` (or `assembler`, or `linker`) is refused by name before any root is searched. - Otherwise the namespace names are ordinary identifiers. ## What you can write now That is the end of the part to read in order. You can now write ordinary programs: functions with failures, your own types, loops and matches, arrays and text, modules, and the host's files and streams through `hosted/blocking` and `core/io`. [`examples.md`](examples.md) has complete programs to read and copy. For storage whose size is known only at runtime, continue with arenas over caller-supplied storage ([0820]) and allocation as a concept ([1360]), then the [growable-vector example](docs/library.md#corevec). Together they show how a collection is handed its allocator and where its storage is released. The sections after this one are reference, to read when you need them: [Pointers](#pointers); [Lifetime and escape](#lifetime-and-escape); [Concepts and generic code](#concepts-and-generic-code); [Runtime dispatch](#runtime-dispatch); [Compile time](#compile-time); [The toolchain, C, and the machine](#the-toolchain-c-and-the-machine); and the principles, the omissions and the open questions at the end. ## POINTERS Most code never needs a pointer: slices, handles and indices do the everyday work ([0490]). Pointers are for hardware, the C boundary and the inside of libraries. When you do need one, it is spelled in words. ### [0430] `ptr`, `addr` and `.val` `ptr u32` is a pointer to a `u32`. `addr` takes an address, and `.val` is the thing pointed at, on either side of an assignment. ```landin mut value: u32 = 42 p: ptr mut u32 = addr value v := p.val -- read through p p.val = 43 -- write through p ro: ptr u32 = addr value -- same address, read-only -- ro.val = 1 -- error: ro cannot write ``` `mut` inside the type is what lets you write through the pointer. `addr` of a mutable variable gives a `ptr mut`, and `addr` of an immutable one a plain `ptr`. What `addr` is applied to decides which address you get: - `addr p.val` is the address of the thing `p` points at. - `addr items[i]` is the address of a slice's element. - `addr p` is something else: the address of the variable `p` itself, which may live on the stack. ### [0440] A writable pointer passes where a read-only one is expected A writable reference is accepted where a read-only one is expected, and the call needs no conversion spelled out. ```landin add_up: (xs: []i32) -> (total: i32) = total = 0 for x in xs do total += x end for end add_up add_written: (writable_slice: []mut i32) -> (total: i32) = total = add_up(writable_slice) -- fine: []mut i32 relaxes to []i32 end add_written ``` No bit changes; the callee simply forgets that it could write. This is the only implicit relaxation in the language, and it only goes this way: a read-only reference never becomes a writable one. ### [0450] Permission is shallow Read-only applies to one level only. An immutable binding, or a read-only parameter, protects the value it holds, not what that value points at. A list handed over read-only still has writable elements if its storage is writable. Protecting deeper would mean knowing which references a value owns and which it borrows, and Landin does not track ownership ([0910]). When you want to hand out a read-only view, hand out a read-only reference; an accessor is how. ### [0460] A pointer to a fixed address `ptr(...)` turns an address into a pointer. The pointer type comes from the declaration. ```landin gpio: ptr mut u32 = ptr(0x4001_0000) ``` This binding is immutable, but the register behind it is written: the two questions of [0070] really are separate. Nothing in the pointer's type makes access to it a device transaction. The operation that reads or writes does that ([0850]). ### [0470] Converting between pointers and integers A pointer and an integer convert both ways like any other conversion ([0700]): apply the type. Here `gpio` is the pointer from [0460]. ```landin gpio_round_trip: () -> (back: ptr mut u32) = address := usize(gpio) -- pointer to integer back = ptr(address) -- integer to pointer: no origin end gpio_round_trip ``` The cost is on the way back. An integer has no origin, so a pointer made from one borrows nothing as far as the compiler knows, and the compiler will say nothing more about that pointer's lifetime. This is the one place inside the language where lifetime checking is left behind, much as at the C boundary. ### [0480] There is no null "Maybe a pointer" is a union of an atom and a pointer type. With a single atom, the compiler stores it as a plain pointer, with 0 meaning the atom. ```landin none_found: atom maybe_ptr: type = none_found | ptr mut u32 lookup: (key: u32, cell: ptr mut u32) -> (found: maybe_ptr from cell) = if key == 0 then found = none_found else found = cell end if end lookup read: (m: maybe_ptr, fallback: u32) -> (value: u32) = match m none_found: value = fallback ptr (p): value = p.val end match end read ``` A pointer goes into the union with nothing extra to write. Getting it out takes a `match`, and the `match` has to name both cases: `ptr (p)` is the present case, with the pointer bound to `p`. To ask only which case the union holds, compare with the atom: `m == none_found` or `m <> none_found`. That reads no address, so it needs no `match`. Two such unions do not compare with each other. The union holds exactly one atom. For a pointer with several states, put the union beside an error set ([0940]), or write a struct of a state and a pointer. Exact rules: spec [1870]. ### [0490] What to use instead of a pointer Before you reach for a pointer, see whether one of these does the job: | you want | use | |---|---| | a run of elements, to read or to write | a slice ([0570]) | | one element of an array you already have | its index | | a service such as an allocator | a handle: a small value that refers to state kept elsewhere ([1360]) | Each says more than a pointer would: a slice carries its length, an index is checked against that length, and a handle's type says what it is for. ### [0500] No pointer arithmetic outside the library There is no `p + n` on pointers, and no built-in operation that turns a pointer into a slice. Code that really needs to compute an address converts to an integer and back ([0470]), and gives up lifetime checking when it does. Inside the standard library, `core/mem` does this for you, behind its private storage operations. If you need an element's address, take it from a slice that you know is not empty: `addr items[0]`. ### [0510] Storage that is not filled yet: `mem.storage(t)` A growing array has room for more items than it holds. The empty slots contain no `t` yet, so no slice may cover them: a `[]mut t` over them would claim values that do not exist. Neither may they be zero-filled, because many types, pointers among them, have no zero value ([0540]). `core/mem`'s `storage(t)` is the answer. It holds a block of storage, counts how many slots at its start are initialized, and only ever shows you that initialized prefix. Its representation is the private type `raw(t)`: you can hold one but not look inside. | operation | what it does | |---|---| | `capacity`, `length` | how many slots there are, and how many are initialized | | `admit` | initialize the next slot | | `get`, `replace` | read or overwrite an initialized slot | | `used` | the initialized prefix as a `[]mut t` | | `withdraw`, `clear` | drop the last item, or every item | | `transfer` | copy one item onto the end of another `storage`, for growing | | `detach` | hand the block back once it is empty | The four ways of asking for something impossible are ordinary failures: `out_of_memory`, `out_of_bounds`, `empty` and `not_empty`. **Growing.** To grow, reserve a bigger block and `transfer` every item into it. A `transfer` copies and leaves its source as it was, so the old block is unchanged until you are done: if a step fails, release the new block and carry on with the old one. Only after every item is copied do you empty and dispose of the old block and publish the new one. This keeps the empty slots out of reach. It does not make raw storage safe: the allocation you supply must be live, aligned and as large as you say ([1720]). ## LIFETIME AND ESCAPE Landin checks borrows and escapes locally. It has no Rust-style ownership and no lifetime parameters. Inside each function, the compiler knows where every pointer, slice and `any` points. That place is the reference's *origin*, and there are three: | origin | what it is | how long it lives | |---|---|---| | static | module storage and literals | the whole program | | allocated | what an allocator handed out | until you give it back | | frame | a function's locals | until the function returns | Everything in this section follows from a few rules: - A frame reference never leaves its function ([0770]). - A function does not keep a pointer it was given unless its signature says `escaping` ([0780]). - While a view into a local is in use, the local cannot be grown or moved ([0830]). - A returned reference says what it came from, with `from` ([0790]). The compiler checks each rule one function at a time, against signatures. A change in one body therefore never changes what another function may do. The price is that some mistakes go uncaught; [0860] lists them. ### [0770] A frame reference cannot leave its function A pointer to a local dies with the function. Returning one is an error, and so is storing it anywhere that outlives the function. ```landin bad: () -> (p: ptr u32) = x: u32 = 42 p = addr x -- error: a frame origin escapes end bad ``` A pointer to module storage is static, so the same shape is fine: ```landin mut tally: u32 = 0 tally_cell: () -> (p: ptr mut u32) = p = addr tally -- fine: module storage is static end tally_cell ``` The origin travels with the value. A slice of a local array is frame too, and so is an `any` built over a local ([1370]). ### [0780] Keeping a pointer you were given: `escaping` A parameter is non-escaping by default. The callee may read and write through a pointer it was handed, but it may not keep the pointer once it returns. ```landin increment_cell: (cell: ptr mut u32) -> none = cell.val += 1 -- using the pointer is fine; keeping it would not be end increment_cell caller_of_increment: () -> (n: u32) = mut local: u32 = 1 increment_cell(addr local) -- fine: the callee does not keep it n = local end caller_of_increment ``` So a pointer to a local can go into any call whose parameter does not say `escaping`. A function that does keep a reference marks the parameter `escaping`. The caller may then pass only something that lives long enough: allocated or static, never frame. The next example assumes a struct `node` with a field `next: ptr mut node`. `mem.allocate_item` allocates one value through the allocator it is given and returns a pointer to it ([1360]; `core/mem` in the [library guide](docs/library.md)). ```landin push_front: (escaping inout head: ptr mut node, escaping item: ptr mut node) -> none = item.val.next = head head = item end push_front build: (provider: type is mem.allocator, memory: provider, escaping seed: ptr mut node) -> (head: ptr mut node) ! mem.out_of_memory = head = seed n := try mem.allocate_item(memory: memory, value: seed.val) push_front(head, n) -- allocated, fine mut local: node = seed.val push_front(head, addr local) -- error: a frame origin escapes end build ``` `push_front` stores each argument where the other can reach it, so both are `escaping`. What counts as keeping: - "Keeping" means any store that outlives the call: into a module binding, or through a pointer, slice or `inout` field the caller owns. - Storing a reference back into storage of the same origin is an update, not keeping, and needs no marker. - Storing one parameter's reference into another parameter's storage needs `escaping`, or else `escaping into`. `escaping into` names the one parameter whose storage keeps the reference. With it, a node on the caller's frame can go onto a list on the caller's frame, provided the node lives as long as the list. The node does so when it is the caller's parameter, static, allocated, or a local declared before the list. In the next example each parameter is kept in the other's storage, so each names the other. ```landin push_kept: (escaping into item inout head: ptr mut node, escaping into head item: ptr mut node) -> none = item.val.next = head head = item end push_kept on_the_frame: (escaping seed: ptr mut node) -> none = mut first: node = seed.val mut head: ptr mut node = seed push_kept(head, addr first) -- fine: first is declared before head mut late: node = seed.val push_kept(head, addr late) -- error: late is declared after head end on_the_frame ``` The function may keep `item` in `head` and nowhere else. A frame reference never goes into a parameter's storage, and a reference from the caller's parameter goes into anything its frame holds. Exact rules: spec [1910]. ### [0830] A view into a local holds the local still A view taken from a local borrows it. While the view is still in use, the compiler refuses to pass the local as `inout` or `sink`, because that call could grow, move or replace the storage under the view. ```landin reset_cells: (inout buffer: [4]i32) -> none = buffer = [9, 9, 9, 9] end reset_cells view_then_reset: () -> (n: i32) = mut buffer: [4]i32 = [1, 2, 3, 4] xs := buffer[0..<2] reset_cells(buffer) -- error: buffer is borrowed by xs n = xs[0] end view_then_reset ``` The fix is always nearby: finish with the view before the call, or take it again after. The check looks at one function body, so there is nothing to annotate. A binding declared in a loop's body is a new binding on each pass, so a view of the last pass's binding does not hold this pass's. Fields of one record are tracked apart. A view of one field holds that field, and with it the record and any field that contains it, but not its neighbours, so two handles can be filled from different fields of one state and used together: ```landin counter: type = struct hits: u32 end counter traffic: type = struct reads: counter writes: counter end traffic slot: (inout c: counter) -> (p: ptr mut u32 from c) = p = addr c.hits end both: () -> (n: u32) = mut t: traffic = zeroed r := slot(t.reads) w := slot(t.writes) -- fine: `r` holds `t.reads`, not `t.writes` r.val += 1 w.val += 2 n = r.val + w.val end both ``` A field is as fine as the tracking goes: two elements of one array are one place, and so are two fields reached through one pointer. A record that holds a reference into its own storage lends together all its fields that could hold such a reference, since the check does not know which of them holds it. Only `inout` and `sink` trigger the check, since they are the two ways a call can change the storage itself. While the view lives, you may still read the local, pass it read-only or pass it by pointer. A view needs no name to be in use. The slice a `for` walks is in use until the loop is done, so the loop's body does not pass what it walks `inout` unless it leaves the loop straight after; and a view given to a call is in use until the call returns, so its source is not passed `inout` beside it. An unchecked region ([1120]) does not turn the check off: origins and escape are among the checks that stay. ### [0790] A returned reference says where it came from: `from` When a function returns a reference derived from a parameter, its signature says so with `from`. The caller then knows that the thing it passed in has to hold still while it uses the result. Here a `batch` holds a writable slice of readings and how many of them are filled in: ```landin batch: type = struct items: []mut u32 count: usize end batch filled_part: (b: batch) -> (s: []mut u32 from b) = b.items[0.. (n: i32) ! mem.out_of_memory = memory := heap.new() xs := vec.used(numbers) try vec.push(numbers, memory, 5) -- error: numbers is borrowed by xs n = xs[0] end grow_under_view ``` Nothing is written at the call. The convention lives in the declaration, and a caller that misuses the result is told at its next use, just as with `escaping`. A container's own storage and what it holds are different things. `vec.used` lends the list's storage, which a push may move. `vec.last` of a list of pointers copies out a pointer the list held, which a push leaves where it was. Its result is declared `from held value`, so it borrows nothing of the list: ```landin import core/mem import core/vec import hosted/heap again: (inout nodes: vec.list(ptr u32)) -> none ! mem.out_of_memory | mem.empty = memory := heap.new() try vec.push(nodes, memory, try vec.last(nodes)) -- fine: what it held end again ``` A result `from held p` is read out of an element: through a pointer `p` carries, or by an index into a slice or array it holds. The address of that element is a view of `p` and needs a plain `from p`. `push` keeps the pointer it is given in the list's own storage (`escaping into`, [0780]), so an item of the caller's list goes straight back into it. ### [0840] Mixed origins count as the shortest-lived When a value combines origins, it takes the most restrictive one. A struct holding one frame pointer is frame as a whole, and a value chosen between two branches takes the shorter-lived of the two. A value that holds no references has no origin and goes anywhere, which is one more reason the idiom is handles and indices. A number computed from a view keeps no borrow: saving `lenof xs` saves a number, and you may use it after `xs` or its container changes. Taking an address or a range is different: that reference keeps the selected storage's origin ([0430], [0790]). Writing through a known address of a local updates the local's origins too. Mixing in a pointer made from an integer ([0810]) does not hide a tracked origin. Exact rules: spec [1910]. ### [0810] A pointer made from an integer is not tracked Converting an integer to a pointer ([0470]) ends tracking. The integer has no origin, so the pointer borrows nothing, and the compiler says nothing more about its lifetime. Nor does the compiler check that the storage is live or large enough: that stays the library's unsafe obligation ([1720]). ```landin block_at: (base: ptr mut u8, offset: usize) -> (block: ptr mut u8) = address: usize = usize(base) + offset block = ptr(address) -- no tracked derivation survives end block_at ``` This is how `core/arena` returns a block without borrowing the arena, after checking its arithmetic; `core` gets no special privilege for it. [0500] says why there is no `offset` or `slice_from` to do this for you, and [0510] keeps uninitialized storage out of reach. A signature brings tracking back. A function that indexes a table C gave it writes `from table` on its result, and the compiler checks its callers against that as against any signature. The compiler does not check the function's body against it, since a pointer made from an integer satisfies any `from`. The contract is its author's claim, so keep such functions small. ### [0820] Arenas are ordinary allocators you give storage to An arena is a library value from `core/arena`: you hand it a block of bytes, it hands out pieces of it, and individual frees do nothing. It is not a builtin type or block. Code that takes any allocator accepts it as a `mem.allocator` provider. ```landin import core/arena import core/mem mut backing: [1024]u8 = zeroed report: () -> (code: i32) = mut space: arena.space = zeroed scratch := arena.over(space, addr backing[0], 1024) code = 1 first := mem.allocate_item(scratch, u8(7)) else (problem) _ = problem return end second := mem.allocate_item(scratch, u8(9)) else (problem) _ = problem return end code = i32(first.val) + i32(second.val) end report ``` - `arena.over(state, base, size)` takes the backing address, its size in bytes, and an `arena.space` you declare `zeroed` beside it. It returns the arena's handle `from` the space and the backing; copies of the handle share one arena. - Allocation aligns the address and advances an offset. A request that does not fit fails with `mem.out_of_memory` before changing anything. - `arena.release` gives everything back at once, and `arena.length` reports the bytes consumed. `over` takes its backing as `escaping base`, so it accepts module storage or storage from another allocator and refuses a frame array. The reason is that allocations borrow nothing ([0790]): a helper could store one in module storage, and an arena over frame storage would let that pointer outlive the frame. For a local buffer whose every use stays inside the frame, `arena.over_unchecked` takes frame backing. You must stop using its results before the buffer ends. Other providers build on the same idea: | provider | what it does | what you must do | |---|---|---| | `core/region.over(ledger, provider)` | records every extent it takes from `provider` in a `region.space` ledger you declare `zeroed` | release all at once with `defer region.release(ledger, provider)`, and stop using its allocations before then | | `core/pool.over` | hands out pieces of backing whose origin its handle keeps | keep the backing live until every result is done with | A region's handle holds a copy of its provider's handle. Its allocations borrow nothing, and its bookkeeping also uses the provider's capacity. A finite provider stays finite: there is no hidden heap fallback. The compiler does not do these for you: - arrange the backing's lifetime and release (`defer`, [1100], runs on every exit); - keep overlapping backing apart; - stop you using a result after its backing ends or is reused. Results obey the ordinary origin rules and nothing more. `arena` itself is not a keyword: it is an ordinary name you may declare. ### [0850] Volatile access sits outside the borrow rules A volatile access is exempt from the borrow rule and from every aliasing assumption. It is an operation, not a pointer type: | operation | for | |---|---| | `compiler.volatile_load`, `compiler.volatile_store` | one scalar | | `compiler.register_read`, `compiler.register_write` | a register image ([0740]) | Each performs exactly one access of its width through an ordinary pointer. That pointer is usually one built from an address ([0460]), and so already outside the lifetime checks ([0470]). Hardware often needs several typed windows on one address, such as a byte view and a word view of the same register, and that is legal on purpose. There is no `volatile ptr`: a second permission on every reference would buy nothing the operations do not. Direct memory access (DMA) uses ordinary slices. Landin makes no lifetime promise about storage a device is still writing: neither an interrupt nor masking one makes it reusable, and waiting for the device is the driver's own protocol. Exact rules: spec [1990]. ### [0860] What the lifetime checks do not catch The checks know which kind of storage a reference points into. They do not know which allocation it points into, or whether that allocation still exists. So these go through: - Use after free or reset. The compiler does not know which arena or allocator a pointer came from, or that it has been given back. - A pointer that went through longer-lived storage. Inside one function a struct carries its fields' origins ([0840]). Store a pointer into a heap node, though, and read it back later through the node: it now has the node's origin, and whatever it pointed to may be gone. - Anything across the C boundary. Catching these would need region-based checking or generation counters, and Landin deliberately has neither. ## CONCEPTS AND GENERIC CODE Generic code has three parts: - A concept lists the operations a type must have. - A conformance says which functions supply them for one type. - A generic function takes the type as a parameter and calls the operations through it. There are no classes, no traits with default bodies and no structural matching: a type satisfies a concept because somebody said so. ### [1230] Declaring a concept A concept names a bundle of operations, each a complete function signature written in terms of the concept's type parameter. ```landin ordered: type = concept (t: type) less: (a: t, b: t) -> (yes: bool) end ordered ``` A concept is an ordinary type declaration, so it lives in a module like any other name. It has no default bodies: each conformance supplies every entry. An entry can also be called on an `any` value ([1390]) when its first parameter is `self` and `t` appears nowhere else in it. `self` is a `ptr t`, a `ptr mut t` or, when `t` is a record, a `t` by value. `less` above takes two `t`s, so only generic code can call it. ### [1240] Making a type conform A conformance registers one type against one concept, naming the function that supplies each entry. ```landin less_than_i32: (a: i32, b: i32) -> (yes: bool) = a < b end less_than_i32 i32 is ordered (less: less_than_i32) ``` Each label is an entry of the concept. Each supplying function must have exactly the entry's signature with `t` replaced by `i32`, and it must be a declared function, named directly: a binding that holds a function value cannot supply an entry. There is no implicit conformance. A type with a matching `less` is still not `ordered` until a line like this one says so. A type built around another often supplies a concept by passing every entry on to a field. Name the field after `through`, and its type's conformance supplies each entry the list does not name: ```landin holder: type = struct tag: u8 inner: i32 end holder holder is ordered through inner ``` `holder`'s `less` of `a` and `b` is then `i32`'s `less` of `a.inner` and `b.inner`. The field's type must conform to the concept itself, and the list may still name a function for an entry the holder supplies its own way: `holder is ordered (less: holder_less) through inner`. Where the concept takes its type as a parameter, by value, `inout` or through a pointer, the field is passed in the holder's place; an entry that returns the type, or takes it any other way, needs a function of its own in the list. A routine that takes the holder and returns the provider may stand where the field does, as `hosted/events` reaches the system handle it computes for each call; its result is a copy, so it stands in only where the concept takes the holder by value. An entry can also be called through the name of a type that conforms, as a generic function calls it through its type parameter ([1290]): `i32.less(1, 2)`, `holder.less(a, b)`. The conformance that supplies it is the one of that type whose concept declares the entry, out of the program's one register ([1280]). Where two of a type's conformances declare it, the call is an error; call it through a type parameter constrained by the concept you mean. ### [1290] Writing a generic function A generic function takes the type as an ordinary parameter, constrained with `is`, and calls the concept's entries through that parameter. ```landin sort: (t: type is ordered, data: []mut t) -> none = for k in 1.. 0 and t.less(data[j], data[j - 1]) do tmp := data[j] data[j] = data[j - 1] data[j - 1] = tmp dec j end while end for end sort ``` `t.less` is the `less` of whatever type `t` turns out to be. Because entries are reached through the type parameter, two constrained parameters never collide: `left_type.less` and `right_type.less` are different functions. Type and `fixed` parameters exist only at compile time; they add no runtime argument. A `fixed` parameter is an integer known at compile time, and inside the body it may also be used as an ordinary value. The order of parameters does not matter, so `fill: (inout data: [capacity]u8, fixed capacity: u32)` is as good as putting `capacity` first. A type parameter may also be unconstrained, for code that only moves values around. The fine print: - Every type parameter is written in the list. A name that is not in scope is a misspelling and an error, never a new type variable, just as a misspelt build option is an error ([1530]). - A generic function is not a function value. Only a call picks a concrete instance, so you cannot take `sort` itself and store it. - A private `! ...` error set is inferred separately for each concrete instance. - The compiler checks the body for each instance a call makes. A generic function nothing calls is checked only for its names and for operands no type could make valid. An error that depends on what `t` turns out to be, such as a view held across a call that may move its source, is reported once a call picks `t`. - In the body, `t(value)` converts one value to whatever type `t` turns out to be, by that type's own conversion ([0310]): `t(0)` starts a sum in any numeric type. An instance whose type has no conversion from the value is an error once a call picks it. A type parameter converts and does not construct: `t(a: 1)` is an error. ### [1300] Calling a generic function The compiler normally deduces the type from the arguments. You may also name it, in the same named-argument list as the runtime arguments. ```landin sort_demo: (values: []mut i32) -> none = sort(values) sort(t: i32, data: values) end sort_demo ``` It is all or nothing: either every type and `fixed` parameter is deduced, or the call names every one of them. Runtime arguments keep [0980]'s rule, positional first and then named. Deduction matches each written parameter type against the argument's type, exactly. It never uses the return type, a conversion or a search of the conformances, and it runs no code. Two consequences: - A writable `[]mut i32` argument still passes where `[]t` is written ([0440]), but deeper inside a type, permission must match exactly. - A fixed bound written `capacity * 2` is never solved for `capacity`; it is only checked once another argument has fixed `capacity`. Exact rules: spec [1920]. ### [1310] How generic code runs: tables, and specialization as an option A call to a generic function passes, invisibly, a table for each conformance the body uses. The table holds the type's size and alignment, then the concept's functions in the order the concept declares them. `t.less(...)` loads `less` from that table and calls it. The same tables carry `any C` values ([1370]), so static generics and runtime dispatch are one mechanism ([1690]). The tables are the meaning of generic code. Specialization replaces an indirect call with a direct one where the compiler can prove which table arrives. It is an optimization that never changes what a program does. Two independent switches control code generation: | option | values | default | |---|---|---| | `--optimize` | `none`, `size`, `speed` | `size` | | `--specialize` | `off`, `auto`, `all` | `auto` | Neither depends on `--build-mode`. A call is never specialized merely because its source type is known: the compiler needs proof of the table that actually arrives. A call stays indirect when it goes through `any`, through a table the compiler cannot trace, or in an instance whose address is taken. `--build-report=PATH` writes a report of what was specialized and what stayed indirect, and why. ### [1340] Combining concepts A concept may build on others by naming them after `is`. A type that satisfies the combined concept still conforms to each part separately. The example assumes a struct `button` with a `text` field, a type `canvas`, and functions `button_draw`, `button_click` and `button_focus` with the entries' signatures. ```landin drawable: type = concept (t: type) draw: (self: ptr t, target: ptr mut canvas) -> none end drawable clickable: type = concept (t: type) click: (self: ptr mut t, x: u32, y: u32) -> none end clickable widget: type = concept (t: type) is drawable, clickable focus: (self: ptr mut t) -> none end widget button is drawable (draw: button_draw) button is clickable (click: button_click) button is widget (focus: button_focus) ``` All three conformances are needed, because `widget`'s supplies only what `widget` adds. Having the parts does not make a type a `widget`, and being a `widget` does not make it `drawable`. Conformance is always declared, even when its list is empty. The combined concept has a name of its own, so an `any widget` value still carries one table and stays two words. In generic code, `t.entry` must name exactly one declaration across the concept and all its parents: - A parent reached twice, through two paths, is still one concept. - Two different concepts that both declare `entry` make `t.entry` ambiguous. - Parent order never decides, and a child's own entry does not override an inherited one. - A clash nobody uses is not an error. Exact rules: spec [1920]. ### [1350] Generic types A type takes parameters through its own declaration form. It is not a function that returns a type: that would be compile-time execution, which Landin does not have. Substitution, not execution. ```landin pair: type (t: type) = struct first: t second: t end pair ``` `pair(i32)` and `pair(u8)` are different types, and every use of `pair(i32)` is the same type. A growable container is generic the same way: `core/vec`'s `list(t)` is one, and [0510] explains how it keeps its empty slots out of sight. A type parameter may carry one concept constraint, and a `fixed` parameter is an integer known at compile time. Here `cmp.hashable` is a concept `core/cmp` provides, and `zeroable` is [0550]'s: ```landin import core/cmp key_value: type (key_type: type is cmp.hashable, value_type: type) = struct key: key_type value: value_type end key_value cleared: type (t: type is zeroable, fixed capacity: u32) = struct items: [capacity]t len: u32 end cleared ``` Applications are positional and complete: `key_value(u32, utf8)`, never `key_value(u32)`. A `fixed` argument is anything an array length may be ([0520]): an integer literal, a `fixed` parameter passed on by another generic declaration, a compiler fact, `sizeof` or `alignof` of a built-in scalar type, an immutable module integer, or `+`, `-`, `*`, `/` and `%` over those. So `cleared(u8, compiler.word_size)` and `cleared(u8, 2 * sizeof u32)` are types, as `[compiler.word_size]u8` is. The argument must fit its declared type. Whether an argument type may go where the body puts it, as a field or an array element, is checked after substitution. An alias may be generic too, including a union of atom sets. An alias never makes a new type: `missing | ptr t` keeps the one-word optional pointer of [0480]. The fine print: - The compiler checks a generic type's template even if nothing applies it, and reports an error that depends on the argument at each application. A generic function's body is checked per instance instead ([1290]). - An unused or phantom parameter still distinguishes instances. - A struct may not contain itself by value, even through another template. ### [1250] A conformance for a generic type A conformance for a generic type declares its type variables in front, because it holds for every one of them. The examples use two concepts met later: `iterable`, which `for` loops use ([1320]), and `mem.allocator` ([1360]). `counted(provider)` is an allocator that wraps another, and the `pair_...` and `counted_...` names are the functions that supply each entry. ```landin (t: type) pair(t) is iterable (cur: u8, item_type: t, first: pair_first, at_end: pair_at_end, item: pair_item, next: pair_next) (provider: type is mem.allocator) counted(provider) is mem.allocator (alloc: counted_alloc, grow: counted_grow, resize: counted_resize, free: counted_free) ``` The binder is an ordinary parameter list, the same form functions and generic types take. So a variable may carry a constraint, and a `fixed` parameter may appear among them. The supplying functions are generic themselves. Instantiating the conformance gives them their type argument and leaves functions of exactly the concept's shape. A family may hand its entries to a field too, `(provider: type is mem.allocator) counted(provider) is mem.allocator (alloc: counted_alloc) through inner`, as long as a field that holds a type variable has it constrained by the concept. The target must be the whole generic type applied to the binder in order, each variable used once: one conformance covers the whole family `pair(t)`. Another family for the same template and concept is a collision ([1280]), and so is a concrete exception such as `pair(u8) is iterable`. Without this form no generic container could be traversed, sorted or handed to other generic code. ### [1270] One type, several conformances A conformance is keyed by the type, the concept and the concept's other input types, so one type may satisfy the same concept more than once. The example assumes `position` is a byte-offset type, and `utf8_nth` and `utf8_at_pos` look up a character by count and by position. ```landin indexable: type = concept (t: type, idx: type, item_type: type) get: (s: t, i: idx) -> (item: item_type) end indexable utf8 is indexable (idx: usize, item_type: u32, get: utf8_nth) utf8 is indexable (idx: position, item_type: u32, get: utf8_at_pos) ``` The labels for the extra inputs, `idx` and `item_type`, are part of the key; the function labels are not. Which concepts exist, and how finely they distinguish what an operation costs, is the standard library's business. The language checks nothing about cost: a guarantee should not depend on how clever the compiler happens to be. ### [1280] Where conformances live, and what collides A conformance may be declared in any module, and two for the same key are an error. There is no precedence, no orphan rule and no override: the compiler reports the collision and somebody sorts it out. When two libraries collide, you do not have to change either. Wrap the type in a `distinct` type of your own and conform that, or pass the functions explicitly instead of through a concept. The compiler collects every conformance in every module the program reaches before it checks any generic call, whether or not anything uses the conformance. Modules the program does not reach contribute nothing. A conformance is a registration, not a name, so it needs no `public` and refuses one. ### [1260] A concept fixes its error sets A concept entry's error set is written out or absent, never inferred with `! ...`. An entry is reached through a table, and [0960] forbids an inferred set there. So the concept fixes the error set once, for every type that will ever satisfy it. That is right for allocation, where out of memory is out of memory, but it shapes how you design a concept. The same goes for what an implementation is handed: by convention, a concept with no allocator among its parameters says its implementations do not allocate. The compiler does not check that, since any hosted function can make a heap of its own ([1680]). Resist widening a concept until it fits its hungriest implementation; that hands every implementation the sum of everyone's needs. Either the hungry one picks a shape that does not need it, or there are two concepts. ### [1320] Traversal is a concept `for x in s` over your own type uses the `iterable` concept that `core/iter` declares. Conform to `iter.iterable` and your type works in a `for` loop; a concept of your own with the same name does not. ```landin -- core/iter iterable: type = concept (t: type, cur: type, item_type: type) first: (s: ptr t) -> (c: cur) at_end: (s: ptr t, c: cur) -> (yes: bool) item: (s: ptr t, c: cur) -> (v: item_type) next: (s: ptr t, c: cur) -> (c2: cur) end iterable ``` The conformance supplies the cursor type `cur` and the `item_type`, as [1250]'s `pair` does. The labels may come in any order. The loop evaluates `s` once and keeps a private copy. Each provider gets a read-only pointer to that copy, so a large struct is copied once, not on every call. The four signatures are exact: no permission, error set or `from` clause is inferred or converted. So a provider whose result is declared `from s` does not match. `item` returns a fresh value for the loop binding, never an alias into the source. A container that wants to hand out references into its storage returns a slice view instead and uses the built-in slice traversal, as `for value in vec.used(numbers)` does. The library's map and tree conform. `for each in m` walks a map's entries in insertion order, each entry a copy of its key and item. `for id in t` walks a tree's node identifiers. A source whose steps can fail is not `iterable`: it is walked with a `while` that takes each step with `try` ([1150]). ### [1330] Integer ranges are not values In `for i in 0..<10 do`, the loop evaluates the two bounds once and counts between them directly ([1150]). `0..<10` and `0..9` are loop and slice syntax ([0360]), not expressions, and the header does not go through `iterable`. For other stepping, write a struct with its own `iterable` conformance. A library could then offer `for i in step(0, 10, 2) do ... end for`; `core` has no such `step` or `step_range` today. ### [1360] Allocation is a concept An allocator is anything that conforms to `allocator`. The same container runs on the heap, in an arena or on a fixed buffer, and a deliberately failing allocator makes the out-of-memory paths testable, which almost nobody bothers with in C. This is `core/mem`'s concept: ```landin allocator: type = concept (provider: type) alloc: (self: provider, size: usize, alignment: usize) -> (p: ptr mut u8) ! out_of_memory grow: (self: provider, p: ptr mut u8, old_size: usize, new_size: usize, alignment: usize) -> (grown: bool) resize: (self: provider, p: ptr mut u8, old_size: usize, new_size: usize, alignment: usize) -> (moved: ptr mut u8) ! out_of_memory free: (self: provider, p: ptr mut u8, size: usize) -> none end allocator ``` A function that adds to a list takes the list `inout` and the allocator as an ordinary argument: ```landin record_reading: (provider: type is mem.allocator, inout readings: vec.list(u32), memory: provider, value: u32) -> none ! mem.out_of_memory = try vec.push(readings, memory, value) end record_reading ``` The same `record_reading` runs with `heap.new()` as `memory`, or with an arena over a buffer on the stack ([0820]). The list is changed, so it is passed `inout`. The allocator is passed as a handle: a small copyable value, passed read-only, that refers to its provider's state. The handle's lifetime is checked once, where the handle is made from that state, and using it does not borrow that state. So several containers can allocate through one handle, and a region can allocate from its parent while both are live. The allocator is passed to each call rather than stored in the container. A stored one would be part of the type, `vec.list(t, provider)`, so a list in an arena and a list on the heap would be different types and no function could take both. Passing it keeps the type `vec.list(t)`, at the cost of one argument to every call that can allocate. The four entries: | entry | what it does | |---|---| | `alloc` | a new block, or `out_of_memory` | | `grow` | extend the block where it is; `false`, with nothing changed, if it cannot | | `resize` | a new extent, larger or smaller, moving the block if it must | | `free` | give the block back, with the size it was allocated with | `resize` keeps the bytes the old and new extents share, and a refusal reports `out_of_memory` with the block as it was. A concept entry has no default, so a provider that can only move a block calls `mem.relocate`, which allocates, copies and frees through it. The standard library's providers and containers: | module | what it gives | |---|---| | `core/arena` | a bump allocator over storage you supply | | `core/zone` | a bump allocator that grows by taking blocks from another allocator | | `core/pool` | uniform slots over storage you supply, freed slots reused | | `core/fault` | wraps any allocator and fails once a budget of attempts is spent | | `hosted/heap` | the operating system's memory, really freed, on every hosted system | | `core/vec` | a growable list | | `core/spill` | a list that keeps its first items inline and spills to an allocator | | `core/map` | an open-addressed hash map | None of them has a hidden heap or a fallback. Every failure is `out_of_memory`, reported before anything changes: a container that cannot grow keeps its old storage and contents. The [library guide](docs/library.md) lists each module's calls. When you use the containers directly: - A map's key needs both an `equatable` and a `hashable` conformance; the combined one does not supply its parent ([1340]). Equality must be an equivalence, equal keys must hash alike under the seed the map is given, and neither may change while the key is stored, including through a pointer inside the key. The compiler does not check any of this. - A map's entry cursor is just a position. Start a new walk after any change to the map, and never resume one on a different map. - A map's fields are public. Code that works below its operations must keep the map's invariants itself. - A spill list's `spill.used` lends its items `from` the list, so the list cannot spill or be released while that view is still used ([0830]). Its first spill doubles the inline capacity, checking that the result fits `usize`, or takes eight if the inline capacity is zero. If a spill or later growth fails, the list is unchanged. These are the providers' contracts. They do not make raw storage safe: storage you hand an arena or a pool must be live, aligned and as large as you say ([1720]). ## RUNTIME DISPATCH Generics ([1290]) pick the type at compile time. When the type is only known at run time, such as a list of widgets of different kinds, use `any C`. ### [1370] `any C`: a value of some type that satisfies C `any C` holds a value of some type that satisfies concept C, decided at run time. It is two words: a pointer to the data and a pointer to C's table of entries for that type. What the pair is, as a value: - It is an ordinary copyable value, and can sit in a variable, a field or a slice. - What it points at is never copied, because its size is unknown. So the pointee must stay alive as long as any copy of the pair can use it. An arena ([0820]) is the usual place for it. - It needs no permission of its own: the concept's entries carry it. An entry declared with `self: ptr mut t` can only be satisfied by a pointer that may write, so a stateful implementation behind `any` just works. - It does carry its pointee's origin ([0770]), so an `any` over a local cannot go into a list that outlives the frame. An `any C` is itself a provider of C and of every concept C builds on ([1340]). So a generic function ([1290]) takes one, and each entry the function calls goes through the value's own table. Here an `any widget` is handed to a function that wants a `drawable`: ```landin draw_on: (provider: type is drawable, item: ptr provider, target: ptr mut canvas) -> none = provider.draw(item, target) end draw_on paint_one: (item: any widget, target: ptr mut canvas) -> none = draw_on(addr item, target) end paint_one ``` An `any C` converts to `any P` for every concept P that C builds on, directly or through other concepts. The conversion is implicit wherever an `any P` is wanted: a binding, an assignment, an argument, a result or a struct field. The converted value has the same data pointer and P's table for the same type, so its calls reach the same type's entries, and the pointee and its origin are unchanged. ```landin show: (item: any widget, target: ptr mut canvas) -> none = shown: any drawable = item shown.draw(target) end show ``` An `any C` converts to no other `any`: not to that of a concept built on C, and not to that of a concept beside it. Build such a value from its pointer with `any(addr item)` instead. A slice or array of `any C` does not convert to one of `any P`. An `any C` provides no other concept, and the compiler, not the program, declares these conformances. An `any` is not erased again: where an `any C` is wanted, pass the one you have rather than its address. Printing is where most programs first meet `any`. `io.write_format` takes its values as a `[]any text.formattable`, each built from a value's address: ```landin print_born: (host: blocking.host, name: utf8, year: u32) -> none = io.write_format(host, io.out(host), "{} was born in {}.\n", [any(addr name), any(addr year)]) else none end print_born ``` ```landin print_born(host, "Ada", 1815) -- Ada was born in 1815. ``` Integers, `bool`, `utf8` and byte strings are formattable, floats not yet, and a type of your own becomes formattable by conforming ([1240]). The text is made in a small buffer on the stack and written as it fills, so printing allocates nothing. A template whose `{}` and values differ in number fails with `text.invalid_format` and writes nothing. ### [1380] Building an `any` with `any(...)` You build an `any` explicitly from a pointer. The concept comes from context where it can; otherwise name it. ```landin make_widget: (provider: type is mem.allocator, memory: provider) -> (item: any widget) ! mem.out_of_memory = initial: button = (text: "OK") b := try mem.allocate_item(memory: memory, value: initial) item = any(b) end make_widget ``` Here the result type supplies `widget`. Without a context, `any(pointer)` needs exactly one concept the pointee's type conforms to. A read-only pointer cannot build an `any` whose concept has an entry taking `self: ptr mut t`. Once the `any` is built, binding mutability controls only replacing the pair, not the write authority its pointer already carries. ### [1390] Calls go through the table A call on an `any` looks up the entry in the table and passes the data pointer as the first argument. This is the only place in Landin that reads like a method call. ```landin paint: (items: []any widget, target: ptr mut canvas) -> none = for w in items do w.draw(target) end for end paint ``` An entry is callable this way when it meets two conditions: - Its first parameter is `self` as `ptr t` or `ptr mut t`, or `self: t` taken by value when `t` is a record. - The hidden type `t` appears nowhere else in it. A by-value `self` is copied out of the data pointer when the call is made. So to put a small handle, such as an allocator handle `memory`, behind `any`, take the address of the variable that holds it: `any(addr memory)`. An `any C` converts only to the `any` of a concept C builds on [1370]; no other two `any` types convert to each other, and a slice or array of `any C` does not convert at all. The implicit `self` takes part in the same `from`, `escaping` and origin checks as a written pointer argument. The compiler checks a call through `any C` even if the program has no conformance of C. Then no `any C` can be made and no value reaches the call, so it compiles to a trap that never runs. A library that takes an erased capability therefore builds in a program that supplies none. ### [1400] What `any` can do that generics cannot One slice can hold values of different types. A `[]t` is always one `t`; a `[]any widget` holds buttons, labels and anything else that is a widget. ## COMPILE TIME Landin has a little compile time and keeps it little. You can ask which target you are building for and choose declarations by the answer ([1500]), check a layout ([1510]), and declare build switches ([1530]). You cannot run your own code while the program builds ([1540]). ### [1490] The word `fixed` `fixed` marks something the compiler knows before the program runs. You meet it in three places: - `fixed if` chooses declarations ([1500]). - A fixed parameter is a compile-time value ([1520]). - A fixed expression is what a condition, an assertion or an option default is written in ([1500], [1510], [1530]). ### [1520] A compile-time value parameter A `fixed` parameter is a value the caller supplies at compile time, so it can size an array in the signature. ```landin make_buffer: (fixed capacity: u32, t: type is zeroable) -> (b: [capacity]t) = zeroed end ``` A fixed parameter sits beside the type parameters and works the way they do ([1290]): the call supplies it or deduces it, and it has no storage at run time. ### [1500] Choosing declarations by target `fixed if` picks which module-level declarations exist in this build. It works on declarations only, not on statements. ```landin fixed if compiler.arch == arm64 then word_bits: u32 = 64 elsif compiler.arch == cortex_m0 then word_bits: u32 = 32 end if ``` The compiler parses every arm, so a syntax error in an arm you are not building is still an error. Only the selected arm's declarations join the module; the declarations of the other arms have no names, no types and no effect. Arms may nest, an arm may be empty, and an arm opens no scope. **The facts.** The compiler supplies these facts: | fact | what it says | |---|---| | `compiler.arch` | `x86_64`, `arm64`, `rv64`, `cortex_m0`, `rv32`, `xtensa` or `synthetic_32` | | `compiler.os` | `linux`, `darwin`, `freebsd` or `freestanding` | | `compiler.word_size` | the width of `usize`, in bits | | `compiler.byte_order` | `little` or `big` | | `compiler.build_mode` | `debug`, the default, or `release` | | `compiler.c_sysv_lp64`, `compiler.c_darwin_lp64`, `compiler.c_aapcs64_lp64`, `compiler.c_riscv_lp64d`, `compiler.c_aapcs32`, `compiler.c_riscv_ilp32`, `compiler.c_xtensa_windowed_ilp32` | which C ABI the target uses, each true for its own ABI alone | | `compiler.c_runtime` | whether C's runtime starts the program and its library is linked | | `compiler.feature.NAME` | whether the selected CPU level has feature NAME | | `compiler.cache_line` | the line of the device description's cache, in bytes, or 0 without one | Build mode is a value you ask for. It does not change runtime checks or optimization. **The C ABI and the C runtime.** Ask the C ABI question directly rather than guessing the answer from the architecture: Linux and Apple arm64 share `compiler.arch == arm64` and answer the C ABI question differently. `compiler.os` is separate from the C ABI because Linux and FreeBSD share a calling convention on each architecture but not every libc record layout. It is `linux`, `darwin`, `freebsd`, `windows` or, on firmware, `freestanding`. `compiler.c_runtime` is always true on Darwin and FreeBSD, true on Linux only when the build asks with `--link=libc`, and never true on Windows, which links no C runtime, or on firmware. A library calls the C library only where this fact says it is there. **CPU features.** A build assumes a CPU feature level. You choose it with `--level=`, and it defaults to the oldest processor of the architecture. `compiler.feature.NAME` asks about one feature, such as `bmi2` on x86-64, `lse` on arm64, `idiv` on the M profile or `xtheadba` on RV64. A feature of another architecture is simply false, so you need no `compiler.arch` test first: ```landin fixed if compiler.feature.idiv then divide_cycles: u32 = 12 else divide_cycles: u32 = 40 end if ``` A level changes which instructions the build may use, never a layout or a calling convention, so code built at two levels links together. `spec.md` lists the levels and their features. **Values that differ by target.** When only a value differs, you need no `fixed if` at all. A module value may read a fact, and a function branches on that value with an ordinary `if`: ```landin fast_count: bool = compiler.feature.popcnt on_linux: bool = compiler.os == linux word_bytes: usize = compiler.word_size / 8 ``` An integer fact takes its type from context. You read an atom fact, which is one of `compiler.arch`, `compiler.os`, `compiler.byte_order` and `compiler.build_mode`, by comparing it with one of its atoms. **Inside a function.** A function body reads no fact directly, except in an array length, which is part of a type [0520], and `fixed if` cannot begin a statement. Instead: - What differs by value branches on a module value like those above. - What needs a call that one system lacks is a function declared in each arm of a module-level `fixed if`. **Conditions.** A condition is a closed fold: literals, parentheses, unary `-`, integer `+ - * / %` without overflow, integer comparisons, equality, `not`, `and`, `or`, and `sizeof` and `alignof` of the built-in scalar types. - Sizes count target bytes, so `compiler.word_size == 8 * sizeof usize` holds on 32-bit and 64-bit targets alike. - A condition may also read your own options ([1530]). - The compiler refuses calls, runtime names, measurements of your own types and aggregate operations, even in an operand that short-circuiting would skip. **Forms that do not exist.** There is no `public fixed if`, no trailing name after `end if`, and no `fixed if` inside a block, struct, signature or template. Exact rules: spec [1940]. ### [1510] Checking a layout at compile time `compiler.assert` stops the build when a fixed condition is false. ```landin compiler.assert(sizeof usize == 8) ``` `compiler.assert` is a module-level directive, and a selected `fixed if` arm may hold one too. An assertion in an inactive arm does nothing. The condition is the same closed fold as in [1500] and must be a bool. A false condition is reported at its own source. An assertion may also measure your own types, as in `compiler.assert(sizeof header == 8)`. The compiler then checks it once the type is laid out. `compiler.assert` is a builtin call rather than a keyword, like the rest of [1560]. That leaves the word `assert` free for an ordinary function of your own, such as the `assert` of [1040]. ### [1530] Your own build switches An `option` declares a typed build switch with a default, which the build can override. A misspelt switch is a compile error, never a silent false. ```landin option log_level: u32 = 0 ``` Read it in a fixed condition, and set it on the command line with `--option=log_level=2`: ```landin fixed if log_level > 1 then trace_enabled: bool = true else trace_enabled: bool = false end if ``` **Type.** An option's type is `bool` or a built-in integer type; `usize` and `isize` take the selected target's bounds. An option has no storage at run time, and its name is visible only in fixed conditions, option defaults and compiler assertions. **Declaration.** Option names are global across the whole program, so each is declared exactly once, unconditionally at module level and never inside a `fixed if` arm: the compiler collects every option before it chooses arms. **Names.** An option may not share a name with either of these: - an active declaration or import in its declaring module, including another file of that module; - a compiler-owned atom such as `arm64` or `release`. Ordinary bindings in unrelated modules may use the same spelling. Fixed configuration still reads the global option, while runtime uses ordinary module/import lookup. **Defaults.** A default may refer to another option, even one declared later, and sees that option's overridden value. The compiler refuses cycles, and every default must be valid even when overridden. **On the command line.** `--option=NAME=VALUE` takes `true` or `false`, or signed decimal integer text. Unknown or repeated names, malformed values and values out of range are errors. `--build-mode=debug` or `--build-mode=release` sets the separate built-in build mode. ### [1540] No compile-time execution There are no compile-time loops and no compile-time function calls. Nothing of yours runs while the program is being built. The builtin modules of [1560] look like an exception and are not one. Their members are operations the compiler recognizes, not your functions run during the build, and nobody can add another. Their inputs differ: - Some must be fixed, such as assertion conditions, library names and assembly text. - Others can be runtime values, such as atomic data and assembly input operands. When you need a generated table or a structure-of-arrays layout, write a program that writes the source, and have the build run it. ## THE TOOLCHAIN, C, AND THE MACHINE This section is about the edges of a program: what the compiler produces, how Landin calls C and C calls Landin, how a program links, and how it reaches the processor with atomics, assembly, placement and device registers. It ends where a program begins: the entry point, the capabilities it hands out, and what happens when a check fails. ### [1550] What the compiler produces `refine` compiles the whole program at once into assembly text, and the platform's own assembler and linker turn that into an executable. There is no LLVM and no C in between. Going through C would lose the calling convention, the traps and the debug information Landin is precise about, so every target's backend is Landin's own. The [README](README.md#current-compiler-capabilities) lists the targets. - The emitted assembly is deterministic: the same program and options give the same bytes, whatever the build directory, environment or order. The linked executable is not covered by that promise. - Every ordinary function and every interrupt handler sets up the frame pointer, so a debugger or a backtrace can always walk the stack. On Cortex-M0 a function with no calls, no assembly and no stack changes may leave it alone (spec [1990]). A naked function ([1570]) owns its frame instead. - The whole program is compiled together ([1480]). The compiler may keep private caches, but there is no stable separate-compilation interface. On Cortex-M the `cortex_m0` backend emits ARMv6-M Thumb, the default `armv6-m` level. - **Levels.** `--level=armv7-m`, `--level=armv7e-m` or `--level=armv8-m.main` lets the backend use that level's instructions too, which the processor must then support. All four levels are little-endian. - **Floats.** Floats are computed in software unless the device description names a float unit. A Cortex-M7's `compiler.float_unit("fpv5-d16")` makes the build hard-float at `armv7e-m`: its f32 and f64 arithmetic becomes VFP instructions, its floats are passed in s and d registers, and `compiler.feature.fp` and `compiler.feature.fp_dp` say so. - **Firmware.** A firmware request emits its own reset code, vector table and linker script. Reset copies initialized data and RAM code out of flash and clears BSS before your code runs. - **Caches.** A Cortex-M7's description may also declare its caches, `compiler.cache("armv7-m-l1", 32)`. Reset then turns them on after those copies and off again if the entry returns, and `compiler.feature.cache` and `compiler.cache_line` say so. A direct memory access (DMA) buffer is kept in step with the caches through `core/cache`. Exact rules: spec [1990]. ### [1560] The `compiler`, `assembler` and `linker` modules Three builtin modules reach the toolchain. They belong to the reserved `landin` package (`landin/compiler` and its siblings) and are in scope without an import, which is why nobody else can use their bare names. | module | what it reaches | | --- | --- | | `compiler` | target, word size, byte order, build mode, CPU features; the atomic, volatile and register intrinsics; the two stack builtins under fibres ([1675]); `compiler.unreachable()`; `compiler.utf8_unvalidated(bytes)` | | `assembler` | inline assembly | | `linker` | libraries, sections, entry | Two of those calls: - `compiler.unreachable()` is a call that never returns. It stops the program as a failed check does ([1670]). Given a `caller` parameter of the function it is written in, `compiler.unreachable(where)`, it reports the stop at the call that filled the parameter ([1040]). - `compiler.utf8_unvalidated(bytes)` is text of bytes known to be UTF-8, made without reading them and only inside `unchecked` ([0600]). The members of all three modules are built into the compiler; you cannot write one yourself. Some arguments must be fixed when the program is compiled: - `compiler.assert` takes a fixed condition. - `linker.library` takes a fixed name. - `assembler.block` takes fixed instruction text. - An atomic's ordering is always a fixed `compiler` atom. Atomic and volatile pointer and value operands, and assembly inputs, can be runtime values. What works today: - Every hosted target has the compiler facts, `compiler.assert`, `linker.library` ([1590]) and the scalar atomics and barriers ([1620]). - Firmware targets also have placement annotations ([1640]) and the firmware entry request ([1650]), which hosted targets refuse, and Cortex-M firmware links C archives through `linker.library` ([1590]). The [capability inventory](docs/capabilities.md) names the supported firmware targets and their limits. - `assembler.block` is checked on every target ([1630]). - Any other tool operation is refused by name. Why some things are builtin and others are not: something is builtin when the compiler has to understand it. - Atomics are builtin, because opaque assembly in a hot loop wrecks the register allocation around it. - Masking interrupts is not. A critical section wants nothing moved across it, which is exactly what opaque assembly gives. So `cortex_m.disable_interrupts` and its kin are an ordinary module per target, written with `assembler.block` ([1630]). - An operation that comes to mean the same thing on every target, as the atomics do, can move into `compiler`. - There are no vector intrinsics: fixed arrays are the vector type and take element-wise operators ([0590]). ### [1580] Importing from C A bodyless `extern(c)` declaration imports a C function. A compilation reads Landin, never C headers: `refine bindings`, a deterministic binding generator, asks Clang what a header declares and writes these declarations for you. ```landin none_returned: atom allocation: type = none_returned | ptr mut u8 extern(c) malloc: (n: usize) -> (p: allocation) extern(c) free: (p: ptr mut u8) -> none ``` **Null.** A C pointer may be null and a Landin pointer may not. So a C result or parameter that may be null is [0480]'s one-atom pointer union, which costs no extra bits, and you `match` the result before using the pointer. - `ptr(0)` is refused, and so is any fixed expression that folds to zero at the target's `usize` width. - A pointer built from an integer at run time is checked, and zero traps, even in `unchecked`: losing the origin is not permission to make null. - Absent allocator backing is a named union too, never a fake `ptr(1)`. **What a header leaves out.** A header does not say everything Landin wants to know: whether a pointer may be null, who owns it, what it is `from`, whether C retains it, how to read incoming varargs. The generator takes that from a written policy, not from a handwritten replacement signature. **A function found while the program runs.** Such a function, a symbol of a loaded library for example, is just an address. Apply a C function type to it and you have a function value: ```landin c_adder: type = extern(c) (a: i32, b: i32) -> (r: i32) add_at: (address: usize) -> (sum: i32) = add := c_adder(address) sum = add(2, 3) end add_at ``` Nothing can check that code of that type is there, as nothing checks a C cast, and the value is yours to call only while the library stays loaded. **The supported ABIs.** Landin supports seven C application binary interfaces (ABIs): | C ABI | where | | --- | --- | | SysV AMD64 LP64 | Linux and FreeBSD x86-64 | | Apple's arm64 variant of AAPCS64 | macOS | | the standard AAPCS64 | Linux and FreeBSD arm64 | | RV64 LP64D | Linux RV64 | | AAPCS32 | Cortex-M | | the Windows x64 convention, LLP64 | Windows x86-64 | | Microsoft's arm64 variant of AAPCS64, LLP64 | Windows arm64 | Under Cortex-M's AAPCS32, floats travel in the float unit's registers when the device description has one and in core registers when it has none. **C's types.** `platform/c` names them: the signed and unsigned integer widths, `c_size`, `c_ptrdiff`, `c_float`, `c_double` and `c_bool`. It asserts `compiler.c_sysv_lp64 or compiler.c_darwin_lp64 or compiler.c_aapcs64_lp64 or compiler.c_riscv_lp64d or compiler.c_aapcs32 or compiler.c_win64_llp64 or compiler.c_windows_arm64_llp64`, so it admits exactly those seven ABIs; another target with the same pointer width, RV32's or Xtensa's, is not admitted. - The first four are LP64, with a 64-bit `long`. AAPCS32 is ILP32, so there `c_long` is an `i32` and `c_size` a 32-bit `usize`. Both Windows ABIs are LLP64: `c_long` is an `i32` beside a 64-bit `c_size`. - Plain `c_char` is the ABI's plain `char`, a number and not a Unicode scalar: `i8` under SysV, Apple's ABI and both Windows ABIs, `u8` under the standard AAPCS64, RV64 and AAPCS32. What crosses the boundary: | kind | how it crosses | | --- | --- | | integers, `bool`, pointers, `f32`, `f64`, C function values | by value | | nonempty `layout(c)` structs, with nested structs, nonempty fixed arrays and fixed C callbacks as fields | by value | | packed records and records with a flexible array member | by pointer only | | fixed arrays | as fields or pointees, never as a by-value argument or result | | C enums | as their integer values | | unions, bitfields, globals, thread-locals, nullable callbacks | through the generator's representations and adapters | Anything else a header can say, such as `long double`, 128-bit integers, complex or vector types, or forwarding a `va_list`, is refused by name rather than guessed. **Variadic functions.** A variadic C function writes `, ...` after at least one fixed parameter. This `...` is C's variadic tail, unrelated to [0960]'s `! ...`. ```landin extern(c) printf: (format: ptr u8, ...) -> (written: i32) say_count: (format: ptr u8, count: i32) -> none = _ = printf(format, count, 1.5) end say_count ``` - Calls, direct or through a function value, are positional only, including the fixed parameters. - The variadic tail takes scalars, pointers and fixed C callbacks, not structs, arrays, slices, atoms or `any`. - C's promotions apply: `f32` becomes `f64`, and `bool` and narrow integers become C `int`. An untyped literal is `i32` or `f64`. - A variadic function value may be stored and called in Landin, but it cannot fill a C callback field or parameter. - A Landin definition cannot receive varargs; the generator writes a C adapter from an explicit extraction schema instead. - Cortex-M declares no variadic C function yet. Write a C function of fixed arity that makes the variadic call, and import that one. Exact rules: spec [1975]. ### [1600] Exporting to C Give an `extern(c)` declaration a body and you have defined a C function in Landin. Make it `public` and C code can call it by its name. ```landin public extern(c) my_add: (a: i32, b: i32) -> (r: i32) = r = a + b end my_add ``` `extern(c)` chooses the calling convention and nothing else: - Without a body it imports. - With a body it defines. - `public` is what exports, making the declared name a global symbol. A private C definition is still useful: its address can be handed to C as a callback. Limits: - A C signature is not generic, takes only read-only parameters and returns at most one value. - Landin's declared failures do not cross. Recover inside the body and return the status or value the C interface promises. - Nothing is promised if a foreign exception or a `longjmp` crosses Landin frames. - On Cortex-M a C signature cannot be variadic: import a fixed-arity C function that makes the variadic call instead. ### [1610] Choosing a symbol's linker name `link(symbol: "...")` gives a declaration a linker name its Landin name cannot spell, or does not want. It follows `extern(c)` for a C import or definition, or stands alone before a native Landin function or a module datum. ```landin link(symbol: "native_identity") identity: (value: i32) -> (result: i32) = result = value end identity extern(c) link(symbol: "foreign_add") add: (a: i32, b: i32) -> (r: i32) ``` Landin code still calls these `identity` and `add`: `link` changes neither lookup nor signature nor Landin visibility. The standalone form keeps the native Landin convention and still needs `= body end`; `link` never means C and never means bodyless. It does export. Which symbols the linker sees: - A link name is a global symbol whether or not the declaration is `public`. That is how you export a module datum deliberately. - Without `link`, C imports and public C definitions use their declared name. - The program's entry is global, and so are a public definition in a machine convention and a Cortex-M definition with [1640]'s section, alignment, vector or `keep` (spec [1975]). - Every other function and datum, public or private, is a local symbol under its own name, so no C library can collide with it. It is renamed, with its module path, only when the program holds that name twice. The rules for a link name: - A link name matches `[A-Za-z_.$][A-Za-z0-9_.$]*`: no whitespace, no `@` suffix, no assembler expression. - It is the name before the platform's prefix. ELF uses it unchanged; Darwin adds one underscore, so `foreign_add` becomes `_foreign_add` and `_entry` becomes `__entry`. The backend quotes it where the assembler needs that. Native and C link names follow the same rule. - Bodyless C declarations may share a symbol with each other and with one definition if their signatures agree. Disagreeing signatures and a second definition are refused. `escaping` counts, although C has no such word: an import of a C function that keeps its pointer must say so, as the definition does. Exact rules: spec [1975]. ### [1615] Storage local to each thread `link(thread)` before a module `mut` binding gives every thread its own instance of it. A thread reads and writes only its own, and each one starts at zero when its thread starts. ```landin link(thread) mut last_failure: i32 note_failure: (number: i32) -> none = last_failure = number end note_failure ``` Two threads calling `note_failure` at once each keep their own number, so this needs no lock. `hosted/system` keeps each thread's last errno this way. - There is no initial value: write none, and use a type that has a zero, so not a pointer or a slice. - It takes no `symbol` or `section`, so a C thread-local is not named this way; use the binding generator ([1580]). - On a microcontroller, which runs one thread, it is ordinary module storage. - Its address is good while its thread runs. Do not hand it to a thread that may outlive the one it belongs to. Exact rules: spec [1996]. ### [1590] Linking a library `linker.library` asks the C driver for a library, as `-lNAME` asks it in C. Write it next to the declarations that need it, not in a separate build file. `linker.directory` says where to look, relative to the file it is in. ```landin linker.library("raylib") linker.library("m") linker.directory("vendor/lib") ``` This links `libraylib` from `vendor/lib` beside the source, and `libm` from wherever the C driver keeps it. - **The name** is a fixed text literal of ASCII letters, digits, `_`, `-` and `.`. It is nonempty, does not begin with `-` and is not only dots. The driver takes a shared library or an archive of that name, as it would for a C program. - **Order.** Active directives reach the linker after the program, in source order, repeats included. So moving one among the module's declarations can change how archives resolve. This is the one place where declaration order matters. A directive in an inactive arm of a `fixed if` ([1500]) adds nothing. - **A directory** is a fixed, nonempty text literal: relative to the directory of the file that names it, or absolute. One that does not exist is refused before anything is linked. - **`-L DIR`** on `refine compile`, `run` or `check` names another directory, relative to where the build runs. It is searched first, so a build can put its own copy of a library ahead. - **At startup.** Each directory is also where the program looks for a shared library when it starts. - **A missing library.** A library the link cannot find is named with every directory searched. - **On Linux** a library links beside the C library, so a build that asks for one needs `--link=libc`. The default static link ([1650]) refuses a library, and refuses a directory too. - **Cortex-M firmware** links each library as a static archive built for its core, after the program and before the compiler's runtime. It refuses one that brings C constructors, thread-local storage or a dynamic linkage, none of which its startup can honour. ### [1570] Calling conventions A function's calling convention is written `extern(...)` before its name. Without one, a function uses Landin's own convention. | convention | for | | --- | --- | | `extern(c)` | the target's C ABI ([1580], [1600]) | | `extern(interrupt)` | an interrupt handler, whose entry, exit and vector placement differ from a call ([1640]) | | `extern(naked)` | no prologue at all: the body is one assembly block ([1630]) | The convention is an atom, not a keyword, so the set can grow, for example to `extern(aapcs)`, `extern(sysv)` or `extern(win64)`. No other convention is in Landin yet. The two machine conventions, `interrupt` and `naked`, are their own function types: - A definition is nongeneric, exactly `() -> none`, and declares no failures. Its function value can be stored or named by a vector, but not called or converted to an ordinary or C function. - An interrupt handler runs an ordinary Landin frame on top of the hardware's exception frame and returns through EXC_RETURN. - A naked body is one assembly block with no compiler prologue. The stack, registers, calls and return instruction are yours, and falling off the end traps. - Neither convention keeps a function from section garbage collection ([1640]). - Naked functions also work on hosted x86-64, arm64 and RV64; `platform/linux`'s process entry is one. ### [1620] Atomics Atomic operations are `compiler` builtins, not assembly, so the compiler knows which memory they touch and can still allocate registers around them. The ordering is a fixed atom. ```landin bump: (p: ptr mut u32) -> none = _ = compiler.atomic_add(p, 1, compiler.acq_rel) end bump ``` `core/atomic` wraps one `u8`, `u16`, `u32` or `u64` in a cell whose operations carry their orderings in their names: | operations | ordering | | --- | --- | | `load` | acquires | | `store` | releases | | `exchange`, `add`, `compare_exchange` | acquire and release | | `load_relaxed`, `store_relaxed`, `add_relaxed` | order nothing else | Cortex-M0 has no read-modify-write atomics, so there a cell has no `exchange`, `add` or `compare_exchange`, there is no `u64` cell, and the compiler reports a call to one. What it has is `sole_add`, the single writer's add: a load and a store, correct while only one context, say an interrupt handler, writes the cell. State that several contexts write needs `platform/cortex_m`'s critical section instead. A cell, and the single writer's add on it: ```landin import core/atomic mut ticks: atomic.cell(u32) = zeroed count_tick: () -> none = _ = atomic.sole_add(addr ticks, 1) end count_tick ``` Each tool for shared memory does one thing: | tool | what it gives | | --- | --- | | atomics | synchronization of coherent CPU memory between threads | | volatile accesses ([0850]) | every access happens, as written; no synchronization between threads | | compiler barrier | the compiler forgets what it knew about memory; no hardware ordering | | the target's device and completion barriers | hardware ordering and completion of the accesses before them | A direct memory access (DMA) buffer stays an ordinary slice. When the device has finished, by its own protocol and not merely because an interrupt arrived, make its writes visible with the target's barriers or cache maintenance and a compiler barrier. Then read the buffer. Masking interrupts does not stop DMA. `spec.md` defines the supported operations, the exact orderings, alignment traps, happens-before and what a race may do. Exact rules: spec [1990]. ### [1630] Inline assembly, for what has no builtin `assembler.block` takes fixed quoted or raw text in a function body, and after it the operands that carry values in and out. An operand names its direction, its name, its type and the register it is placed `at`: ```landin disable_interrupts: () -> (previous: u32) = previous = assembler.block("mrs {mask}, primask\ncpsid i", out mask: u32 at general) end disable_interrupts restore_interrupts: (previous: u32) -> none = assembler.block("msr primask, {mask}\nisb sy", in mask: u32 at general = previous) end restore_interrupts ``` - **The register** is a name the target answers for, never text. `general` asks the compiler to choose one, and `{mask}` in the text is where the chosen register goes, spelled at the width the operand's type selects. A fixed register is the architecture's own full-width name, and the text may use it directly. - **The direction:** `in` carries a value in, `out` carries one out, and `inout` does both through one register. - **The value.** The outputs are the block's value, as a function's named returns are its: one is a scalar, several are an anonymous result you destructure. ```landin (low, high) := assembler.block("rdtsc", out low: u32 at rax, out high: u32 at rdx) ``` **What an operand can be.** - An integer scalar that fits one register, placed `at general` or at an integer register. - An `f32` or `f64`, placed `at float` or at a float register: `xmm3`, `v3`, `f3`, or `d3` on a Cortex-M7 whose description has its float unit. A target without float registers, such as a Cortex-M with no float unit, refuses a float operand. - A pointer crosses as `usize(p)` and comes back through `ptr(u)`, whose zero check then happens there. The integer keeps no permission. So a function around a block that writes storage takes it as `ptr mut u8` or `[]mut u8`: its callers are checked against that parameter, and an immutable buffer is refused there rather than handed to the system. - A flag comes back as `x <> 0`. Inputs are evaluated once, left to right, before the block runs. Landin has no square-root builtin, so a block is how you reach the instruction. `float` chooses a float register, as `general` chooses an integer one, and the text spells it at the operand's width: `%xmm1` for either on x86-64, `d1` or `s1` on arm64. ```landin root: (x: f64) -> (r: f64) = r = assembler.block("sqrtsd {x}, {r}", in x: f64 at float = x, out r: f64 at float) end root ``` **What a block may touch.** - Every block may overwrite the registers a call may, and the flags. - A register a call must preserve is declared, as an operand or as a discarded output `out _ at rbx`, or `out _ at v8` for a float one. That declaration is what makes the function save it. - The frame, stack and link registers are never named, so a block cannot break a backtrace. - The language reserves no register of its own. - A block that changes x86-64's direction flag, or a float unit's rounding mode or exception flags, puts them back before it ends. **Every block is opaque to the compiler.** Memory knowledge is invalidated and memory accesses cannot be moved across it, which is exactly what a critical section wants. It is not itself a hardware barrier. An ordinary block is straight-line code, with no labels or calls; a system call returns to the next instruction, so it is straight-line too. **The common blocks, already written.** `platform/cortex_m` wraps them: - `disable_interrupts()` returns the prior PRIMASK, and `restore_interrupts(previous)` puts it back, so nested critical sections do not enable interrupts too early. Both work in thread and handler mode. They do not stop DMA or mask NMI or HardFault. - `wait_for_interrupt()` issues DSB, then WFI. Waking up is a reason to check the device again, not proof that it finished. - `compiler_barrier`, `device_barrier` and `completion_barrier` are the three distinct boundaries of [1620]. There is no cache or scheduler API. **A naked body.** A naked body ([1570]) owns its control flow, so its block may use labels and branches. This entry runs after the compiler's reset has initialized data and stacks: ```landin extern(naked) start: () -> none = assembler.block(""" 1: wfi @ sleep until an interrupt b 1b @ then sleep again """) end start ``` The compiler request names the source entry: ```sh refine compile main.ldn --target=cortex-m0 --firmware-entry=start --emit=exe ``` A naked entry may set up PSP or call explicitly linked ordinary code, but it must then meet that code's eight-byte stack alignment, r9 and frame obligations. `none` is not a promise never to return: the compiler traps if the entry returns or the naked block falls through. There is no hosted caller to return to. **Comments in the text.** A line of the text may end in a comment, written as the target's own assembler writes one: `@` on Cortex-M, `//` on arm64, `#` on x86-64 and RV64. The compiler removes it before it reads the text, so a register or a `{name}` in a comment means nothing, and it never reaches the assembly the compiler writes. Any other form, `/* */` or another target's, is refused, and so is a number with a `_` in it: the text is the assembler's, and its numbers take no separator. Exact rules, with each target's registers, the text rules and your obligations: spec [1990]. ### [1640] Placing code and data on a microcontroller On a firmware target, a `link(...)` annotation also places a declaration: in a section, at an alignment, in an interrupt vector slot, and kept against the linker's section garbage collection. Cortex-M, RV32 and Xtensa all place declarations this way. The example and the vector table below are Cortex-M's; RV32 and Xtensa have tables of their own, and the compiler checks a slot against the one selected. ```landin link(vector: 16) extern(interrupt) device_handler: () -> none = assembler.block("nop") end device_handler link(section: ".rodata.firmware_mark", align: 16, keep) firmware_mark: [4]u8 = [55, 48, 49, 0] ``` Slot 16 is IRQ0 in the selected profile: a vector number is the absolute slot in the table, not an IRQ number or a peripheral's name. Calling convention, symbol name, placement and retention are four independent choices; none implies another. **The vector table.** The compiler owns it. Its first word is the initial stack pointer, its second the compiler's reset, reserved slots are zero, and `vector` annotations fill in handlers with their types checked. So a stack address, a reserved word and a handler can never be mixed up. A vector annotation needs a firmware-entry request ([1650]). **What survives the link.** - The table is kept and refers to each handler in it, so those handlers survive. - An interrupt function nothing refers to and nothing keeps can disappear. - `keep` retains the section that holds the declaration. Several objects placed in one section share that retention. - A link name alone retains nothing. **Where things go.** | what | sections | | --- | --- | | functions | `.text.*` in flash, or `.ramtext.*`, copied to RAM at reset | | immutable data | `.rodata.*` | | mutable data | `.data.*`, or `.bss.*` when zeroed | - `align` is a power of two up to 256. It places the object and does not change its type's layout. - `align` and `vector` take decimal literals; digit separators are fine, hex and expressions are refused. - `region: "NAME"` places a function or module datum in a region of the device description, by name rather than by section. Code needs a region that may execute and mutable data one that may be written, and reset copies or clears it there. - Without a device description, the image has the reference firmware profile's 32 KiB of flash and 16 KiB of RAM, whose top 4 KiB is reserved for stacks; a description gives its own. The linker checks bounds and overlap. - A generic function is a function for each instance, and every instance goes to the section, alignment or region it is placed in. A vector slot, the boot stage and `keep` each name one function, so a generic one takes none of them. - The compiler refuses reserved vectors, a section that does not match the declaration, duplicate attributes and symbol collisions. - There is no module initialization in user code ([1460]). **A second boot stage.** Some boot ROMs run a second stage before the image: RP2040's reads its flash through one. On such a chip that stage lives in the device description, as a naked function marked `link(boot_stage)`. The description's boot kind places it at the start of the image, and the compiler seals it with the checksum the ROM checks. Nothing else is marked that way, and nothing else in a description is code. ### [0730] Register images: flags, selections and sets A hardware register mixes kinds of field, and confusing them is the classic driver bug. Landin describes a register as a packed struct whose fields sit at bit positions you write down. | kind | what it is | how you write it | |---|---|---| | flag | one bit | `bool` | | selection | one of several named values, encoded as the datasheet says | a union of atoms with encodings | | set | several independent flags at once | a packed struct of `bool` | | number | a plain number | an unsigned field such as `u12` | The examples below use these atoms: ```landin irq_rx: atom irq_tx: atom irq_err: atom internal: atom external: atom pll: atom active_low: atom active_high: atom by_1: atom by_2: atom ``` **A selection** is a union that gives each atom its encoding. The encoding belongs to the union, not to the atom, so the same atom may be encoded differently in another register. The width is the smallest that holds the largest encoding; write a base type only when the datasheet gives the field more room than it needs. ```landin polarity: type = (active_low = 0 | active_high = 1) -- one bit clock_mode: type = (internal = 0 | external = 1 | pll = 4) divider_sel: type = u4 (by_1 = 0 | by_2 = 1) -- four bits, as given ``` **A set** is a packed struct of `bool`, one field per member, each at the bit its member's encoding names. - Membership is a field read. - Adding or removing a member is a field write. - Building one is an ordinary struct literal with `of` ([0720]). There is no set literal or set operator, because a struct needs none. Inside a larger image the same fields sit at the image's bits, offset by where the set begins. ```landin irq: type = (irq_rx = 0 | irq_tx = 1 | irq_err = 2) irq_set: type = layout(packed, u32) struct irq_rx: bool at 0 irq_tx: bool at 1 irq_err: bool at 2 end irq_set control: type = layout(packed) struct enable: bool at 0 mode: clock_mode at 4..6 irq_rx: bool at 8 -- irq's encodings, from bit 8 irq_tx: bool at 9 irq_err: bool at 10 divider: u12 at 16..27 end control ``` A set earns its place when its members mean something. A numbered bank of lines does not: sixteen output pins are `[16]bool` at `0..15`, not sixteen invented atoms. **Positions are written.** Bit positions are never implied by field order, so reordering the fields of a published register is not a hidden breaking change. In a packed struct every field carries a position, or none does. Any bit no field claims is reserved: you cannot name it, no completion list offers it, and a read-modify-write leaves it untouched. **You rarely write these by hand.** A generator reading a vendor's System View Description (SVD) file writes the fields, and the helpers [0740] uses, for every register: `refine svd` generates them ([devices](devices/README.md)), and running a generator as a step of a build belongs to the companion tool. The language has no `set(X)` type former to do it instead. **A field may be an array**, which is how a real peripheral packs sixteen two-bit pin settings into one word. The element width times the count must equal the range, and element zero takes the low bits. ```landin pin_input: atom pin_output: atom pin_alternate: atom pin_analog: atom pin_mode: type = (pin_input = 0 | pin_output = 1 | pin_alternate = 2 | pin_analog = 3) moder: type = layout(packed) struct pins: [16]pin_mode at 0..31 end moder set_pin: (inout m: moder, n: usize, mode: pin_mode) -> none = m.pins[n] = mode end set_pin ``` Indexing such a field with a run-time value is a shift by a computed amount, with a bounds check that stays even in `unchecked`. Do it on an image in memory, never straight on the device ([0740]). Fine print: - A packed struct is a raw image, and every bit pattern is a valid image. Copying, passing and returning it keep all its bits. - Reading an encoded field checks that the bits name a member and traps if they do not, so a `match` on the result can be exhaustive. - Writing a field leaves every other bit alone, and a fresh literal starts from zero. A packed field has no address of its own: to update one, pass the whole image. - `layout(packed, u32)` keeps a 32-bit carrier even when the highest position would fit a smaller one. - Field widths run from `u1` to `u64` inside packed structs only; they add no arbitrary-width arithmetic or calling convention. Exact rules: spec [1870]. ### [0740] Reading and writing a device register A device register is read and written by two operations, and how the register behaves is data you pass them, not a keyword: - `compiler.register_read(pointer, read_mode)` - `compiler.register_write(pointer, image, write_mode, reserved_policy, named_mask)` The pointer is an ordinary one to `u8`, `u16`, `u32` or `u64`, and its width is the one transaction the device sees. Modes and policies are atoms, so a generator can describe write-one-to-clear, clear-on-read and whatever the next vendor invents without the language growing a word for each. ```landin status_raw: (base: usize) -> (raw: u32) = port: ptr u32 = ptr(base + 0x04) raw = compiler.register_read(port, compiler.normal_read) end status_raw clear_events: (base: usize, events: u32) -> none = port: ptr mut u32 = ptr(base + 0x08) compiler.register_write(port, events, compiler.one_clears, compiler.write_zero, 0x0000_0007) end clear_events ``` | argument | values | |---|---| | read mode | `compiler.normal_read`, `compiler.clear_on_read` | | write mode | `compiler.normal_write`, `compiler.one_clears` | | reserved policy | `compiler.preserve`, `compiler.write_zero`, `compiler.write_one` | | named mask | a fixed number of the register's width, with a one at every bit a field names | A register that cannot be read has no read to perform, so `compiler.no_read` is an error rather than a mode, and so is `compiler.no_write`. The operation, not the pointer's type, makes an access a device transaction: there is no `volatile ptr` and no `register(t, ...)` wrapper type. **Changing one field.** You cannot write a single field of a device register. For an ordinary read/write register, read the whole image, change it locally and write it back whole. The generator of [0730] writes, beside `control`, `control_decode` from the raw `u32` to the image, `control_encode` back, and the constant `control_named_mask`: ```landin reset_flags: (base: usize) -> none = port: ptr mut u32 = ptr(base) image: control = (enable: true, mode: external, irq_rx: true, of zeroed) compiler.register_write(port, control_encode(image), compiler.normal_write, compiler.write_zero, control_named_mask) end reset_flags read_modify_write: (base: usize, n: u16) -> none = port: ptr mut u32 = ptr(base) mut image := control_decode(compiler.register_read(port, compiler.normal_read)) image.divider = n compiler.register_write(port, control_encode(image), compiler.normal_write, compiler.preserve, control_named_mask) end read_modify_write ``` - A fresh local literal knows nothing of what the hardware holds. To keep reserved bits as the device has them, read the image first, as `read_modify_write` does; `compiler.preserve` never reads behind your back. - That read, change and write is not atomic. - The read, change and write does not carry over to clear-on-read or one-clears registers: a destructive read consumes state, and a one-clears readback is not a command. **Reset values.** A register's reset value initializes nothing. It is what the datasheet says the register holds after a reset, generated as a constant so that tools and readers know where they start. The hardware puts it there, not the program. Exact rules: spec [1870]. ### [1650] Where a program starts A hosted program starts at `public main: () -> (code: i32)` in the entry module, and `code` is the exit status, passed through the system's C ABI. **Arguments.** The arguments are not parameters. You ask the host for them, as `io.argument(host, 0)` does in "Reading a file" at the top: the host keeps the argument table and lends each argument as an OS string ([1660]). The first argument is the one after the program's own name. C's `argc` and `argv` shape could not be indexed in Landin without turning a pointer into a slice, which Landin does not do ([0500]). **The C library.** A Linux executable needs no C library. It starts at `platform/linux`'s `_landin_start`, which calls `main` with the process's arguments; `--link=libc` links the C runtime instead. Darwin and FreeBSD always link their C library. **The argument root.** A program that imports `hosted/system`, directly or through `hosted/blocking`, imports `platform/posix` with it. Its entry then first calls this C-callable function with the real values, before the body of `main` begins, so the environment is kept beside the arguments and lent the same way: ```text void _landin_host_initialize_arguments(int argc, char **argv, char **envp); ``` When C owns `main` and calls exported Landin functions, it calls that function itself, with its own `envp` or C's `environ`: - Call it before `blocking.new()` acquires an argument capability, and before starting any thread that may acquire one. File, stream and heap work needs no argument root, so linking `core/io` alone does not require the call. - The first call with a nonnegative count and a non-null table sets the one root; a null environment is an empty one. Repeating exactly the same three values is harmless. Using the argument services before the call, or calling with different values, traps. No ordinary export or callback initializes or resets the root. - Nothing is copied. The C owner keeps the tables and the strings they name readable as long as any world, view or callback derived from them can use them. - The arguments start at `argv[1]`, so a C program run with only its own name gives Landin no arguments. **Freestanding.** There is no `main`. The compiler request names the entry: an infallible ordinary `() -> none` or `() -> noreturn` function, or a naked `() -> none` one, in the entry module ([1630] shows the request). The compiler's reset initializes RAM before calling it. Returning from it, or a failed check, traps, since there is no hosted exit to go to. General build and package orchestration are outside the firmware path. **An image loaded into RAM.** For a debugger-loaded SRAM image, select `--firmware-layout=ram`. The compiler derives RAM placement from the same device description, retains BSS clearing and skips copies of data already in place. The board tool establishes the device state before entry. The default `boot` layout keeps the image its boot ROM needs; a RAM run does not test that boot path. Exact rules: spec [1975] for hosted programs, spec [1990] for firmware. ### [1660] Where capabilities come from The entry point is the usual place to make the program's roots — the host, an allocator, a diagnostics log — and pass them down as ordinary arguments. The language does not reserve that to the entry point: any function can call the constructors ([1680]). What a root imports: - A hosted root imports `hosted/blocking`, whose reads, writes, network calls and sleeps block the thread until they are done. - A program that serves several things at once imports `hosted/events` instead, whose waits let other fibres run ([1675]). - A program that never reads, writes or sleeps may use `system.new()` alone; it is not a world, since it cannot read or write. - A caller-backed root needs only `core/io`. `hosted/blocking` and `hosted/events` are both built over `hosted/system`, which keeps everything that does not wait: the arguments and environment, opening and closing files, directories, running programs, entropy and the wall clock. This is the essential flow of `examples/derived_hosted`, a complete log filter. Its `main` is one line, `code = app.entry()`, and the work starts in `entry`, a public function of the program's own `app` module. That module imports `hosted/blocking`, `hosted/heap`, `core/region`, `core/diag` and `core/io`, and `run_logged` is the application's function that does the work: ```landin public entry: () -> (code: i32) = host := blocking.new() world: any io.world = any(addr host) heap := heap.new() mut ledger: region.growing_space = zeroed program := region.over(ledger, heap) defer region.release(ledger, heap) mut logger := diag.stream(world, world.err()) log: any diag.log = any(addr logger) kept: usize = run_logged(program, world, usize(4096), log) else (problem) _ = problem code = 1 return end _ = kept code = if log.failed() then 1 else 0 end if end entry ``` **Roots are handles.** Each root is a small value, copied and passed by value, that refers to its state. - `blocking.new()` and `heap.new()` borrow nothing, because what they refer to belongs to the process: the argument root, the descriptors, the last errno and the heap. `blocking.new()` acquires the real argument table; it does not create or copy it ([1650]). - A caller-owned provider is made from state the caller declares, as the region is made from `ledger`. The handle cannot outlive that state, and the state cannot be released while the handle is still used. - An erased capability is built from the address of a handle binding, and its dispatch copies the handle from there. So `world` and `host` itself can be used side by side, and nothing is locked. **Handing it something else.** Because the code below the root only sees what it is handed, you can hand it something else. A test gives the same `run_logged` an in-memory world from `core/io`'s `io.memory_over`, which takes caller-owned files, arguments and output storage and makes no host call, and the run cannot tell. That works because I/O is a concept, not a type, so another provider can satisfy it. It travels as `any` rather than as a type parameter: an indirect call costs next to nothing beside the system call behind it. An allocator sits in hot loops, so it is passed as a type parameter instead. The machinery is the same, chosen case by case ([1690]). **Four concepts.** I/O is four concepts, because a provider should supply only what it has ([1260]): | concept | entries | | --- | --- | | `io.writer` | `write`, `write_some` | | `io.reader` | `read` | | `io.files` | open, close, `same_file` | | `io.process` | the three standard streams, the argument table | `core/io` has more concepts beside these four, each separate and not part of the world: `directories`, `environment`, `programs`, `file_system`, `terminals` and `entropy`. `io.world` composes the four for a root that has everything, and `world.write` on an erased world reaches the writer's entry. A UART implements `writer` and nothing else. A diagnostics log asks for `any io.writer`, and `entry` hands it the world: an `any io.world` converts to an `any` of each concept it is built on, keeping the same handle ([1370]). An `any io.writer` does not convert back, since a writer need not be a world. **Arguments and paths.** Both providers lend each argument and path as a `text.os_string`: the bytes the system gave, unconverted and uncopied, so an argument passed on as a path reaches the system unchanged, whether or not it is UTF-8. Neither provider's arguments include `argv[0]`. The library reference describes the system providers (`hosted/system`, `hosted/blocking` and `hosted/events`), the memory provider and host strings (`core/io`, `core/text`). The exact provider contracts — errno capture, whole and partial writes, retries, `same_file` — are in spec [1975]. ### [1670] When a check fails When a check fails — an index out of range, an overflow, a bad conversion, an `unreachable`, a fibre's stack run out ([1675]) — the program calls a fixed handler that never returns. With none of your own, a hosted program writes one line, `FILE:LINE:COLUMN: trap: KIND`, to standard error and stops; firmware just stops. To replace the default, declare a public `panic_handler` of exactly this shape in the entry module: ```landin import core/panic public panic_handler: (kind: panic.panic_kind, site: u32) -> noreturn = loop do end loop end panic_handler ``` It gets two scalars and no strings: - `kind` is one of `core/panic`'s `out_of_range`, `overflow`, `bad_conversion`, `unreachable` and `stack_exhausted`. - `site` is a plain `u32`, not [1040]'s `site` struct: a number the compiler gives the failing operation and its check family. File and line live in an optional table outside the target, so a small firmware image carries no file names. `refine compile --panic-map` writes that table. `refine site PROGRAM SITE` resolves a site against the build that made it, and only that build. Fine print: - The handler must have exactly this infallible form and atom domain. A linker symbol of the same spelling does not replace it. - A failed check does not unwind: the failed computation's `defer` and cleanup do not run. - Entering the handler a second time traps, including a check that fails inside it. - Caller coordinates are a separate value ([1040]). - Hardware faults and naked assembly keep their machine obligations. Exact rules: spec [1960]. ### [1675] Two things in flight: fibres Concurrency is a capability, like an allocator or the host ([1660], [1680]). There is no `async`, no second calling convention and no coloured function type. A function that wants two things in flight asks for something that runs them, and whether they really overlap is that provider's answer, not the function's. Each one runs on a stack of its own, a fibre. **A task** is an ordinary function. It takes its state `inout` and fails with `core/failure`'s set, and nothing in it knows it runs on a fibre: ```landin answers: type = struct order: [2]u8 count: usize end answers asking: type = struct clock: any time.clock wait: u64 tag: u8 heard: ptr mut answers end asking ask: (inout self: asking) -> none ! failure.reason = if self.wait > 0 then self.clock.sleep(time.milliseconds(self.wait)) end if self.heard.val.order[self.heard.val.count] = self.tag self.heard.val.count += 1 end ask ``` **A group.** A function starts tasks as a group, over storage it lends, and waits for them before it goes on, so whatever they borrow from it outlives them: ```landin ask_both: (runs: any fibre.scheduler, clock: any time.clock, inout heard: answers) -> none ! failure.reason = mut stacks: [2 * 8192]u8 = zeroed mut asks := try fibre.group_over(runs, stacks, 2) defer fibre.join(asks) else none a: asking = (clock: clock, wait: 20, tag: u8('a'), heard: addr heard) try fibre.admit(asks, ask, a) b: asking = (clock: clock, wait: 0, tag: u8('b'), heard: addr heard) try fibre.admit(asks, ask, b) try fibre.join(asks) end ask_both ``` - `group_over` cuts the backing into two equal stacks. Nothing is allocated: the stacks are the caller's bytes, and the group comes `from` the provider and the backing ([0790]). - `admit` waits for a free stack, copies the state onto it as a call passes an argument, and starts a fibre that calls `ask` with the copy. One group can hold tasks with different state types. - `join` waits until every task has ended, then fails with the first failure any of them had. Nothing cancels a fibre, so the others run to their own ends first. - A group must be joined before its backing goes. The `defer` does that on every way out, as it releases a region ([1660]); the compiler does not check that you wrote it. - The state is kept in the group until its task ends, so `admit` takes it `escaping into` the group ([0780]). `a` may point at `heard`, a parameter of the function that made the group; a local declared after the group is refused. **Providers.** Two concepts say what a provider is: - A `fibre.scheduler` may run each task to its end inside `admit`, before returning. - A `fibre.turns` is a scheduler with `yield`, and promises more: a fibre that yields lets every other unfinished fibre of its provider run before it goes on. The blocking host and `fibre.whole` are schedulers. Over either of them, `a` sleeps its 20 milliseconds and is answered first. `stacks.round`, a round of fixed turns from `core/fibre/stacks`, provides `turns`. Give it a clock whose sleep takes a turn for each millisecond, and `b` is answered while `a` waits: ```landin turning_sleep: (self: turning, span: time.duration) -> none = deadline: u64 = self.reading.val + u64(span) while self.reading.val < deadline do self.runs.yield() self.reading.val += u64(time.milliseconds(1)) end while end turning_sleep ``` One `ask_both`, three providers, and the answers are `ab`, `ab` and `ba`. So a program written against `scheduler` must be right when every task runs to its end as it is admitted. A program that needs turns says so: `fibre.turns_over` takes an `any fibre.turns`, and handing it the host or `whole` is refused where the group is made, not when a task waits for ever. **Choosing a provider on a hosted system.** The choice is made where the roots are minted ([1660]), and the functions below never learn it: | provider | a call that waits | groups | signals | | --- | --- | --- | --- | | `hosted/blocking`, `blocking.new()` | blocks the thread | `scheduler`: each task to its end | none: SIGTERM ends the process | | `hosted/events`, `events.over(state, fibres)` | lets the other fibres run while epoll or kqueue waits | `turns` | `core/io/signal`'s `signals` | `events.over` takes a space the caller declares and a round's table, one entry more than the fibres unfinished at once. A signal is an event a fibre waits for with `next_signal`, so only a provider of turns gives one: over the blocking host a fibre waiting for SIGTERM would hold the program before it served anything. **Fibres are cooperative.** A fibre gives the core away only inside a call to its provider, a `yield` or a call that waits, and nothing preempts it. The fibres of one provider are one execution context: between two such calls no other fibre of it runs, so a module counter or the last error a call left is not raced for. A switch is a full compiler memory boundary, and a fibre never moves to another thread. **A fibre's stack does not grow.** In a program that prepares a stack, a function compares its frame with the current stack's limit before it reserves the frame; the few that skip the check, small ones that call nothing, fit in a margin kept for them. Past the limit, the function traps `stack_exhausted` at its own declaration, before it has written below the stack ([1670]): ```text main.ldn:15:1: trap: stack_exhausted ``` - The limit stands a margin above the stack's lowest byte, room for the handler to run in: 640 bytes on x86-64 and arm64, 768 on RV64, 384 on Cortex-M0. - A program that prepares no stack has no check, and its code is what it would be without fibres. - How deep a task goes depends on the target: `ask` takes up to 4.4 KiB of its stack on RV64 and less on the others, which is why its stacks are 8 KiB. - `refine compile --stack-report=PATH` writes each function's frame and the deepest stack its calls can reach, and names the `any` calls, recursion and foreign calls that leave that open. Size a stack from its task's row and the margin. - A backing too small for its stacks fails `mem.out_of_memory`, where the group is made or when a task is admitted. **On one core** nothing runs at once, so there fibres are for structure: one takes the next request while another answers this one. A single-core device answers requests one at a time, in the order they arrived, and says `busy` when its queue is full; two answers are never in flight together. On Cortex-M0 a fibre runs on the process stack and interrupt handlers on the main one, so a fibre's backing pays for one exception frame, 36 bytes, and the handlers' own frames are the main stack's. A handler never switches: it records what happened, and the provider looks before it waits. **Writing a provider.** An application makes a group, and at most a provider, as the round above. `core/fibre/stacks` also holds the switch, `prepare` and `switch` over records a provider keeps, for whoever writes a provider of their own, built on two `compiler` builtins. - A program over `whole` or the blocking host imports no switch and runs on every target. - The switch runs on every target with a native backend. - A debugger's backtrace through a switch shows `landin.stack_switch`, and a fibre's frames end at `landin.stack_start`. The library reference describes `core/fibre` and `core/fibre/stacks`. Exact rules: spec [1995]. ## THE PRINCIPLES BEHIND THE DECISIONS A few rules explain most of Landin's choices. When something in the tour surprises you, one of these is usually why. ### [1680] Pass the capability, don't track the effect Landin has no effect system. A function that does I/O, allocates or reads the clock takes the thing that does it as a parameter: an allocator, an `io` writer, a peripheral handle, a random source. A caller can then hand it an in-memory world or a bounded allocator. The parameter list says what a caller supplies, not everything the call can reach: - Any hosted function may call the public host and heap constructors itself. - A driver may make a pointer from an address [0460]. Creating the roots in `main` [1660] is a convention the compiler does not check. If you need to know that a call tree does no host I/O, read its calls and imports. Exact rules: spec [1975]. ### [1690] One mechanism, read two ways Generic code and `any` share one foundation: evidence that a type satisfies a concept. Static generics and runtime dispatch are two readings of one feature, not two features ([1310], [1370]): - When the compiler knows the concrete evidence, it may specialize the call. - Otherwise the call goes through a table, and an `any C` value carries that table with it. ### [1700] Atoms are the same idea wherever they appear An atom is identity without payload. Enumerations, error sets, variant tags, register encodings and panic kinds are all uses of atoms, not separate categories. There is no `enum` in the language because there is nothing left for it to be. ### [1710] How a new feature earns its place When a program cannot be written cleanly, ask in this order: | ask, in order | then | | --- | --- | | can an existing mechanism express it? | a library | | can the compiler work it out itself? | no syntax | | must the programmer say it, and does saying it generalise or remove another mechanism? | a candidate | | does it only solve this one case? | not yet | A new mechanism should let two old ones leave the building. ### [1720] What Landin promises, plainly Landin makes local checks: origins and escape, consumption [0910], reference permission [0430], bounds, conversions and arithmetic. It is not a memory-safe language and not a resource-safe one. What the checks do not cover: - Pointer-to-integer conversion and the C boundary leave the checked model altogether [0470]. - A copy taken before a `sink` is not refused [0910]. - Distinct pointer or computed-index paths may alias across `inout` [0900]. - Two arenas look the same to the compiler [0860]. That is a smaller claim than "safe" and a larger one than C's: deliberately unsafe, with static help worth having. `spec.md`'s guarantee register classifies every observable failure boundary the compiler implements, and each new operation joins it. Checks are on by default. `unchecked` [1120] removes only the checks that entry lists, and only in the region where it is written. It tells the optimizer nothing: it emits fewer checks and gives no later pass a fact to assume. Optimization adds no undefined behavior, no-alias, overflow or floating-point assumption because of it, and keeps scalar results and the order of side effects and traps. ### [1730] Check once, then carry the proof A successful check can produce a value that stands for what was checked. A buffer that passed the alignment test becomes a `dma_buffer`, and the DMA interface asks for nothing else. Distinct types and error sets are enough for this; it needs no feature of its own, only the habit. The proof is the checking function's result. A guard on an ordinary integer proves nothing to the next function: the integer becomes a `percent` when `to_percent` returns it ([0660]), as the buffer becomes a `dma_buffer`. Write the conversion to the distinct type in that one function and nowhere else. ## WHAT LANDIN DELIBERATELY DOES NOT HAVE - no classes, inheritance, methods or runtime type information - no exceptions, no stack unwinding, no catchable panics - no garbage collection and no reference counting - no destructors - no closures that capture - no implicit conversions - no null - no positional tuples: anonymous records with named fields exist - no function name overloading and no multiple dispatch - no user-defined operators and no macros - no compile-time execution - no separate interface files - no header parsing inside the compiler (`refine bindings` asks Clang what a header declares) ## WHAT IS STILL OPEN Open work is listed in [ROADMAP.md](ROADMAP.md), not here. That includes what this tour leaves parked: structure-of-arrays [0620], affine values [0910] and restricting where capability roots are created [1680]. `refine` implements the whole of this pre-v1 language, and [the README](README.md#current-compiler-capabilities) says what it does today. Production status, release versioning, package acquisition and self-hosting are not part of the current plan. Version 0.2.11 — what each version changed is in [the handoff](handoff.md#versions). Warnings are the compiler's observations about legal source, never extra language rules. You can select, suppress or deny them by code. A denied warning fails that compilation, and the program stays legal Landin all the same. The compiler never warns about shadowing; it does warn about a declaration that takes a predeclared type's name, such as a local named `u8`, because no type written where that name reaches can then mean the type. ### [0620] Storing a collection field by field (deferred) DEFERRED: not in Landin yet; it is planned (Language evolution, in [the roadmap](ROADMAP.md)). A collection could be stored transposed: one array per field instead of one array of structs, so that one field of every element is a contiguous slice. It would be written `soa [4096]entity`. The feature touches aliasing, generics, slicing, `addr`, layout, debug information and the optimiser all at once, and no program has needed it yet. Until one does, generate the arrays with a program that writes the source ([1540]). ## WHAT WAS TRIED AND DROPPED This appendix is design history. You do not need it to learn or use Landin; it is here for anyone about to propose one of these ideas again. Its examples keep the spelling of their time, so some of them are not Landin as it is now. The revision log this replaces recorded every change across a long sequence of versions. Most of it was arrival. What is worth carrying is the other kind of entry: the thing that was designed, sometimes built, and then taken out again — because a reader who does not know that will propose it back, and because a design is partly defined by what it refused. - an ambient environment, carried in a register, holding the allocator and the diagnostics and the Io — Odin's context. Designed in full, then removed. Once the argument was that every property it needed made it visible anyway, the only thing left was its implicit flow, and that was the thing worth losing. It became an ordinary parameter and the ABI lost a reserved register [1680]. - compile-time execution, refused twice. It would have given generics, macros and configuration from one mechanism, and it costs an interpreter inside the compiler. The accepted price is that generated tables and vendor bindings come from generator programs [1540]. - witness tables as the only story, then monomorphisation as the only story: both refused. The table is the foundation and specialising is an optimisation weighed per instantiation [1310]. - cost annotations on a conformance, and the concepts that went with them. Removed entirely: how finely a concept distinguishes what an operation costs is a library's business, and no language guarantee should rest on how clever an optimiser happens to be [1270]. - loops with a value, and a loop form for steps that fail. `break with value` made a loop an expression, a `complete` block ran when the loop ran out, and `try for` walked a source whose steps could fail. All three were removed. Only the fixtures that pinned them used them; a mutable local and a plain `break`, or a function that returns, says the same, and so does a `while` over tried steps [1170] [1190] [1150]. - pointer unions of several atoms. A union of a pointer and two or more atoms kept a code cell beside the pointer, and was removed: every union in the library held one atom, and the second cell cost every target's IR, calls and widening. A one-atom union beside an error set, or a struct of a state and a pointer, says the same [0480]. - a layout that reordered fields. `layout(optimal)` sorted a struct's fields by alignment when that made it smaller, and was removed: no library struct asked for it, and a reader had to sort the fields in their head to know where one sat. Fields written largest alignment first give the same struct [0750]. - assembly's positional value. `assembler.block(text, value)` passed one `u32` through Cortex-M0's r0, and was removed once every target had named operands; `inout value: u32 at r0 = value` says it [1630]. - a concept for ranges. Integer range traversal now uses bounds in a `for` header, and left-exclusive forms went with the concept [0360]. - a second type with the shape of a fixed array and different operator rules. Fixed arrays are the vector type [0590]. - transposed collections, designed and deferred: they touch aliasing, generics, slicing, addr, layout, debug information and the optimiser at once, and no program has yet needed one [0620]. - weak conformances, built and removed. Libraries would declare weakly and applications override strongly, which worked — and meant an application could quietly change the behaviour of generic code inside a library. A collision is simply an error [1280]. - labels on if and match, removed; they earn their place on loops and bare blocks only [1180]. - errdefer, refused, and then arrived at from the other side. A cancellable defer was tried first and dropped, because the cancel always sits where the block succeeds and is hand-made bookkeeping for a question the exit already answers. defer with an argument was dropped because it reads as a call. What went in is undo, its own word, because to defer is to do it later and this may never be done at all [1110]. - read-only reference types spelled as a second form of every reference — considered twice and refused both times, then arrived at anyway from the other end. What was refused was deep const with an implicit widening; what went in is permission in the type with one stated relaxation, and it removed two mechanisms rather than adding one [0430]. - permission derived from where a reference came from, which lasted one version. It rescued the register case and could not express the commonest signature in a driver, so it was replaced by permission in the type [0430]. - inferred derivation for the from clause, refused with a counterexample rather than an argument: mechanically an allocator's result does come out of the allocator, so inference forbids a second live allocation [0790]. - braces, which were never a decision. They crept into two register examples and a set literal and were taken out again; the language has none [0730]. - a keyword for the compile-time assertion. The collision with the ordinary assertion was resolved by subtraction: it is compiler.assert now, a builtin call like the rest, and the language has one keyword fewer [1510]. - sets as a kind of their own, with a literal, three operators and a membership operator, all of which were designed and then not needed: set(X) generates a packed struct of bool, so membership is a field read [0730]. - affine values, which cannot be copied. Not refused — parked, with the condition that would bring them in, and with sink honestly described in the meantime as a use-after-consume check on one place rather than as ownership [0910]. - async and await, and the stackless coroutines under them, refused before either was built. Concurrency is not a property of a function here; it is a capability the caller hands down, so the same code blocks or does not depending on the Io it was given [1660]. One implementation of that Io ships first and it blocks, which is a scheduler not yet written rather than a limit in the language. Stackless is the refusal proper: cutting a function into a state machine is a compiler project of its own, and it colours every function type that reaches one — the same objection that removed the ambient environment above [1680]. Stackful fibres are the route to take instead, since taken [1675], and the design already pays for them: the frame pointer is always present, the callee-saved discipline is explicit, and nothing rides in a reserved register. - a volatile pointer type, a generated register wrapper carrying read, write and reset modes, and a `set(X)` type former, all sketched before any driver ran. The complete driver needed none of them: an operation says a device access happens, the modes are its arguments, and the generator writes the per-register functions and the named bool fields. A qualifier would have been a second permission on every reference [0740] [0850]. - per-field byte order and the weak, inline and noinline attributes, listed and never used. A big-endian field makes every access a conversion and its address unreadable through an ordinary pointer; inlining is the optimizer's business; one definition per name leaves weak nothing to do [0750] [0760]. - vector intrinsics beside element-wise array operators. The table listed both and only one was ever needed: fixed arrays are the vector type [0590] [1560]. ======================================================================== spec.md ======================================================================== # The Landin specification > **You probably do not want to read this.** It is the normative reference: > grammar, rules and recorded decisions, written to settle questions > exactly, not to teach. Nobody reads it from the top. To learn Landin, > read [the tour](tour.md); to write a program, > copy one from [the examples](examples.md); if you know C, start with > [Landin for C programmers](docs/from-c.md); for the library's calls, see > [the library reference](docs/library.md). > > Come here with a number. The tour ends many entries with > "Exact rules: spec [NNNN]", and a compiler message names the paragraph it > enforces; follow that number to the one paragraph you need. This is the normative document. `tour.md` explains the language and this says what it is; where the two could be read differently, this one decides. It is deliberately partial and it grows one slice at a time, so it says what is true today rather than what is intended. Three things are in here and the difference matters. **The grammar of the enabled kernel**, [1740] to [1830], covers the constructs the compiler enables today and nothing else, so that what a program may say and what the compiler will accept are the same sentence. A construct `tour.md` describes and this grammar omits is not enabled yet, and the compiler says so by [1830] rather than guessing. **The rules the tour left unsaid**, [1840] to [2000], are not about the kernel and they will not be deleted as it grows: that a comparison yields a bool, that an immutable binding may not be written, that a name must be assigned before it is read. The tour teaches by example and a tutorial omits what a reader supplies for themselves, so each of these was found by an implementation needing a rule and finding none. Each cites the sentence it derives from. **The decisions this document took** are the register after them. A rule in either part above is a transcription of something the tour already decided or a decision taken because the tour said nothing, and a reader cannot tell the two apart by reading one; the decisions are named in the register, each with the alternative it was chosen over and the fixture that pins it. All three are ordered by subject, and the numbers are not. An id is a stable citation anchor and never moves, so [1950] sits beside [1890] because both say what an operator takes, and D1 sits beside D233 because both say what a declaration introduces. What is read first and what was found first stopped being the same thing. ## THE GRAMMAR OF THE ENABLED KERNEL The notation is ordinary: a name in lower case is a rule, a quoted word is itself, '?' is optional, '*' is none or more, '+' is one or more, '...' between two quoted bytes is every byte from one to the other, 'any byte' is exactly that, and parentheses group. 'any Unicode scalar' denotes the shortest-form UTF-8 encoding of one scalar value, subject to its stated exclusions. Nothing here is a parser generator's input. The parser is hand written, and this is the agreement it is written against. The rules come in two layers, and the difference matters. The lexical layer reads bytes. identifier, keyword and literal each produce one token; space, line_end and comment produce no token at all and are discarded where they are found; the rest of that layer spells out part of one of those and produces nothing of its own. Every other rule reads the tokens that remain, and a quoted word or sign in one of them stands for the single token spelled that way. A quoted word is not thereby reserved: when [1760]'s keyword rule omits it, the token is an identifier whose spelling the enclosing production recognises. Thus 'of', 'lenof', 'offsetof', 'variant', 'caller', 'range', 'arena', 'concept', 'is', 'as', 'option', 'compiler', 'assembler', 'linker', 'c', 'layout', 'packed', 'at', 'u8', 'u16', 'u32', 'u64', 'link', 'symbol', 'align', 'section', 'region', 'keep', 'thread', 'boot_stage', 'vector', 'interrupt', 'naked', 'noreturn', 'distinct', 'out', 'into', 'held' and 'through' remain identifier tokens everywhere their contextual productions do not meet them. D225 reserves control words in every position, including ordinary name positions. The `packed_unsigned` production names contextual representation widths; it does not expand the ordinary scalar family. D202 separately reserves the three tool names as declaration/import bindings; that semantic reservation does not turn their tokens into keywords. A token is as long as it can be, comments excepted, whose opener decides [1780]: 'inc' followed by 'x' with nothing between them is the one name 'incx', which is why [1750] says what separates two tokens. ### [1740] A source file is an import prelude and declarations in any order A source file is a possibly empty import prelude followed by declarations in any order. All reached source files together are the program. Declaration order does not affect name lookup inside a module [0130]: names are collected as a set, and a name may be used above the line that introduces it. Active `linker.library` directives retain canonical source/declaration order for archive resolution (D202). 'public' rides on a declaration and not on a statement [0090]: what a module exports is decided where the module is written, never inside a body. ```landin-grammar program ::= import_declaration* declaration* import_declaration ::= "import" import_path ("as" identifier)? import_path ::= identifier ("/" identifier)* declaration ::= "public"? (atom_declaration | binding | function | external_function | machine_function | linked_binding | type_declaration | concept_declaration) | conformance_declaration | fixed_conditional | option_declaration | tool_directive option_declaration ::= "option" identifier ":" type "=" expression tool_directive ::= tool_namespace "." identifier "(" (expression ("," expression)*)? ")" tool_namespace ::= "compiler" | "assembler" | "linker" fixed_conditional ::= "fixed" "if" expression "then" declaration* ("elsif" expression "then" declaration*)* ("else" declaration*)? "end" "if" atom_declaration ::= identifier ":" "atom" identifiers ::= identifier ("," identifier)* ``` ### [1750] A source file is bytes A source file is bytes, a line ends three ways, and space separates tokens. A span in a diagnostic names a byte, and every later stage must be able to point at the same one, so the lexical rules are written over bytes. A line ends at LF, at CR followed by LF, or at a CR that is not followed by LF, and a file need not end with one at all. Text inside a literal or a comment may be any UTF-8 [0260]; nothing outside them may be. Space is a space byte, a tab, a line end or a comment [1780], and any run of them may sit between two tokens. Two tokens whose spellings would run together into one longer token need at least one, which is the whole of the rule: 'mut x' is two tokens and 'mutx' is one name. Otherwise space carries no meaning, and no rule below this layer mentions it. A line end therefore never terminates a statement: when the token after it can continue the expression or selection before it, it does. This is [1060]'s one-line rule read from the other direction. One `(` is read by where it stands: a `(` that begins a line, and whose matching `)` is followed by `:=`, begins [0990]'s destructuring binding rather than a call of the line above, because a call is no place and that reading could never derive. ```landin-grammar space ::= " " | "\t" | line_end | comment line_end ::= "\n" | "\r\n" | "\r" ``` ### [1760] Identifiers are lower case, and no identifier is a keyword Identifiers are lower case, and no identifier is a keyword. Every name in the language has this one shape: types, functions, bindings and fields alike, which is why the tour never needs to say which case a thing is written in. Two rules narrow it. A word the keyword rule spells is that keyword and never a name, so 'if' is not available as a binding; that one is the tokeniser's. The other is in the rule itself: a name that starts with '_' needs something after it, so the lone '_' is the discard of [1020] and nothing may be called it. The kernel reserves fifty words; the reserved set of the whole language is larger, and each word joins it when its construct is enabled in the language. Once reserved, it is a keyword in every program, even one that does not use that construct. Type names are not among them: u32 and bool are names the kernel predeclares, and a program may declare the same spelling [0120]; [1790] says which of the two a type position names. Control words cannot name bindings, types, functions, parameters, results, fields, atoms, import bindings or loop and block labels. In particular, `begin = 10` and `begin: i32 = 10` are invalid; `(begin)` is not an identifier escape. A longer spelling such as `begin_value` remains an ordinary identifier. D225 records the reservation and its compatibility consequence. ```landin-grammar identifier ::= lower (lower | digit | "_")* | "_" (lower | digit | "_")+ lower ::= "a" ... "z" digit ::= "0" ... "9" keyword ::= "addr" | "alignof" | "and" | "any" | "atom" | "begin" | "break" | "continue" | "dec" | "defer" | "do" | "else" | "elsif" | "end" | "escaping" | "extern" | "fail" | "false" | "fixed" | "for" | "from" | "if" | "import" | "in" | "inc" | "inout" | "loop" | "match" | "mut" | "none" | "not" | "or" | "ptr" | "public" | "return" | "sink" | "sizeof" | "struct" | "then" | "true" | "try" | "type" | "unchecked" | "undo" | "uninit" | "when" | "while" | "zeroed" ``` ### [1770] The kernel's literals include characters, floats and text The kernel's literals are integers, floats, characters, quoted text, the two booleans, and contextual `zeroed` and `uninit`. Integer literals are untyped and take the type of their context [0190], defaulting to i32 with none [0200]; the bases and the separator are [0220]'s. Each integer digit run starts and ends in a digit of its base; any internal run of underscores separates digits. A number ends where its spelling ends: a letter, digit or underscore directly after one belongs to it, so `1u64` or `1.5f32` is one malformed literal rather than a number and a name (D245). `uninit` is D152's restricted private inline-array field initializer; it reserves storage without assigning an item image. It has no stand-alone value type. `zeroed` has no type of its own: [0540] gives it the all-bits-zero image of a directly supplied initializer, assignment or field-label context. D27--D30 establish fixed-array contexts, D39--D43 scalar contexts, D49 and D57--D59 whole array-field and ordinary-struct contexts, D62 the depth-one indexed field place, D64--D67 labelled struct fields and static images, D75/D76 variant-bearing struct storage and case payloads, and D87 depth-one nested ordinary storage. It remains refused where no enabled construct supplies that context. D161 admits [0260]'s quoted literal when its direct context is a read-only `[]u8`; the unescaped source content is UTF-8 [1750], and [0270]'s byte escapes are decoded into that view. Raw text [0280] takes the same direct byte-slice context by D164, but interprets no escape and removes a line-leading closing delimiter's indentation. The maximal opening quote run chooses the delimiter width; only a later run can close it. Adjacent quotes therefore cannot encode an empty raw literal. Intervening line endings remain content under D164; empty text uses `""`. D181 adds `utf8`, `utf16` and `cstring` contexts and makes `utf8` the contextless default. A scalar escape is encoded as UTF-8 or UTF-16 for those views; a byte escape remains exclusive to `[]u8`. D162 admits [0210]'s decimal float with [0220]'s optional exponent. D166 adds [0230]'s hexadecimal fraction and required binary exponent. D167 admits [0240]'s type-qualified `infinity` and `nan` values for f32 and f64. D163 admits [0250]'s single-quoted character as exactly one Unicode scalar value of fixed type `u32`. A raw scalar is shortest-form UTF-8; [0270]'s simple escapes and `\u{...}` spell scalar values, while byte-only `\xNN` does not. ```landin-grammar literal ::= integer | float | character | text | raw | "true" | "false" | "zeroed" | "uninit" character ::= "'" (character_escape | unicode_scalar) "'" unicode_scalar ::= any Unicode scalar except apostrophe, backslash or line_end character_escape ::= "\\" ("n" | "r" | "t" | "e" | "\\" | "\"" | "'" | "u" "{" hex_digit+ "}") text ::= "\"" (text_escape | text_byte)* "\"" text_byte ::= any byte except quote, backslash or line_end text_escape ::= "\\" ("n" | "r" | "t" | "e" | "\\" | "\"" | "'" | "x" hex_digit hex_digit | "u" "{" hex_digit+ "}") raw ::= quote_run raw_content quote_run quote_run ::= "\"" "\"" "\"" "\""* raw_content ::= any byte+ integer ::= decimal | hex | octal | binary float ::= decimal_fraction decimal_exponent? | hex_fraction binary_exponent decimal_fraction ::= decimal_digits "." decimal_digits decimal_exponent ::= ("e" | "E") ("+" | "-")? decimal_digits hex_fraction ::= "0x" hex_digits "." hex_digits binary_exponent ::= ("p" | "P") ("+" | "-")? decimal_digits decimal_digits ::= digit ((digit | "_")* digit)? hex_digits ::= hex_digit ((hex_digit | "_")* hex_digit)? decimal ::= digit ((digit | "_")* digit)? hex ::= "0x" hex_digit ((hex_digit | "_")* hex_digit)? octal ::= "0o" octal_digit ((octal_digit | "_")* octal_digit)? binary ::= "0b" binary_digit ((binary_digit | "_")* binary_digit)? hex_digit ::= digit | "a" ... "f" | "A" ... "F" octal_digit ::= "0" ... "7" binary_digit ::= "0" | "1" ``` ### [1780] A comment ends a token, and its opener says which kind it is A comment ends a token, and its opener says which kind it is. The three forms are [0010], [0020] and [0030], and their openers share a prefix, so length cannot tell them apart: the longest opener decides. '--(' opens a block comment, '---' a doc comment and '--' a line comment, and the form so chosen decides where the comment ends rather than the rule that a token is as long as it can be. A line or doc comment ends at the line end. A block comment ends at its own ')--', so it may sit between two tokens on one line, and it nests: a ')--' closing an inner one does not close it, which is why commenting out a region that already contains one is not a trap. One never closed runs to the end of the file and is reported there. A comment is space [1750], so it may appear wherever a space may. ```landin-grammar comment ::= block_comment | doc_comment | line_comment block_comment ::= "--(" block_item* ")--" block_item ::= block_comment | any byte that begins neither "--(" nor ")--" doc_comment ::= "---" (any byte except line_end)* line_comment ::= "--" (any byte except line_end)* ``` ### [1790] A binding names one thing, and says how much it may change A binding names one thing, and says how much it may change. The full form, the inferred form and the mutable form are [0040], [0050] and [0060]; a binding with no value must be assigned before it is read [0080]. A binding, a field and an atom declaration name one thing each (D1656); [0100]'s shared form is left to parameter, named-return and payload lists, which write several names of one type. The kernel's types are the thirteen scalar names, atom sets, fixed arrays, pointers, slices, D145's `any C`, function types with their complete declared error sets, and what [1795] declares from them: aliases, named ordinary structs and D74's named variant-bearing structs. `mut` in a pointer or slice type records permission to write the pointee or viewed elements [0430] [0570]; it is independent of a binding's `mut` [0070]. Enabled runtime leaves are scalar, atom set, reference, function, fixed array or D147's erased pair; ordinary and variant-bearing structs compose those leaves recursively. A pointer is one target pointer-width carrier and a slice is its non-null base plus a `usize` length. Neither has an all-zero value [0540]. A function type is written with [1800]'s signature syntax. Its parameter and return names describe positions and declare nothing; only a function declaration opens [1840]'s signature scope. The other TYPES YOU DECLARE remain deferred. A type position holds a name either way. The kernel predeclares the thirteen scalar names and the three text-view names; the grammar spells these out because a program need not declare them itself. They are in no scope of [1840] and [1760] does not reserve them, so a program may declare the same spelling. A type position that spells one is looked up lexically like any name, and the nearest visible declaration of that spelling is what the position names, whatever it declares (D1260): a type declaration or a type formal gives the position its type, and a function, binding, parameter or any other declaration is no type, so the position is refused with L0338 as any name that is not a type is. The lookup does not continue outward past it, as [0140] has an inner name hide an outer one. Only when nothing visible declares the spelling does the position name the predeclared type. A call or value use of the spelling resolves the same way: a visible function named `u8` is what `u8(v)` calls, and `u8(v)` converts to the predeclared `u8` [0700] only when nothing visible declares `u8`. A function named `u8` therefore cannot write `u8` in its own signature, and no type position its name reaches can; a module that wants both gives the function another name. An array [0520] is a type position too, and its length is part of it. D136 folds the bound expression from integer literals, fixed formals, unary `-`, and the target-independent binary arithmetic `+`, `-`, `*`, `/` and `%`; D438 adds immutable module integers, D1321 compiler facts and `sizeof` of a scalar type, and D1340 `alignof` of a scalar type, each at the selected target's value. A type application's fixed actual folds the same expressions with the same refusals (D1663), so `buf(compiler.word_size)` is a type as `[compiler.word_size]u8` is; an argument written as a lone name is read as a type reference, and checking takes it as the fixed formal or module integer it names when that is what it names. The element is a type like any other. A parameterized alias or nominal struct is a type position through its fully applied positional application. D135 substitutes an alias during checking; D137 interns a struct application by its template and normalized actual tuple, then checks the substituted field shape. A binding, a parameter, a named return and a field declare a type, and there [0640]'s atom union may be written in place: `mode: read | write`. It is the same structural set a type declaration of that union names, so the two are one type and either may be written where the other is (D216). It includes D189's pointer union, `absent | ptr node`, and since `ptr` binds tighter than `|`, `ptr a | b` is that union of `ptr a` and `b`. A function type's parameters and returns are declared too. Everywhere else a type is written, as an array's or a slice's element, as a type argument, a `distinct` base or a conformance's target, a union needs that declaration's name, and the one refusal says so. `sizeof`, `alignof` and a labelled argument read `a | b` as [1820]'s alternation, and a union there is refused the same way. ```landin-grammar binding ::= "mut"? identifier ":" declared_type ("=" expression)? | "mut"? identifier ":=" expression declared_type ::= type | atom_union type ::= function_type | array_type | pointer_type | slice_type | any_type | type_application | scalar_name | packed_unsigned | text_name | declaration_reference function_type ::= signature | c_convention c_signature | machine_convention c_signature array_type ::= "[" expression "]" type pointer_type ::= "ptr" "mut"? type slice_type ::= "[" "]" "mut"? type any_type ::= "any" concept_reference type_application ::= declaration_reference "(" type_argument ("," type_argument)* ")" type_argument ::= type | expression scalar_name ::= "u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64" | "usize" | "isize" | "f32" | "f64" | "bool" text_name ::= "utf8" | "utf16" | "cstring" ``` ### [1795] Type aliases and declared identities A type declaration without a body or `distinct` names an existing type. [0120] declares a type like any other value and [0650] writes 'distinct' to make one that is not the type it was written from. D15 reads the second as deciding the first: without that word a declaration gives an existing type another name and the two are one type everywhere. A struct body [0670] has no existing type to alias and introduces the nominal type [0710]. It is written `struct`, a field a line, and `end` (D1657): a parenthesised field list is a parameter, result or payload list, never a type declaration, so `(` after `type =` begins a function type and nothing has to look past its `)` to tell the two apart. Without formals its identity is this declaration's empty-actual instance. With formals, D137 makes each fully applied normalized actual tuple a distinct instance of this declaration; an alias of either keeps that same identity. Every alias chain has to reach a scalar type, atom set, fixed array, function type or struct body. A chain that comes back to an alias in the chain reaches no type and is refused at that declaration. A declared type name is an ordinary declared name, so one declaration per name per scope [1850] and a name that names nothing is refused [1860] both hold for it unchanged. A predeclared name is in no scope, so declaring its spelling duplicates nothing; [1790] says which meaning a type position takes. There is no range subtype (D1661): `T range a .. b` after a type declaration's base type is refused as L0696, naming a `distinct` type over the base and a function that checks the range [0660]. `range` stays a word [1760] does not reserve. ```landin-grammar type_declaration ::= identifier ":" "type" ("=" (encoded_union | atom_union | distinct_body | type | struct_body) | type_formals "=" (encoded_union | atom_union | distinct_body | type | struct_body)) distinct_body ::= "distinct" type concept_declaration ::= identifier ":" "type" "=" concept_body concept_body ::= "concept" type_formals ("is" concept_reference ("," concept_reference)*)? concept_entry* "end" identifier? concept_entry ::= identifier ":" signature conformance_declaration ::= type_formals? conformance_target "is" concept_reference (conformance_entries conformance_field? | conformance_field) conformance_entries ::= "(" conformance_argument ("," conformance_argument)* ")" | "(" ")" conformance_field ::= "through" identifier conformance_target ::= array_type | pointer_type | slice_type | any_type | type_application | declaration_reference conformance_argument ::= identifier ":" argument_rhs concept_reference ::= declaration_reference declaration_reference ::= identifier | qualified_reference qualified_reference ::= identifier ("." identifier)+ type_formals ::= "(" type_formal ("," type_formal)* ")" type_formal ::= identifier ":" "type" constraint? | "fixed" identifier ":" type constraint ::= "is" concept_reference atom_union ::= union_member "|" union_member ("|" union_member)* union_member ::= declaration_reference | type_application | pointer_type encoded_union ::= packed_unsigned? "(" encoded_member ("|" encoded_member)* ")" encoded_member ::= declaration_reference "=" exclusion packed_unsigned ::= "u1" | "u2" | "u3" | "u4" | "u5" | "u6" | "u7" | "u8" | "u9" | "u10" | "u11" | "u12" | "u13" | "u14" | "u15" | "u16" | "u17" | "u18" | "u19" | "u20" | "u21" | "u22" | "u23" | "u24" | "u25" | "u26" | "u27" | "u28" | "u29" | "u30" | "u31" | "u32" | "u33" | "u34" | "u35" | "u36" | "u37" | "u38" | "u39" | "u40" | "u41" | "u42" | "u43" | "u44" | "u45" | "u46" | "u47" | "u48" | "u49" | "u50" | "u51" | "u52" | "u53" | "u54" | "u55" | "u56" | "u57" | "u58" | "u59" | "u60" | "u61" | "u62" | "u63" | "u64" struct_body ::= ("layout" "(" ("c" ("," "packed")? | "packed" ("," ("u8" | "u16" | "u32" | "u64"))?) ")")? "struct" member+ "end" identifier? member ::= field | variant_part field ::= identifier ":" declared_type ("at" expression (".." expression)?)? variant_part ::= identifier ":" "variant" variant_case ("|" variant_case)* "end" identifier variant_case ::= identifier (":" "(" payload_field ("," payload_field)* ")")? payload_field ::= identifiers ":" declared_type ``` ### [1800] A function is a value with a body, and its returns are named A function is a value with a body, and its returns are named. '=' opens the body and 'end' closes it [0870]; a body that is one expression still takes an end, and the expression fills the named return [0880]; every named return must be assigned before the function returns [0930]. The parameter conventions [0900], `escaping` [0780], `from` [0790], `caller` [1040] and generic parameters [1290] have their parser and resolution foundation on a declared routine. Its complete signature scope collects type/fixed formals, runtime parameters and named returns before resolving any type; runtime formals alone make the runtime signature. `escaping` precedes an explicitly written convention, and both precede the parameter name (D140). `escaping into p` names the parameter whose storage may keep this one (D445); `into` is a contextual word [1760] does not reserve, a target only when a second name follows it, so a parameter may still be called `into`. Its name is associated with a runtime parameter position as a `from` name is, and the parameter it names may stand earlier or later in the list (D455). A parameter without a convention is read-only, and `in` is never written (D1655). Each `from` name is retained in written order and associated with the correspondingly labelled runtime parameter position. A name written `held p` says the result is what `p` holds rather than a view of it (D1369); `held` is contextual in the same way, the word only when a second name follows it. For every returning edge that actually carries a tracked reference, the reference-origin pass checks its source set against exactly that ordered list; [0480]'s provably empty optional arm has no reference or origin to compare. Unknown, duplicate, missing and extra sources are rejected. A generic template has no standalone function value or IR item. D138's first executable increment deduces a direct type formal or exact `[n]t` shape from context-free runtime argument types, interns the concrete routine instance, and emits that instance rather than the template. An enabled nongeneric signature takes values including function values, hands one or more named values (or none) back, and optionally declares [0940]'s payload-free atom error set. A standalone `link(symbol: text)` may precede the name of a native function declaration, but does not change this signature or convention and does not make its body optional [1610]. A function type reuses the nongeneric `signature` production but has no body. Its labels are type description only and do not declare parameters or named returns. A function value names a declared function; there is no anonymous one (D1654). A body is one block. Its statements run in source order and an optional final expression fills the one named return or the complete anonymous aggregate of a multiple return list. A final `if` or `match` whose every answer is a call that does not return answers nothing and is a statement, whose arms assign the named returns (D431). One token past a leading name decides between a first statement and a direct expression: ':' opens a binding and an assignment operator opens an assignment; anything else means the body begins with its value. A function returning none has no expression form, because there is no return for one to fill. An unguarded `return` has no fallthrough edge, so it can end a statement-only block but cannot be read as the prefix of that block's final expression. This also keeps `return 1` the refused payload spelling [1810]. A guarded return may prefix a final expression because its untaken edge continues. ```landin-grammar function ::= (link_attributes "public"?)? identifier ":" declared_signature "=" body "end" identifier? external_function ::= (link_attributes "public"?)? c_convention link_symbol? identifier ":" c_declared_signature ("=" body "end" identifier?)? machine_function ::= (link_attributes "public"?)? machine_convention link_attributes? identifier ":" declared_signature "=" body "end" identifier? linked_binding ::= link_attributes "public"? binding c_convention ::= "extern" "(" "c" ")" machine_convention ::= "extern" "(" ("interrupt" | "naked") ")" link_symbol ::= "link" "(" "symbol" ":" text ")" link_attributes ::= "link" "(" link_attribute ("," link_attribute)* ")" link_attribute ::= ("symbol" | "section" | "region") ":" text | ("align" | "vector") ":" integer | "keep" | "thread" | "boot_stage" c_signature ::= "(" (parameters ("," "...")?)? ")" "->" returns errors? c_declared_signature ::= "(" (routine_formals ("," "...")?)? ")" "->" returns errors? signature ::= "(" parameters? ")" "->" returns errors? declared_signature ::= "(" routine_formals? ")" "->" returns errors? routine_formals ::= routine_formal ("," routine_formal)* routine_formal ::= parameter | type_formal errors ::= "!" (declaration_reference ("|" declaration_reference)* | "...") parameters ::= parameter ("," parameter)* parameter ::= "caller" identifiers ":" declared_type | ("escaping" ("into" identifier)?)? parameter_convention? identifiers ":" declared_type parameter_convention ::= "inout" | "sink" returns ::= "(" named_return ("," named_return)* ")" | "none" | "noreturn" named_return ::= identifiers ":" declared_type ("from" return_source ("," return_source)*)? return_source ::= "held"? identifier body ::= block block ::= statement* | value_statement* expression value_statement ::= binding | destructuring_binding | assignment | increment | discard | call | labeled_application | defer | undo | try | "return" "when" expression | "fail" expression "when" expression | break | continue | loop | while | for | if | match | bare_block | labeled_block destructuring_binding ::= "(" destructured_field ("," destructured_field)* ")" ":=" expression destructured_field ::= identifier (":" (identifier | "_"))? | "_" ``` ### [1810] Statements do one thing each, and only exits carry 'when' Statements do one thing each, and only exits carry 'when'. Assignment is a statement and never an expression [0390]; there is no '++', and 'inc' and 'dec' are statements too [0400]; discarding a result is written out [1020]; the one-line form of every construct is [1060]. 'when' rides on an exit and on nothing else, which is what keeps a conditional statement from having two spellings. `return` carries no value. A named return is assigned like any other place and `return` leaves [0930], which is why the kernel needs no second way to say what a function hands back. `fail` is the other early exit [0970]: it carries one payload-free atom on the declared channel and does not read the successful named return. A direct or selected call, with positional or named arguments, is a statement as well as an expression, because a function returning none has nothing to bind. That is the only call the position takes: one that hands a result back is refused there, recovered or not, because [1020] wants a result discarded on purpose rather than by omission, and `_ = call` is how it is written (D244). A labelled application in this position must resolve to a function call; the shared construction syntax still requires its ordinary value context and does not make constructed values standalone statements. A standalone `try call` explicitly propagates its failure and discards any successful result, whatever its shape. `defer` and `undo` each register one call when their statement is reached and evaluate the callee and arguments only on applicable exits from the lexical block [1100] [1110]. They are statements rather than expressions and so cannot supply a block's final value. A match is D77's exhaustive tag selection or [0640]'s exhaustive atom-set selection. A variant subject is one directly selected variant part and each case arm carries one statement or one expression; a bare `begin` block makes a multi-statement arm. D78 extends the arm with positional payload bindings. An `if`, a `match`, and a bare `begin` block retain their statement forms and also occupy expression positions under [1820]. Used as a statement, one takes no value from its branches, so a branch, an `elsif` or `else` arm, a `match` arm or the block itself, that ends with a value is refused, as a call standing alone that hands one back is: nothing would take the value, and [1020] drops none by omission. The refusal names the two routes, a branch written as a statement and, where the value followed a call's `else` that divided an `if` [1820], the recovery parenthesised or bound. A place is [1820]'s indexed selection, so a binding, a field of a struct, or an enabled array element is written and stepped exactly as the binding holding it is. What may be written is [1900]'s and not this rule's: a field is writable when the binding it belongs to is. D165 enables [0390]'s compound forms. Each reads the selected place, applies the corresponding [1820] binary operator to that value and the right-hand expression, then writes the result back. The place is evaluated once before the right-hand expression [0410], must already be assigned [1910], and needs the same write permission as `=` [1900]. The operator keeps its ordinary type, known-operand, trapping and wrapping rules. The kernel admits the statement forms of [1130], [1140], [1170], [1180], and [1190]. An unconditional loop tests nothing; a `while` condition is evaluated before every iteration and must be `bool`. `break` transfers to the point after its target loop and `continue` transfers to that loop's next condition test (or next unconditional iteration). Without a label they target the nearest loop; with one they target the nearest enclosing loop, or labelled bare block, carrying that ordinary name. A labelled loop or block closes with its label. A block is left only by `break`: `continue` naming one is refused (D234). A loop is a statement and gives no value, and a `break` carries none (D1651): a loop written where a value belongs, a `break with`, and a `complete` block are refused, each with the replacement named. Their optional `when` condition is evaluated once and must be `bool`; its false edge continues with the following statement. Both transfers leave every lexical block between the statement and the loop edge, so [1100]'s `defer` runs and [1110]'s `undo` does not. Every exit of a loop reaches the statement after it. After a loop, a name is definitely assigned when it is assigned on every edge that leaves the loop: a `while`'s false test, a `for`'s exhaustion, and every `break` (D430). D159 enables the integer-range form of `for`: both bounds are evaluated once, from left to right, and have one integer type. `a..>=" | "+%=" | "-%=" | "*%=" increment ::= ("inc" | "dec") place discard ::= "_" "=" expression defer ::= "defer" call undo ::= "undo" call return ::= "return" ("when" expression)? fail ::= "fail" expression ("when" expression)? break ::= "break" identifier? ("when" expression)? continue ::= "continue" identifier? ("when" expression)? loop ::= "loop" "do" block "end" "loop" | identifier ":" "loop" "do" block "end" identifier condition ::= expression | condition_declaration condition_declaration ::= "mut"? identifier ":=" expression | "mut"? identifier ":" declared_type "=" expression while ::= "while" condition "do" block "end" "while" | identifier ":" "while" condition "do" block "end" identifier for ::= "for" identifier ("," identifier)? "in" expression ((".." | "..<") expression)? "do" block "end" "for" | identifier ":" "for" identifier ("," identifier)? "in" expression ((".." | "..<") expression)? "do" block "end" identifier try ::= "try" (call | labeled_application) if ::= "if" condition "then" block ("elsif" condition "then" block)* ("else" block)? "end" "if" match ::= "match" expression match_arm+ "end" "match" match_arm ::= (match_label | "_") ("(" match_binding ("," match_binding)* ")")? ":" (statement | expression) | match_label ("," match_label)+ ":" (statement | expression) match_label ::= declaration_reference | "ptr" match_binding ::= ("inout" | "sink")? identifier unchecked ::= "unchecked" "begin" block "end" "unchecked" bare_block ::= "begin" block "end" labeled_block ::= identifier ":" "begin" block "end" identifier place ::= indexed ``` ### [1820] Precedence, tightest first, and comparison does not chain Precedence, tightest first, and comparison does not chain. The operators are the ones OPERATORS already decided: [0290] for arithmetic, [0300] for the wrapping forms, [0330] for the bitwise set, [0320] for shifts, [0350] for comparison and [0340] for the logical words. Every binary level below is left associative, which the repetition in each rule is what says. Comparison takes at most one operator, so 'a < b < c' is not a sentence in this grammar rather than a fold: a chain that read left to right would compare a bool with a number, and [0310] refuses that anyway. A selection is [0420]'s ordinary member-selection syntax. The enabled representation retains every selected name without deciding whether it denotes a struct field or [0430]'s `val` pointee; that classification belongs to later checking. It binds tighter than every operator because it is part of naming a thing rather than an operation on one, and it is left to right, so 'a.b.c' selects from what 'a.b' named. Module resolution uses that same retained selection for a qualified declaration reference. When its first name is this file's imported namespace, the first selected name is public module lookup and the namespace produces no runtime value. Otherwise the selection is the ordinary runtime form above. Later selections from a module binding are ordinary fields of the selected value. An index or slice selection [0570] binds the same way and for the same reason, and takes what a selection named: `a[i]`, `a.b[i]` and `a[lower..>") sum)* conjunction ::= shift ("&" shift)* exclusion ::= conjunction ("^" conjunction)* alternation ::= exclusion ("|" exclusion)* comparison ::= alternation (("==" | "<>" | "<" | "<=" | ">" | ">=") alternation)? logical_and ::= comparison ("and" comparison)* expression ::= logical_and ("or" logical_and)* ``` ### [1830] What is not enabled is refused, and named What is not enabled is refused, and named. A construct `tour.md` describes and this grammar omits is not a guess the compiler gets to make. Meeting one is a diagnostic that names the construct's paragraph and says what the refused form is, so a program written against the whole tour fails with a list rather than with a parse error. This grammar owns what is already true. The note says one of three things, and never names the work that decided it (D246). - A source-form boundary is a disallowed shape within an implemented construct, and the note says it is a recorded boundary; it must not claim that the complete construct remains unimplemented. For example, indexing requires a named place, inline structs require a named type declaration, and a labelled construction starts with a labelled field. D236's constrained compositions and the shapes D233 and D241 leave outside their constructs are of this kind. - A withdrawn form is one the language no longer has, and the note says it is withdrawn and names what replaces it. D212 withdraws [0820]'s formerly promised lexical `arena` block and builtin `arena` type, and both notes name the ordinary allocator replacement. `arena` is not a keyword: a declared type, parameter, local, call or label with that spelling remains ordinary. Only the statement shape `arena name do` and an otherwise-unresolved builtin type spelling receive the migration diagnostic. No compiler rule recognizes the module `core/mem`. D238's `volatile ptr` names its withdrawal and the explicit operations that replace it. - A transferred form is one a successor roadmap owns, and the note names the successor. D237's u128, i128 and f16 name their transfer to Language evolution. [1430]'s import alias is enabled; D201 states its binding and visibility rules. [1440]'s selected import is refused, naming the whole import (D1658). ## THE RULES THE TOUR LEFT UNSAID These are the rules an implementation needed and `tour.md` does not state. They are grouped by subject: names, scopes and what a doc comment is about, then the types and the context a literal takes its type from, then what an operator takes and what it refuses, then places, assignment and what may be discarded, then calls and the declared-error channel, then module values, and last the boundaries the compiler owns — the hosted entry, the C boundary, the firmware and machine directives, and the switch between stacks. ### [1840] The kernel's scopes, outermost first The kernel's scopes, outermost first. [0130] and [0140] are two sentences about scopes and this grammar has to say which scopes it has, because a rule about an inner scope means nothing until the inner ones are named. | scope | what it holds | | --- | --- | | program | every module reachable from the entry directory after [1420]'s ordered-root selection. This is the outer identity and the one whole-program conformance register; it is not a source namespace. | | configuration | D202's global options and implicit tool namespaces, used by the closed configuration fold before ordinary resolution. It has no runtime declarations or storage. | | module | every direct `.ldn` file in one directory [1410]. Its named declarations are shared by those files regardless of order, module-internal by default and public only when written so. Active `linker.library` directives retain source order (D202). | | file imports | the final segment of a plain import or the written alias in this file's prelude [1420]-[1450]. A namespace binding is not a declaration or value. This scope encloses the module scope for lookups performed from that file. | | type declaration | D135's complete ordered formal list. The scope encloses the declaring file's imports and is visible in every fixed formal's declared type, direct concept constraint and in the alias or struct body, regardless of formal order. It closes with that declaration: its names do not enter the module or another type declaration. A type declaration without formals opens no scope. | | concept declaration | D142's complete ordered type-formal list. It encloses the declaring file's imports and is visible in every direct constraint, parent name and entry signature. Entry parameter and result labels describe signature positions and declare nothing in this scope. | | conformance declaration | D142's optional complete type/fixed binder. It encloses the declaring file's imports and is visible in every binder constraint, the target type, every labelled input or function RHS and the routine a `through` names (D1363). The conformance itself declares no module name. | | signature | a declared routine's type/fixed formals, runtime parameters and named returns [1800]. Every binder is collected before any signature type or direct concept constraint is resolved, so its source order has no visibility meaning. Named returns are places the body assigns [0930]; all three binder kinds share one namespace, but type/fixed formals are compile-time-only and have no storage. A declared function's signature encloses its file-import scope. A written function type opens no scope and its labels declare nothing. | | body | what a function runs; one for each arm of an `if` and its `else`; one for each loop body; one for each `match` arm; one for every bare `begin` block; and one for a call-site recovery [1810] [1030]. A statement run plus its optional final expression is a block and a block is what scopes [1090], so a name declared in one is not visible in a sibling or after the block closes. D185's initialized condition binding shares the scope of the one `if`, `elsif`, or `while` body it guards; its initializer is resolved in the enclosing scope, and it is absent from later conditions, sibling arms, `else`, and following statements. Match payload bindings and a recovery error name live only in their block. | [1800]'s direct final expression opens no additional scope inside its function body, because an expression declares nothing. Order matters in a body; module declaration order does not affect lookup. [0130]'s set is a set of named declarations, so a module name may be used above the line that introduces it; [1800]'s block is a sequence, so a local is visible to the statements and final expression after it. Both its written type and initializer resolve before its name exists [0110] (D218), including names inside pointer, slice, array and applied-type syntax. Lookup proceeds through body and signature scopes, then this source file's imports, then its module. An import may therefore shadow a same-named module declaration for qualified lookup, and a parameter or local may shadow the import. A namespace import leaves an unqualified same-named module value visible; a selected declaration shadows the module declaration for ordinary unqualified lookup too. Imports do not enter sibling files and are not re-exported. Lookup ends at the module: [1790]'s predeclared type names are not a further scope but what a type position names when lookup finds no declaration (D1260). ### [1850] One scope gives one name to one thing One scope gives one name to one thing. Two declarations of one name in one scope leave nothing to choose between them: [0130] makes module name lookup independent of declaration order, so neither is first, and [0140] licenses shadowing between an inner scope and an outer one and not within one. So it is refused, and the report names both places. Shadowing is not this. An inner scope may shadow an outer name [0140] and nothing is said about it, because a rule that permits something does not also warn about it. The compiler's one observation about a name is D1342's warning at a declaration that takes a predeclared type's name: those types are in no scope, so such a declaration hides none of the program's names, only the language's own type from every type position it reaches [1790]. The file-import scope follows the same rule: two imports with one final segment, including a repeated identical import, are refused and both import sites are reported. ### [1860] A name that names nothing is refused A name that names nothing is refused. There is no implicit declaration in this language: a name that is not in scope is a misspelling and not a new binding [1250]. The report names the use, because the use is where the mistake is and the declaration that was meant is not there to point at. An imported namespace whose selected member exists but is not public is a different error: the use is refused as inaccessible and the private declaration is related evidence. A namespace used without selecting a member names no runtime or type value and is likewise refused. ### [2000] What a doc comment is about A doc comment [0030] is about the declaration that follows it, and the language gives it no other meaning: a program means the same with every doc comment removed. The doc comment of a declaration is the run of doc comment lines directly above the line it begins on, read top to bottom. Each line of the run holds nothing but blanks and one doc comment, and the run ends at the first line above it that holds anything else, a blank line among them, so a line comment or an empty line between a doc comment and a declaration keeps the doc comment for nothing. A doc comment on the same line as code, or below a declaration, is about nothing. A doc comment's text is what follows its `---`, without one blank after it if there is one. ```landin --- The larger of two counts. --- Equal counts give the first. larger: (a: u32, b: u32) -> (c: u32) = c = if a < b then b else a end if end larger --- About nothing: a blank line follows it. total: u32 = 0 ``` ### [1870] The kernel's types, and what each of them holds The kernel's types, and what each of them holds. [1790] gives the kernel scalar and text spellings and nothing that says what one of them holds, so nothing yet says whether a u8 may be given 300. [0150] puts the width in the name, [0160] takes usize and isize from the machine and [0180] gives bool its two values; written out, that is: | type | what it holds | | --- | --- | | `u8` `u16` `u32` `u64` | every unsigned value of that many bits | | `i8` `i16` `i32` `i64` | every signed one, two's complement | | `usize` `isize` | the same pair, at the target's pointer width [0160] | | `f32` `f64` | IEEE 754 binary32 and binary64 values, including signed zero, infinities and NaNs [0170] [0240] | | `bool` | false and true [0180] | | `ptr T`, `ptr mut T` | one non-null target address, with tracked origin unless constructed from an integer [0430] [0470] | | `[]T`, `[]mut T` | one non-null aligned base and a `usize` length [0570] [0580] | | `utf8` | a distinct immutable `[]u8` view of validated shortest-form UTF-8; its length counts bytes [0600] | | `utf16` | a distinct immutable `[]u16` view of valid UTF-16; its length counts code units [0600] | | `cstring` | a distinct immutable `ptr u8` view of NUL-terminated bytes with no length; a literal's bytes are validated UTF-8, a foreign boundary's promise only accessible backing through the first NUL [0600] | | an atom union | exactly the declaration identities in its flattened set [0630] [0640] | Two's complement is not a new decision. [0300]'s wrapping forms have to wrap somewhere and [0320]'s '>>' keeps a sign, and neither means anything without it. Each of the thirteen is its own type. usize is not u64 on a machine whose pointer is eight bytes wide, because if it were, [0310] would refuse a program on one target and accept it on another for a reason no paragraph here could state. [1510]'s 'sizeof usize == 8' asks what a machine does; it does not say two names are one type. D162 enables f32 and f64 without making either an integer or one another. u128 and i128 [0150] and f16 [0170] are not in this version: D237 transfers them to the Language evolution successor, and the checker refuses the three spellings by name. The packed widths are enabled only in D228's packed-field positions [0730]. They are representations within an image, not new ordinary scalar or ABI types: reading such a field gives the smallest enabled unsigned scalar that holds its width, so a `u1` field reads as a `u8` of 0 or 1 and is not a `bool` (D228). An atom declaration introduces one value and its singleton type. An atom union is structural: aliases are flattened, order and repeated members do not change identity, and assignment or argument passing may widen a singleton or smaller set into a set that contains it. No integer is an atom and no zero or default atom exists. With one atom, `atom | ptr T` uses zero for the atom and every nonzero pattern for the pointer, occupying one target pointer carrier [0480] (D189). A pointer union holds exactly one atom: a union that flattens to two or more atoms beside a pointer, written in place, through an alias or by applying a parameterized alias, is L0696 (D1659). [1795]'s `union_member` admits one written pointer type beside the atom name, and a second pointer member is L0338. The union is not a pointer. `.val`, `addr` of a `.val` reached through one, an integer conversion of one, `any` construction from one, a comparison with another union or a pointer, and an argument or result position wanting `ptr T` are each L0335, because each would read an atom case as an address; `ptr(n)` cannot produce one for the same reason, and `zeroed` does not name an atom case because no zero or default atom exists. A plain `ptr T` widens into a union whose pointer member it relaxes to, and its atom's singleton widens into it, in the direction this paragraph already gives atom sets; neither direction reverses (D189). A union may be compared for equality with its atom, on either side: `u == a` and `u <> a` test the atom case without exposing an address (D429). `match` [1210] is the way to recover the pointer: its cases are the union's atom name and the reserved word `ptr` with an optional read-only binding of the plain pointer type, an `inout` binding on that arm is L0333 [1220], a case named twice is L0311, and a case named by neither an arm nor `_` is L0312 exactly as for an atom set. The bound pointer carries the subject's own origin [0770] [0780], and an atom case carries none, so a union built from a frame address still refuses an escaping use of the bound pointer. An origin names a kind of storage, not a lifetime: "allocated" says a reference came from an allocator, and nothing about whether that allocator has since released or reset it [0770] [0860]. Two arenas are one origin, and a pointer stored in a field and read back carries the field's origin. The checks here are the local ones [0770] promises, and freeing storage under a live reference remains outside them. Fixed arrays hold their declaration-order elements [0520], and ordinary or variant-bearing structs hold the fields their nominal declaration gives them [0710] [0750]. A function type holds a target code address with the complete parameter and result signature [0870] [1000]. The signature, not the address, decides which values may be stored together and how a call is checked. ### [1880] Where a literal's type comes from, and what a context is Where a literal's type comes from, and what a context is. [0190] says an integer literal is untyped, takes the type of its context and is checked at that point, and [0200] says it is i32 with none. Neither says what a context is, and a checker cannot ask for one until they are listed. In the kernel these positions give a literal a type: - a binding's declared type [1790] - the type of the place an assignment writes [1810] - the type of the parameter an argument fills [1800], in a generic routine too when that type names no formal the call deduces (D419) - the named return's type, or the complete anonymous result aggregate for a multiple-return expression body [0880] [0990] - the result expected from an `if`, `match`, bare `begin`, or call-site `else` expression; that same complete context reaches every fallthrough answer - the element type of a contextual array literal or repetition - the field type of a contextual labelled struct literal - the complete pointer type of `ptr(integer)` and the complete slice type of `[]`; the address integer itself takes `usize` - the other operand's type, for a binary operator - the other endpoint's integer type, for a range traversal (D219) - a unary operator's own context, handed on [1820] - a branch's or while loop's condition and an exit's 'when', all of which want a bool [1050] [1070] [1140] [0970] and so give an integer literal a context it cannot take A call with two or more results has [0990]'s anonymous structural aggregate: its declaration-order field names and complete field types are its value shape. That shape supplies an inferred whole binding and every arm of a control value. And two give none: the inferred form [0050] and a discard [1020], where [0200]'s i32 is what is left for an integer and D162's f32 for a float. [0250]'s character literal is different: it already has type `u32`, so a surrounding context must agree and an inferred binding keeps `u32`. For [0260]'s text literal, those same direct positions may instead supply a complete text view. D161 and D164 admit quoted and raw literals as `[]u8`; D181 admits `utf8`, `utf16` and `cstring`, and with no supplied context either literal defaults to `utf8`. These identities remain distinct in a generic actual and in every reference-bearing signature or aggregate field. For [0210]'s float literal, the same positions supply f32 or f64. There is no implicit conversion from an integer literal or integer value; with no context the float defaults to f32. The decimal spelling rounds once to the contextual IEEE format. A finite spelling that would round to infinity is L0300 rather than silently becoming [0240]'s named special value. The named values `f32.infinity`, `f64.infinity`, `f32.nan` and `f64.nan` have the type written before the dot rather than taking one from context. D167 chooses one canonical quiet NaN pattern for each width; unary minus changes only its sign bit, as it does for infinity. With no surrounding context, the first written answer of a control expression supplies its scalar type, fixed-array element and extent, or nominal aggregate body; every other answer must have that same complete shape. An edge that returns without an answer is not a second answer and does not participate in inference. A context reaches inward through [1820]'s arithmetic, bitwise, shift and unary levels and stops at a comparison and at the logical words. What those give back is a bool [1890] and a bool says nothing about what was compared, so 'r: bool = 1 | 2 == 3' compares two i32 by [0200] and not two bools. Reference agreement includes the complete referred type and shallow permission. [0440] is the sole relaxation: `ptr mut T` satisfies `ptr T`, and `[]mut T` satisfies `[]T`; neither direction changes bits, and the reverse is refused. It relaxes a value that flows in: an `inout` place of reference type also flows back out, so it agrees exactly, as D243 records. Function signature agreement also includes parameter conventions, `escaping`, and each result's ordered `from` positions; omitted and explicit `in` have the same semantic convention. [1975] additionally includes C versus Landin convention and variadicness recursively, including function-valued fields and nested signature parts. A literal whose value the type does not hold is refused [0190], and the report names the literal. A unary minus over a literal is part of the value that check reads, which is what makes 'i8 = -128' the smallest i8 rather than 128 refused and then negated. Nothing else is folded: 'u8 = 200 + 100' is two literals a u8 holds and a sum it does not, and [0300] says that traps rather than that it is refused here. This literal-range rule does not suppress [1975]'s separate refusal of a known null pointer construction, whose closed expression is folded before testing its target-width value. ### [1890] What each operator takes and what it gives What each operator takes and what it gives. [1820] settled what binds; this settles what agrees. Every binary operator takes two operands of one type, because [0310] converts nothing. D209 additionally lifts the numeric arithmetic rows over equal-shape fixed arrays or an array and its exact scalar element type; that scalar is evaluated once and broadcast, not implicitly converted. | operator | takes, and gives back | | --- | --- | | `+` `-` `*` `/` | one integer or float type, and that type back [0290] | | `%`, and [0300]'s `+%` `-%` `*%` | one integer type, and that type back [0290] | | `&` `^` `\|`, and the unary `~` | one integer type, and that type back [0330]; or one distinct type whose base is an unsigned integer, and that distinct type back [0650]. That distinct type also admits `&=`, `^=` and `\|=`, reaching the assigned place once [0390] (D427) | | `<<` `>>` | an integer shifted by an integer of that same type, and that type back [0320]. The amount is not bounded by the width: an amount at or past it gives zero on every shift, a signed `>>` included, while inside the width a signed `>>` keeps the sign (D13). | | `==` `<>` `<` `<=` `>` `>=` | one type on both sides, and a bool back [0350]; atom sets have identity equality and inequality only, including between disjoint or overlapping sets. D200: the type is a scalar, an atom set, a pointer or a function value; two pointers must point at one type, permission aside, and a slice, an erased value, an array or a struct has no comparison. A pointer union has none with another union or a pointer, but takes `==` and `<>` with its atom, on either side, answering whether it holds that atom [1870] (D429). Two values of one distinct type whose base has equality, a scalar, an atom or atom set, a pointer or a function value, have `==` and `<>` [0650] (D427), and a scalar base also gives `<`, `<=`, `>` and `>=` in the base's order, IEEE's comparisons for a floating base with NaN unordered; a distinct type over a pointer union, a struct, an array or a slice has none; never with the base or another type without a conversion | | `and` `or` `not` | bool, and a bool back [0340] | | unary `-` | one integer or float type, and that type back | So an integer has no logical words and a bool has no arithmetic and no bitwise set: 'and' is what [0340] gave a bool and '&' is what [0330] gave an integer, and neither reaches across. [1820] already read the comparison rule this way when it said a chain would compare a bool with a number and that [0310] refuses it. The positions that want a bool and are not operators are a branch's or while loop's condition [1050] [1070] [1140], and an exit's `when` [0970]. For D185's condition declaration the required initializer first establishes the binding's declared or inferred type, and that stored value is the bool being tested. ### [1950] An operand an operation cannot take An operand an operation cannot take. [1890] says every binary operator takes two operands of one type and gives that type back, and for three of them a value of the right type is still not one the operation can use. No paragraph of the tour says what any of the three does. | the operation | the operand it cannot take | | --- | --- | | integer `/` `%` | a divisor of zero [0290] | | `<<` `>>` | a negative amount [0320] | | `[ ]` | an index outside the length [0520] | The third is not a binary operator and belongs here anyway, because it is the same question with the same answer. [1720] says this language checks bounds and [0580] says indexing checks the length before it computes an address, so what was left unsaid is only which of refusing and trapping applies where — and that is what the rest of this paragraph already decides for the other two. Float division follows IEEE 754: division by signed zero produces an infinity or NaN and does not use this refusal or trap rule. D18 makes an array index `usize`, so a negative expression is refused by its type before this row applies. The row asks only whether a well-typed index is below the array's length. This is not [0300]'s question, and the difference decides both answers. An overflow is a good operation whose result the type does not hold, which is why [1880] leaves it to the trap inside a body. Here the operand is what is wrong and there is no operation to perform at all, which is the case [0310] already answered for 'u8(300)': known when the compiler reads it, it is refused; otherwise it traps. Known is [1880]'s and [1940]'s and nothing besides — inside a body a literal, or a unary minus over one; at module level the whole of [1940]'s fold. So 'x / 0' is refused and 'x / y' traps, and which of the two a program gets does not move when an implementation gets better at folding, which is the objection D7 raised against believing a condition. 'a[4]' on a '[4]u8' is refused for the same reason 'x / 0' is, and 'a[i]' checks its length at run time. A negative amount is writable only where the left operand is signed, because [1890] gives the amount that type. No unsigned shift carries this check, on any target. At module level a trap is not available at all. [1460] says nothing runs before the entry point, so a module value whose divisor is zero has no moment in which to trap and no value to stand for it, exactly as [1940] found for a sum no type holds. Both are refused there. The lowest value of a signed type over -1 is not in the table, and is not a third rule. Its quotient is the case [0300] already covers: that type does not hold it, and [1890] gives '/' no wrapping form to opt out with. Its remainder is 0, which the type does hold, so nothing traps and the machines that fault on it anyway are the x86-64 and arm64 backends' to know about. The report names the operand and not the operator, because the zero and the negative amount are what a reader changes. ### [1960] A trap stops at the operation A trap is synchronous with the operation that causes it and happens at that operation's point in [0410]'s order. It does not return. The operation produces no value, and no later action of the failed computation occurs; actions before it are not undone. D232 permits the selected panic handler's terminal computation, without resuming that failed computation or unwinding its cleanup. How the surrounding system reports the trap is not Landin program behaviour. An operating system's signal, exception, status or other encoding is not stable across targets or compiler releases and a program may not depend on it. The same no-continuation rule applies to a `return` nested in an expression. For example, an index expression runs before the selected element is read and, on the left of an assignment, before its right-hand expression [0410]. If that index returns, neither later action occurs; facts from that edge do not reach a join. The default Linux x86-64 handler deliberately emits `ud2`; D232 defines selected-handler dispatch. It does not inherit the accidental fault or value of the machine instruction used for the operation. ### [1900] What may be written, and what may not What may be written, and what may not. [1810]'s place is a name, and of the four kinds of name the kernel has, two may be written and two may not. | name | written? | | --- | --- | | a mutable binding [0060] | may be | | a named return | may be: [0930] says it must be, and [1840] declares it as a place for that reason | | an immutable binding | may not: [0040] makes it immutable and [0450] says it protects the value it holds | | an `in`, `sink`, or `caller` parameter | may not be replaced | | an `inout` parameter | may be replaced, through the caller-owned place | An atom declaration and a recovery clause's error name are immutable values, not places. A function declaration is not a place. Nor is a range selection [0570]: it is a new view over its source, as a returned slice is, so an assignment, `inc` or `dec` naming one is refused with L0303 as `inout` already refused it, while an element indexed through it is an ordinary place (D250). A local or module binding holding a function value is an ordinary place: an immutable one may be called but not replaced, and a mutable one may be replaced only by a value with the same complete signature. A named function-valued return is a writable place; an unmarked function-valued parameter is not. A function-valued struct field is an ordinary subobject place: the root binding decides mutability, and replacement requires that field's complete recursive signature. A place reached through `.val` or slice indexing instead takes writability from the shallow `mut` in that reference type, independently of the binding that holds it [0430] [0450]. `addr` retains that place's writability: its result is `ptr mut T` for a writable place and `ptr T` for a read-only place. Taking an address does not grant permission to modify immutable storage. Nor does matching: an `inout` payload binding of a match arm [1220] is a writable name for storage of the matched value, so the value matched has to be a place that may be written by these same rules, and the binding is L0303 where it is not (D1085). The value's type is the place's type [0310], and the report names the place as well as the value, because which of the two is wrong is the reader's to decide. 'inc' and 'dec' say what 'x += 1' says [0400], so each wants a place that may be written and an integer type. ### [1910] Assigned before it is read Assigned before it is read. [0080] says a binding declared with no value must be assigned before use and [0930] says every named return must be assigned before the function returns. In a body those are one question and this is its shape: at every read of a name, at every `return`, and where a body ends, each applicable name has to have been assigned by every path that arrives there. For multiple results the question is asked independently of every named return. Aggregate fields retain independent facts, including a function field read as the callee of a call; the callee expression is checked before any argument expression. A written Boolean literal fixes its `if` edge: `true` takes the arm and `false` skips it. No other condition is believed. A name assigned in one reachable arm of `if c` and not another is not assigned after it, even if `c` was initialized with `true`. Only the written literal is used here; interpreting expressions to decide their value would make legality depend on constant folding. 'return when' is a return [1810], so what the function hands back is assigned above it and not below. A control-flow edge has independent fallthrough, successful-return, and failure consequences. A `fail` edge never needs the successful named return; its untaken guarded edge continues. A tried call may fail after its arguments and before any later action; a recovered call joins its success edge only with recovery edges that fall through. A return-compatible control-flow edge has two facts: whether it can fall through and whether it can return. Only fallthrough states meet at an `if` or `match` join; a returned arm neither lends nor removes assignment facts on a surviving arm. Every reachable fallthrough edge of a control expression must reach its block's final expression, and every such expression has the one complete type and shape from [1880]. An early-return edge needs no joined value, but it still requires the named return to be assigned at that edge. A guarded return has both facts: its taken edge returns and its untaken edge continues with the incoming assignment state. The unevaluated side of `and` or `or` is likewise a fallthrough edge: a return from the right operand cannot erase that skip edge, and assignments made only on the right do not survive their join. A `sink` argument follows one binding-rooted path of ordinary fields and literal fixed-array indexes. Pointer dereferences and slice indexes cross a reference boundary and are refused, including a literal slice index. A slice binding, field or fixed-array element still names its own descriptor storage and may be consumed as a whole. D220 makes this place-form boundary explicit. A module binding named through its module, `store.state`, is the binding its own name is [1420]: it roots a `sink` path, and a place consumed under one spelling is consumed under the other. Callee and arguments evaluate left to right before any place is consumed by that call. Each by-value argument captures its value when evaluated, including an aggregate passed by `sink`; a later argument may read or assign its original place. If evaluation transfers control before call entry, that call consumes no places. Effects of calls actually entered while evaluating its arguments still hold. On entry, the pending `sink` places must still be live and become unassigned at their exact binding-rooted paths, in written argument order. Repeated or provably overlapping sink places are refused. Every `inout` place must remain live after these consumptions, so a provable sink/`inout` overlap is refused in either argument order. A nested argument call that consumes a pending place requires a subsequent assignment before the outer call can enter. D223 pins this timing independently of argument-value capture and D149's `inout` rules. A consumed place may be read only after it has been assigned again on every arriving path where it was consumed. A part sunk out of an `inout` parameter must be assigned again on every return edge [0910]. Reading an enclosing aggregate reads its consumed parts too; assigning that aggregate restores those parts. Other fields and other known array elements remain independent. The `inout` obligation includes failure propagation: applicable `defer` and `undo` actions run before the exit check. Unlike a successful named result, the caller's `inout` storage remains observable after a recovered failure. This is definite assignment of one consumed place, not ownership; copies made before the sink remain live. The reference-origin walk is a second local flow fact. `addr` of local storage and a slice of a by-value array parameter have frame origin. An address reached through a pointer dereference or slice index instead retains that reference's origin, including when ordinary fields or fixed-array indices follow it. Taking the address of the local pointer or slice descriptor itself still has frame origin; copying a descriptor locally does not move its backing storage into the frame. A returned value with frame origin is refused. A retained `escaping` argument must be independent or derive only from parameters themselves declared `escaping`. A store checks its destination's backing storage, including `inout` parameters, pointer pointees, slice elements and reference-bearing fields or variant payloads. Caller storage cannot retain a frame reference or a non-escaping reference from another parameter origin. Updating storage with a reference from that same origin is permitted; retaining another parameter requires `escaping`, or `escaping into` naming the parameter whose storage keeps it (D445). Such a parameter may be kept in that storage and in no other, and its argument at a call must outlive the origin of the argument for the named parameter, as D445 and D455 decide it locally; afterwards the frame storage that argument reaches holds what was kept, as a store through a known address does. A known address alias to a local joins its writes into the local's value origins, while a pointee write does not change the pointer descriptor's origin. Integer-created pointers are explicitly untracked [0470]; joining one with a tracked frame or parameter reference does not erase the tracked restriction. On each return edge, [0790]'s exact `from` comparison applies to an actual tracked reference in the returned value. A provably empty arm of [0480]'s optional pointer carries no reference and therefore no origin to compare; it is not an `Untracked` reference. For every edge that does return a tracked reference, the set of parameter origins is exactly the signature's `from` set; in a generic instance, a name whose parameter is typed by a type formal asks nothing when the instance's type for it holds no reference (D290). One exception keeps the exactness honest about storage that outlives the call. A reference is static when it reaches storage no frame owns: module storage, a reference read from module storage or reached through one, a literal, or an independent result such as an allocation. A read-only result whose edge carries a static reference satisfies a named source it does not derive from, because keeping that source alive asks nothing the static storage does not already give; it must still derive from no parameter its clause leaves out. So a concept entry written `from self` is implemented by a provider lending storage the program or the process keeps, as the hosted I/O provider lends the process's arguments. A writable result gets no such exception. In addition, D222 forbids a known independent storage origin in a result with a nonempty `from` clause when its type carries a reachable writable reference. The permission walk includes pointer and slice referents, array elements, struct fields and variant payloads; a read-only outer view does not remove a nested view's permission. An erased value conservatively qualifies, while a function value's signature does not describe storage carried by that code value. Aggregate value origins remain a conservative union, including origins from read-only sibling fields. An independent alternative counts only where a writable reference may reach it: one that arrives as a pointer, slice or nominal aggregate whose type reaches no writable reference, or as an `any` of one, can be no store's destination and is admitted beside the named sources (D375). A separately known independent alternative is retained across control joins, local copies, calls and selection of anonymous result positions. An optional empty atom and an empty slice literal contribute no storage destination; a constructor containing only such empty references preserves that fact. Only the optional atom has D189's exemption from exact source agreement. Explicit untracked conversion alone supplies no origin proof, and does not erase another alternative's known independent origin. A helper which needs parameter and module alternatives passes both as explicit arguments and names both in its `from` clause. Calls reconstruct those written sources; no body inference is introduced. A source a generic instance asks nothing of under D290, one not passed `inout`, adds nothing to that reconstruction, so the result neither derives from its argument nor is a view of it (D1042). A live local view records the binding it derives from and the fields it reached that binding through; an `inout` or `sink` use of that binding, or of a field of it that holds one of those fields or lies in one, is refused when the view is read before being replaced. A binding that holds a reference into its own storage lends the fields able to hold that reference together (D1371). A view replaced by the result of the `inout` call itself ends at that assignment, except where the call's recovery can `break` or `continue` past it (D291). A deferred call on a return or failure edge is checked against what is live on that edge, and no later statement is a use there (D292). A view no name holds is in use as well, until what it was evaluated for is done with it (D1084). The source of a `for` is in use while the loop runs: passing what it views `inout` or `sink` in the body is refused when a path from the call reaches another iteration, or reads the loop's element where that names the walked storage in place [1160]. An argument is in use until its call returns, so what it views is passed `inout` or `sink` neither to that call, in either order, nor to a call nested in a later argument; an operand of any other expression is held the same way while the operands after it are evaluated. What such a view views is the storage under it: a binding an address or a range was taken of, an array of it lent as a slice [0570], and for a call result what each argument its `from` names views, with the binding that argument is rooted in when the argument is a record or an array or is passed `inout`. A pointer, slice or `any` given by value lends what it refers to and not the binding that holds it; a reference only read out of a binding's field has other storage under it and holds nothing here; and an address or range of one field holds no other field of the same binding where fields alone reach both. A module binding named through its module, `store.cells`, is the binding its own name is [1420], here and in D149's test of one place passed twice. Volatile reference paths remain exempt [0850]. A match payload alias keeps its selected storage live even when the payload is scalar and carries no reference. Both reads and writes use that storage; a derived address or range, pending cleanup argument, or reachable inner-loop use also extends its lifetime. A direct retag, replacement of a containing object, or an `inout`/`sink` call that can replace it is refused until the last use. D76 selects a directly written case before evaluating its payload initializers, so reading an old alias in those initializers is still a live use. A whole containing construction also requires those aliases' last use before construction starts; copy a needed scalar first. A computed value destination keeps D134's temporary-and-copy-back order. Known address aliases participate in this local check. Different fields and known array elements remain independent, and a fresh match arm on a later outer-loop iteration creates fresh aliases. D134's copied computed-value subject instead aliases its own temporary; a copied scalar payload value keeps no borrow of the original. Rebinding a pointer descriptor does not replace the payload storage its earlier match selected. A reference-free scalar operator result carries no reference origin [0840]. This includes a saved `lenof` result: using that number after an `inout` use of its source does not keep a view of the source alive. Operand checks and effects still follow each operator's evaluation rules, including short-circuit joins; D14's fixed-array measurement and D31's literal-length measurement remain unevaluated. This value rule does not erase storage provenance: an address or range formed from a selected place still derives from that place's backing reference, even when reading the selected scalar would copy no reference. A `caller` position is part of the complete structural function signature. It has D192's ordinary nominal struct type: exactly three fields, in order, `file_id: u32`, `line: u32`, `column: u32`. Aliases retain that identity; other struct identities remain distinct even when their shapes qualify. There is no parameter convention or `escaping` modifier. It remains an ordinary runtime ABI position after the compiler has filled it; source calls omit it, except for D192's named forwarding from another `caller` parameter. `caller` is a contextual word [1760] does not reserve, exactly as `range` is, and it is the modifier only where a second name follows it: a parameter of that name writes `:` next, so `caller: utf8`, `in caller: u8` and `escaping caller: ptr u8` all declare an ordinary parameter spelled `caller`. A module binding is not ordinary pre-use definite assignment. [1460] says its value is known when the compiler reads it; reference-containing module images must likewise supply a valid non-null static image. ### [1930] What may be discarded What may be discarded. [1020] says a result is discarded on purpose or not at all, and [1810] writes that '_' '=' expression. Anything with a type may be thrown away, including a value nobody computed for the purpose: '_ = 1 + 2' is a discard of an i32 by [0200], because a rule about wasted work is a rule about people and this one is about types. What may not is a call of a function returning none [1920]. Discarding is for a result, and that call has none. The converse holds as well: a call that does hand a result back is not a statement on its own, so the only discard is the written one (D244). A call with a declared error is also refused when a discard would ignore that outcome; `try` propagates it and call-site `else` handles it explicitly. D241 makes the rest mechanical: a discard takes every place and call, and every expression an inferred binding `x := e` takes; a whole aggregate place is discarded where it stands, after its indexes are evaluated and checked. ### [1920] What a call means What a call means. A static `T.entry` selection requires one declaration of that entry name across T's direct concept, represented-formal constraint and parent closure. Each concept is visited once: a shared ancestor reached along two paths contributes one declaration, while different declaring concepts remain ambiguous even when their providers agree. Parent order and a direct child declaration grant no precedence. D221 records this selection rule; an unused colliding closure may still be declared and conformed to. Where T names a concrete type rather than a type parameter, the conformances of T in the program's register [1280] take the closure's place: the one whose concept declares the entry supplies it, and none or two is refused (D1364). Either selection is called where it is written. [0980] gives no source-written parameter a default value, so a call names every non-`caller` runtime parameter exactly once. A `caller` position is instead filled by the compiler with D192's three source coordinates, unless a named argument forwards another `caller` parameter into that position. A positional prefix skips caller positions and fills the other runtime parameters in order; a named suffix may write the remaining parameters in any order, but may not repeat one or name one the callable signature does not have. Matching uses the labels of the static callable signature for a stored or selected function value. Those labels are retained call-shape facts but remain excluded from [1000]'s structural function-type identity. Each runtime argument is synthesized and checked in written order, then its checked value is placed at the matched formal position for the ABI. A static-role label is not a runtime argument of a nongeneric or indirect callable. Each argument has its parameter's type [0310], and the call has the type of the named return. [1975]'s C variadic call is the explicit exception to fixed arity and named matching: all actuals are positional, every fixed parameter is supplied, and the additional tail uses that rule's restricted carriers and default promotions. An argument filling a slice parameter `[]T`, passed `in`, may instead be an array that the call lends a slice of whole [0570]. A fixed array place, a binding, a parameter, a named return or an admitted array field, lends its own storage for the length of its type, and its elements must be the slice's; a `[]mut T` parameter takes such a place only when the place is writable, as a range slice of it would be. A nonempty array literal is checked as an array of the slice's element type with as many elements as it writes, formed in written order, each time the call runs, in storage the caller's frame keeps for that call, and lent read-only: a `[]mut T` parameter never takes a literal. A view of it stays valid in the caller's frame after the call and sees what the call's latest run formed. Neither form is a text view, so a `utf8` parameter takes neither. The lent slice has the origin of what it views: a literal's is the caller's frame, so a result `from` that parameter cannot leave the caller [0780], and a place's is the place's own. A generic routine's parameter whose written type names no formal is such a parameter, and its argument is checked as here (D419). One whose element type is a formal lends a place, matched through its element (D372), and refuses a literal, which has no type of its own to deduce from (D138). An atom argument whose parameter is written as an atom set that names no formal of the routine has nothing to deduce there, and widens into that set as [0640] lets an ordinary call's argument widen: `net.shutdown(host, socket, net.sending)` needs no local of the set's type first. A call of a function returning none has no successful-result type. It is a statement [1810] and nothing else: nothing binds it, no argument is one, and [1930] cannot discard it, because there is no result there to discard. Its call-site `else` [1030] therefore has no result to stand in for: it handles the error and yields nothing, and a value written there, alone or as the last line of its block, is refused. A call with one named return has that return's type. A call with two or more has [0990]'s anonymous structural aggregate; its fields are selected and destructured by the return names. The orthogonal declared error outcome is unchanged at every result count: a failing call is still tried or recovered. A callee is a function. It may be a declared function; a local, module, parameter or named-return binding; or a selected ordinary or variant-payload struct field whose value has a function type. The complete callee expression is evaluated before the arguments, and every stored form calls the runtime code address. A function's own name and an anonymous function away from a call are values of their function types [1000] [1010]. All positions retain one complete structural signature, recursively when a parameter or result is itself a function. Labels are not part of function signature agreement: parameter order and type, plus the ordered result types, are. The labels do remain the field names of a multiple-result value at its static call site. A binding of any other type is not a function. A whole multiple result may initialize an inferred local, be selected by field, be assigned to a mutable inferred local of the same named structural shape, or cross a control-expression join. A destructuring binding evaluates its source once and selects fields by return name in any written order. A bare name binds a local of the same name; `field: local` renames it; `field: _` ignores that field; and one bare `_` explicitly ignores every unbound field. Unmentioned fields are also ignored, as [0990]'s one-field example requires. An unknown or repeated field and two locals with one name are refused by the ordinary field and scope rules. The anonymous shape is not a nominal struct type and has no type spelling of its own. A scalar type name in front of `(` remains [0700]'s explicit conversion. The enabled reference slice admits the two directions [0470] requires: an integer type applied to a pointer checks that the address fits, and `ptr(integer)` takes its complete pointer type from context and produces an untracked non-null pointer under [1975]'s known-zero refusal and always-on converted-zero check. D168 also admits an enabled integer type applied to an integer value. D169 admits f32 or f64 applied to a float value. Conversion from an enabled integer to f32 or f64 is admitted by D170. D171 admits an enabled integer type applied to a float value, and D172 admits an enabled integer type applied to bool. D173 admits bool applied to an integer value. D174 admits bool applied to a float value, and D176 admits f32 or f64 applied to bool. The deferred integer widths remain refused by [1830]. ### [1980] Declared errors are an orthogonal payload-free atom outcome A function is infallible when its signature has no `!`. A concrete `!` names a nonempty atom set; that set is part of complete structural function-type identity, recursively when a function value occurs in another signature. A public declaration, anonymous function, and written function type must be concrete. A private declared routine may write `! ...`; whole-module checking then takes the least fixed point containing every atom it fails with and every concrete or inferred set propagated by `try`. Mutually recursive private routines are solved together. An inferred empty set makes the routine infallible. Generic deduction from a recovered error waits for its complete finalized set, including through local aliases. D215 refuses only a circular key/effect dependency in which choosing a generic instance requires the inferred effects of that same unresolved instance; ordinary and mutual error recursion remain least-fixed-point inference. `fail atom` leaves by the error outcome and carries no successful result. The atom's possible set must be a subset of the routine's finalized declared set. A fail path need not assign the named successful returns. `when` evaluates its condition first; only the taken edge evaluates the atom and fails. `try call` evaluates the call once and propagates its error unchanged; its success value, including a function, fixed array, nominal aggregate or anonymous multiple-result aggregate, has the ordinary call shape. A failing call written without `try` or call-site `else` is refused. Call-site `else` handles only a nonempty declared error set. Its optional name is an immutable atom value scoped to the recovery block and typed as that complete set. The successful call edge and every recovery edge that falls through must supply the same complete scalar, atom, function, array, nominal aggregate or anonymous multiple-result aggregate shape. A recovery edge may instead `return`, `fail`, or a permitted `break` or `continue`; it then supplies no placeholder and does not participate in the value join. Atom `match` is exhaustive over the subject's structural set; one final `_` arm may cover all members not named explicitly, and atom arms bind no payload. Neutral IR keeps successful results and errors separate. Atom constants carry source declaration identity and atom-set metadata; slots, datums, signature parts and values retain that structural set. A call with errors names a separate error slot, `Failure_Test` branches on the abstract outcome, and `Fail` is its own terminator. No inferred marker reaches IR. Verification checks set runs, identity membership, widening stores and arguments, complete signature equality, call failure slots, and failure subsets before a backend sees the unit. For the documented Linux x86-64 internal convention, ordinary atom values use a 32-bit carrier. The backend assigns dense nonzero codes in declaration- identity order. They use the ordinary integer argument positions and `%eax` for a successful atom result. `%r10d` is the dedicated failure carrier for both direct and indirect Landin calls: zero means success and a nonzero dense atom code means failure. A successful callee clears `%r10d`; `fail` writes it. The ordinary scalar or function result remains in `%rax`, and an aggregate success still uses caller-owned storage, so the error carrier consumes no source parameter, result position, or stack argument. No source atom has code zero. ### [1940] A module value is known when the compiler reads it A module value is known when the compiler reads it. [1460] says values at module level must be known at compile time and that nothing runs before the entry point, and the kernel's version of known is short: a literal, 'true', 'false', an operator of [1820] applied to those, and a name bound to a module binding whose value is known. Not a call. There is no compile-time execution in this language, so a call is not a value the compiler holds, and [1830] refuses it as the construct it is rather than as a type error. A compiler fact the build holds is known as well: D437 lets a module image read a bool or integer fact, or an atom fact compared with one of its atoms, as the value configuration found. Ordinary integer `+`, `-`, `*`, `/` and `%` in a module image fold in the signed range from `-(2**64 - 1)` through `2**64 - 1`, independently of the host and destination width. Every intermediate must fit that fold range; the final image must fit its declared or inferred integer type. Thus a module binding `value: u8 = 200 + 100 - 100` holds 200 even though its intermediate 300 does not fit u8. Its individually written literals still need their ordinary type context. A fold beyond the kernel range or a final image outside its destination range is refused: [0300]'s trap has no runtime moment before entry [1460]. Inside a body ordinary arithmetic retains the operand type's width and traps on overflow, so the same u8 addition traps before its subtraction is reached. Wrapping arithmetic, bitwise operations, shifts and explicit conversions keep their own type-dependent rules. D224 records this existing module-fold boundary; D136's fixed expressions and D202's options retain their separate contracts. D162's first float increment admitted a decimal float literal, its unary minus, `zeroed`, or D167's named infinity and NaN as a module scalar or aggregate-field image. D175 admits `+`, `-`, `*`, `/` and comparisons over module-known f32 and f64 values, including scalar and aggregate images. The target-neutral folder evaluates IEEE carrier bits with bounded integer work; it does not use the compiler host's floating-point operations as language semantics. [0130] makes a module a set, so one module value may name another written below it. A chain of them that comes back to where it began names nothing at all: no member of it is first, exactly as [1850] found with two declarations of one name. So it is refused, and the report names the declaration the chain came back to, because that is the one place in it the reader is standing. A name another module exports, written through that module's name, `limits.size`, `colours.green` or `sizeof shapes.pair`, is the same name: resolution binds it to the declaration itself, so it is known exactly when the unqualified name is known in its own module, in a scalar value, an array or record image and a measurement alike, and it selects no storage. The whole program is one set of modules, so a chain may pass through several of them, and one that comes back to where it began is refused at each declaration on it, in whichever module that declaration is. What has no value before the entry point is refused whichever module it comes from, each saying why: a field of a record image or an element of an array image reads storage, a call runs a routine, and an address needs a data relocation no backend emits. A `mut` module value is known by the image it starts with, here or in another module, since nothing has written it before the entry point; inside a body it holds what was last written and is not known. A distinct type's flags combined with D302's `|`, `&`, `^` and `~` fold through its base at the base's width, as its conversion does. A declared or anonymous function is a compile-time-known code address. A module function binding may name either directly, or another module function binding whose static chain reaches one; a chain that returns to itself is refused like any other module-value cycle. Function code addresses have no all-zero value, so a function-valued module binding must write an initializer. A function field in a static struct or selected variant image is a target-neutral relocation to such a declared or anonymous routine, not an integer fold. Copying a complete module struct image copies that relocation while retaining distinct storage. A module aggregate whose active all-zero shape contains a function field must therefore write an explicit static image too. A contextual text literal is also known. A `[]u8`, `utf8` or `utf16` module image is the base of its read-only datum and its decoded code-unit length; a `cstring` image is the base relocation alone. Each datum has exactly one trailing zero element excluded from a slice length. It is an address relocation rather than an integer fold or code run before the entry point. An atom-valued module binding must name an initializer. There is no zero atom, and the zero carrier pattern reserved by [1980] is not a source value. A scalar binding with no value is known too, and what it holds is zero — false, for a bool. [0080] lets a binding carry no value and says it must be assigned before use, and that sentence has nothing to bite on here: [1460] says nothing runs before the entry point, so there is no moment at module level in which to assign one, and [1910]'s walk is over the paths through a body and there is no body. Zero is a value the compiler knows, which is the whole of what [1460] asks. So 'mut counter: u32' is module state a function updates without an initialiser that says nothing, and reading one before anything writes it reads zero rather than being refused, because there is nothing left to refuse. ### [1970] The first hosted path has one entry shape The minimal Linux x86-64 path accepts one hosted entry shape: a public function named `main`, with no arguments and the one named return `code` of type `i32`. Its declaration therefore starts `public main: () -> (code: i32) =`. The returned code is passed to the host as the program's status through the system C ABI [1650]. Every hosted target takes this one shape, and L0502 refuses any other `main`: the arguments reach the program through its hosted world, not as parameters, and C's `argc` and `argv` are what `_landin_host_initialize_arguments` hands that world [1650]. A freestanding program does not use this rule; its build description names the entry [1650]. The first hosted entry is infallible: this boundary has no host mapping for a declared Landin error. In a rooted program, only a declaration in the designated entry module can satisfy this shape. A reachable imported module's `public main` is an ordinary public function and is never selected as the executable entry. Beside the selected entry, a bodyless `extern(c) link(symbol: "main")` of `(i32, ptr ptr u8, ptr ptr u8) -> i32` is admitted as C's view of the same symbol; it is how `platform/linux`'s process entry calls `main` under a static Linux link, which passes the returned code to `exit_group` (D279). The entry may spell the link name it has, `link(symbol: "main")`; the prefix changes nothing, and any other symbol on it leaves the program without an entry, L0502 (D1113). A `public main` in the entry module that is not this shape is refused when the program is checked or emitted as assembly, as when it is linked (D443). ### [1975] The selected hosted C boundaries `extern(c)` selects a function convention, not an import or a visibility. Without a body the declaration imports a linked C routine; with `= body end` it defines a C-convention routine in Landin. A definition may be private (for example a callback) or `public`. A `link(symbol: "foreign_name")` annotation may follow `extern(c)` before the declared name, or stand alone before a native function's declared name [1610]. It selects the linker identity, not the Landin lookup name, signature, convention or visibility. In particular, the standalone form keeps the native Landin convention and still requires the ordinary `= body end`; `link` never implies C. The decoded link name has the precise safe ASCII shape `[A-Za-z_.$][A-Za-z0-9_.$]*`: its first byte is a letter, underscore, dot or dollar, and only a later byte may additionally be a digit. Whitespace, `@` suffixes and arbitrary assembler expressions are outside this form. The name is a logical external identity, before the platform's symbol prefix: ELF uses it unchanged; Darwin prepends one underscore, including when the logical name already begins with an underscore. Thus `foreign_name` maps to `_foreign_name` and `_foreign_name` maps to `__foreign_name` on Darwin. This applies equally to explicit native and C link names and default external names. It does not select a calling convention or enable a backend. Assembly quoting follows that mapping and does not change the resulting object symbol. Compatible bodyless C declarations may share a symbol with each other or with one definition; incompatible signatures and multiple definitions are refused. C imports and public C definitions default to their declared spelling. A private C definition without an override uses collision-safe internal naming. `public` is not an export (D415). The global symbols of a program, the names the linker resolves against the C library and every other object, are its hosted or firmware entry; its C imports and public C definitions under their declared spelling; every routine and module datum with a link name, public or not, which is how data is exported deliberately (D416); every public definition in a machine convention, platform/linux's `_landin_start` among them; and every Cortex-M routine or datum with [1640]'s section, alignment, vector or `keep`. Every other routine and datum, public or private, is a symbol local to the image under its own name: no C library or linked object can collide with it or be replaced by it, and a debugger, a backtrace and the symbol table name it as the source does. A C import's spelling is never checked against the selected C library's: nothing but an export can meet it. Exports meet each other, and a public definition in a machine convention with no link name is held under its own spelling to the rule a link name is: no other export may have it (L0347, D770). Within one program two items can still want one spelling: two modules' routines named `reset`, or a routine beside a C import of its own name, since an assembly reference to that name would reach the local definition. Each such item that is not an export takes its qualified spelling (D417): its module's logical path with every `/` replaced by `.`, or `main` for the entry module, then `.` and its name, so `core/arena`'s `reset` is `core.arena.release` and an entry-module `read` beside C's is `main.read`. An export keeps its spelling and never yields. An identifier cannot hold `.`, so only an explicit link name can hold a qualified spelling as well; then, and for every instance of one generic routine after the first, the item takes the first of the qualified spelling followed by `.1`, `.2` and so on that no other item holds, in item order. The qualified spelling is a function of the declaration alone. Whether an item needs it depends on what else the program holds, and an instance's number on which instances it holds. A C function type is `extern(c) (parameters) -> returns`. Convention and variadic status are part of recursive function identity wherever a function is carried, including nested fields, parameters, results, generic actuals, static images and indirect calls. Neither matching machine widths nor `layout(c)` makes a Landin function a C callback. Function values are code addresses; `ptr handler` instead addresses a stored function value. A C function type applied to one `usize`, written in place or through an alias, `adder(address)`, makes a C function value of the code at that address, as a loader's symbol lookup gives one. Nothing can check that code of that signature is there: that is the program's, as it is a C cast's. The bits are unchanged; zero, the address of no code, traps where the value is made, inside `unchecked` too, and a known zero is refused with L0335. The address carries no origin [0810], so the value is not held to the life of the object it was found in, and a `from` clause cannot name one for it, because a function value holds no reference (L0339). Only the C convention is made so: a native Landin function type applied to an address is refused with L0301, since code outside the program is reached only through its C entry points, and so are an integer of another type and a pointer, which `usize(p)` converts first. The way back is `usize(f)` (D1343): a C function value, written as a declared `extern(c)` function or kept in a binding of a C function type, converts to the address of its code, the word C keeps for that function pointer, with its bits unchanged and no origin. Only a C function value converts, and only to `usize`; a function value in Landin's own convention, or the conversion to another integer type, is L0301, and the address of an interrupt or naked function is no C function's either. The selected hosted ABIs are Linux and FreeBSD x86-64 SysV AMD64 LP64, Darwin arm64 AAPCS64 with Apple's platform differences, both conventions with signed plain C `char`, and Linux and FreeBSD arm64's standard AAPCS64 LP64, whose plain `char` is unsigned, and RV64 Linux LP64D, also with unsigned plain `char`, and Windows x86-64's x64 convention, LLP64 with a 32-bit `long` and a signed plain `char` (D2190). Cortex-M firmware's C ABI is AAPCS32 (D920), ILP32 with an unsigned plain `char`, at the base PCS or, with a description's float unit, the VFP variant (D616). `compiler.c_sysv_lp64`, `compiler.c_darwin_lp64`, `compiler.c_aapcs64_lp64`, `compiler.c_riscv_lp64d`, `compiler.c_aapcs32` and `compiler.c_win64_llp64` are their respective fixed bool configuration facts, each true for its own ABI alone, not guesses from pointer width or architecture spelling. `compiler.c_runtime` is a fixed bool configuration fact too: true when C's runtime starts the program and its library is linked, which on Darwin and FreeBSD is always and on Linux only for a request with `--link=libc`, and false for every other Linux request, a check that emits nothing among them, on Windows, which links no C runtime (D2188), and on a target with no hosted system. A source selects C library calls by it, so a static Linux program never reaches one. The ordinary `platform/c` aliases assert one supported fact before exposing `c_char`, `c_schar`, `c_uchar`, `c_short`, `c_ushort`, `c_int`, `c_uint`, `c_long`, `c_ulong`, `c_longlong`, `c_ulonglong`, `c_size`, `c_ptrdiff`, `c_float`, `c_double` and `c_bool`. These name existing scalar identities: signed/unsigned 8, 16, 32 and 64-bit integers as appropriate, `usize`/`isize`, `f32`/`f64` and `bool`; under the LP64 ABIs `long` and `long long` are both 64-bit, and under AAPCS32 and Windows x64's LLP64 `long` is 32-bit (D921, D2190). C `char` is the selected ABI's plain `char`, a numeric byte and not a Unicode scalar: `i8` under SysV, Darwin and Windows x64, `u8` under standard AAPCS64, RISC-V LP64D and AAPCS32; `c_schar` and `c_uchar` keep their signedness everywhere. A described target's ABI identity and widths do not imply that its C boundary is implemented. C signature, record-layout and variadic-call capabilities are selected explicitly; neither `platform/c` nor generated bindings may infer them from LP64 alone. A C signature is nongeneric and infallible, takes only `in` runtime parameters, and returns at most one value. Its admitted values are the enabled integer scalars, bool, pointers, D189's named one-atom pointer unions, f32, f64, fixed C function values and recursively compatible nonempty `layout(c)` structs. D213 distinct identities over an admitted scalar, pointer, callback or C record have their base's layout and transport, while retaining their own Landin signature identity. A distinct identity does not make an excluded base admissible. Such structs contain those leaves, nested C structs and nonempty fixed arrays of compatible fields, with the selected C field offsets, alignment and trailing padding. A `layout(c, packed)` record (D410) and a record whose last field is a `[0]T` flexible array member (D413) are C records too, but a C signature takes or returns either, or a record holding one, only through a pointer (D414). Ordinary Landin structs, variants, slices, text and `any` do not become C records by having a similar byte count. Arrays are fields or pointees, not by-value C array parameters or results. Pointer permission, `escaping` and written `from` contracts remain Landin checks; a header alone establishes none of their ownership or retention promises. The SysV C transport classifies actual target-byte eightbytes as INTEGER or SSE, recursively merging fields at their offsets. In this non-vector subset an aggregate above sixteen bytes uses MEMORY. Integer/pointer and SSE argument register banks are independent. A register aggregate is assigned wholly or rolled back wholly to inline stack storage when either bank is exhausted; it is not passed as the internal Landin pointer carrier. Results use the corresponding integer/SSE return banks, or caller storage through the hidden C result pointer, returned again by the callee. Copies and partial eightbyte loads/stores stay inside the actual object extent. None of this changes Landin's internal convention or [1980]'s separate failure carrier. Darwin uses independent x0–x7 integer/pointer and v0–v7 floating argument banks. A homogeneous aggregate of one through four f32 or one through four f64 leaves (including nested C records and arrays) uses consecutive floating registers. Other aggregates through sixteen bytes use integer chunks; larger aggregates use a pointer to a caller-owned copy. A register aggregate that cannot fit its bank goes wholly to the stack, exhausting that bank. Fixed scalar and homogeneous floating aggregate stack arguments have their natural size and alignment rather than a mandatory eight-byte slot; any other aggregate on the stack occupies whole eight-byte slots aligned to at least eight, as AAPCS64's B.5 and C.14 require. The caller extends narrow integer arguments to at least 32 bits. Results use x0–x1 or v0–v3; an indirect result uses caller storage addressed by x8 without consuming an ordinary argument register. Copies stay within the object extent. Every Landin routine preserves a frame record through x29; x18 is reserved. These physical rules do not enter target-neutral IR or change source cleanup. The standard AAPCS64 shares Darwin's banks, homogeneous floating aggregates, sixteen-byte indirect bound, narrow-integer extension, results and x8. It differs in two places. Every stack argument, scalar or aggregate, occupies its size rounded up to whole eight-byte slots and is aligned to at least eight, as C.16 requires. An unnamed variadic argument is assigned exactly as a named one of its promoted type would be, to the next register of its bank and to the stack only when that bank is exhausted. x18 stays reserved there too, so one register rule holds wherever `compiler.arch == arm64`. RV64 Linux uses the RISC-V LP64D psABI: little-endian, 64-bit pointers, 64-bit `long`, 32-bit `int`, 64-bit ABI floating registers and a stack kept 16-byte aligned. Scalar alignment is natural, through sixteen bytes; C records keep natural field placement and trailing padding. Integer and pointer arguments use a0–a7; floating scalars use fa0–fa7 while available. A named C record flattening to one or two floating leaves, or one floating leaf and one integer or pointer leaf, uses the corresponding independent banks if the whole flattened value fits. Flattening includes nested C records and arrays at their actual byte offsets. When either required bank cannot fit, the whole value falls back to integer transport without consuming the floating bank. Other values through sixteen bytes use one or two integer chunks. An integer value needing two carriers can split between a7 and the stack. Larger C records pass a pointer to a caller-owned copy. Integer scalars narrower than 64 bits extend according to their signedness to 32 bits and then sign-extend to 64 bits, including unsigned 32-bit values. Floating register values narrower than 64 bits are NaN-boxed. Stack arguments occupy whole eight-byte slots, naturally aligned to at least eight and at most sixteen. Results use the same classification in a0–a1 or fa0–fa1. An indirect result consumes a0 as an implicit first argument; its address need not be returned. Copies stay within the actual object extent. Every Landin frame keeps x8 as the entry CFA, the saved return address at CFA−8 and previous frame pointer at CFA−16. x0, x1, x2, x3, x4 and x8 are unavailable to ordinary assembly operands; integer operands use canonical xN names, with `general` selecting caller-clobbered registers. Named callee-saved registers are preserved; their raw ABI aliases identify those same registers, and only caller-clobbered floating registers may be named without float operands. C signature, C record and outgoing variadic-call capabilities are enabled explicitly for this ABI. Cortex-M firmware's AAPCS32 (D920) places arguments in r0–r3 in four-byte words and then in the outgoing area, which the caller keeps eight-byte aligned. A scalar or `layout(c)` record takes the next words that hold it; a record that does not fit splits between the remaining registers and the area while nothing has gone to the area yet, and once one argument is there every later one is. A value aligned to eight, an `i64`, `u64` or `f64` or a record holding one, starts at an even register and at an eight-byte offset of the area. The caller extends a narrow integer argument to a word, and the callee a narrow result. A record result of up to four bytes returns in r0, an eight-byte scalar in r0–r1, and a larger record through a hidden address in r0, which takes the first argument register. With a description's float unit the VFP variant (D616) passes an `f32`, an `f64` and a record of one to four of one of them in s0–s15 instead, and returns one in s0–s3 or d0–d3. Copies stay within the actual object extent. RV32 firmware's C ABI is the RISC-V psABI's soft-float `ilp32` (D660, D677): little-endian, 32-bit pointers, `int` and `long`, and no floating-point registers, so `f32` is one integer word and `f64` two. Scalar alignment is natural, an eight-byte scalar at eight, and the stack is kept 16-byte aligned. Arguments use a0–a7 in four-byte words: a value of up to eight bytes, scalar or C record, takes one or two, low word first, and splits between a7 and the stack when one register is left; a larger C record passes a pointer to a caller-owned copy, and a larger result comes back through a hidden pointer in a0. Stack arguments occupy four-byte words, aligned to their own alignment up to sixteen. An unnamed eight-byte argument takes an even register pair. Every Landin frame keeps x8 as the entry CFA, the saved return address at CFA−4 and the previous frame pointer at CFA−8. The planner holds this convention to GCC's (D677); C signatures, records and variadic calls stay disabled on RV32 (D920). A final `, ...` after at least one fixed parameter marks a variadic C signature. It is not [0960]'s `! ...`. Variadic calls use only positional arguments, including their fixed prefix, evaluated in written order. Their unnamed tail admits scalars, pointers (including named optional unions) and fixed C callbacks, not aggregates, arrays, slices, atoms or erased values. Outgoing direct and indirect calls promote unnamed f32 to f64 and bool/narrow integers to C int; untyped integer and floating literals take i32 and f64 respectively. Other admitted tail identities remain unchanged. SysV calls supply the ABI's SSE-register count; Darwin places every promoted unnamed argument in an eight-byte stack slot; standard AAPCS64 assigns them as named arguments. RISC-V LP64D assigns the promoted unnamed tail by the integer convention, including floating-point bit patterns; after one unnamed argument goes to the stack, all subsequent unnamed arguments go to the stack. AAPCS32 calls no variadic function yet: a variadic C signature is refused there, and a fixed-arity C function that makes the call is imported instead (D922). Fixed arguments retain their declared types. Variadic C function values may be stored and called in Landin, but a C callback parameter, result or record field must have a fixed signature. A native Landin definition that receives varargs is refused: incoming entries require a generated C adapter with an explicit extraction schema rather than an untyped Landin `va_list`. No declared or inferred Landin error set, exception unwinding, or `longjmp` across Landin frames is part of this boundary. Header processing belongs to Clang, which the deterministic binding generator `refine bindings` asks for a header's AST (D820); no compilation reads a header. The generator contract covers declarations and C adapters for integer-backed enums, untagged unions, bitfields, globals, thread-local access, nullable callbacks and schema-defined incoming varargs. It does not introduce native C union, bitfield or TLS grammar. Policy supplies missing nullability, origin, retention and adapter choices, not handwritten replacement signatures. Nullable callbacks require a genuine code-pointer adapter representation, never a pointer to a function-value cell. Selected extended/x87 or 128-bit scalars, complex, vector, atomic or volatile types, old-style or non-C-calling-convention functions, packed, overaligned, flexible or zero-size by-value records, anonymous unaliased declarations, unsupported arrays, unsafe, stale or missing policies, and unsupported `va_list` forwarding receive explicit generator refusals rather than guessed layout or a fallback ABI. Enums, unions, bitfields, globals and TLS, nullable callbacks and bounded incoming-varargs schemas cannot be refused wholesale as a completion shortcut. This rule states the generator's contract; it is not a claim that its implementation or differential evidence is complete. A known integer-to-pointer construction whose value is zero after target `usize` conversion is refused, including a closed folded expression. A dynamic construction tests the converted address for zero and traps before producing a pointer; this check remains in `unchecked`. Integer construction still loses origin, not non-nullness. Foreign nullable data pointers use a named one-atom pointer union and exhaustive `match`. Absent allocator backing uses that same ordinary union discipline, never a forged `ptr(0)` or `ptr(1)` allocation. `core/mem.detach` reports `not_empty` for a nonempty prefix and `empty` for already absent backing; a successful release clears backing to its atom. Foreign failure detail is ordinary explicit state. `platform/posix` reads the errno after a documented libc failure indication on Darwin and FreeBSD, through `platform/libc`'s `errno_cell` before any other host call, and on Linux takes it from the failing system call's negative result (D279); either way it reaches `hosted/system` or a provider built over it, `hosted/blocking`, as an atom of `posix.errno` with its number (D298). Each retains the exact terminal value in the last-error cell the system handle names, exposed by `system.last_errno` and `blocking.last_errno`: the process's private cell for a handle from `system.new()` or `blocking.new()`, or a caller-declared `system.space` for one from `system.over` or `blocking.over` (D288, D476). Safe interrupted open/read/write attempts may retry; completed read/write progress is never replayed. Close consumes the handle even on failure and is never blindly retried, including EINTR. These facts neither add payloads to error atoms nor make errno a public Landin variable. The hosted argument root belongs to `platform/posix`, which defines the public C-convention routine `_landin_host_initialize_arguments` with the signature `(count: i32, escaping values: ptr ptr u8, escaping environment: ptr ptr u8) -> none`, which C declares as `void _landin_host_initialize_arguments(int argc, char **argv, char **envp);` under the platform symbol prefix. When a hosted entry is selected and the program defines a C routine with that link symbol, the selected no-argument Landin entry calls it with the actual incoming C carriers, `argc`, `argv` and `envp`, still in the first three argument registers, before its source body runs; a program that defines none calls nothing. Beside a hosted entry every declaration carrying that symbol must be exactly `extern(c) (i32, ptr ptr u8, ptr ptr u8) -> none`, whatever its `escaping` markers, or it is refused. The environment table is retained beside the argument table without copying, a null table meaning an empty environment, and an identical repeat must repeat all three carriers. A C-owned startup that drives public C-convention Landin routines calls it explicitly before `system.new()` or `blocking.new()` can mint an argument-table capability and before starting any thread that may do so. Merely importing `core/io` does not perform initialization, and file, stream and heap work, which needs no argument root, may run without it. Ordinary exports and callbacks never initialize, replace or reset this state. The host I/O and heap constructors are public, zero-argument library routines. Any ordinary hosted routine can call them; hosted argument services still require the startup described here. Constructor use is not restricted to the entry point or to a routine that received a capability argument. A routine's parameter list therefore records supplied capabilities, not an enforced upper bound on host I/O or allocation in its call tree [1660] [1680]. For a call tree that uses only its supplied providers, a caller can substitute an in-memory world or bounded allocator without changing that code. Establishing that premise requires inspecting the called code; a signature alone cannot establish it, including for code offered as untrusted. The first call requires a nonnegative `argc` and non-null `argv` and retains that exact pair as the one argument root. It allocates and copies nothing: the C owner must keep the `argv` table and every argument it names readable for the whole lifetime of every Landin world, view and callback derived from them. A later call with the identical count and pointer is harmless; a negative count, null table or attempt to replace either part of the established root traps. `system.new()` and `blocking.new()` trap before initialization. The published user table begins at `argv + 1`, its count is `max(argc - 1, 0)`, and indexed lookup traps on a null entry within that count. The compiler names no other host routine, except that a static Linux link enters the program at `platform/linux`'s `_landin_start` (D280). The public module `platform/libc` declares the C library beneath the hosted providers as ordinary `extern(c)` imports: `open`, `read`, `write`, `close`, `strlen`, `malloc`, `free`, `stat` and the calling thread's errno cell, with the constants and records whose values differ between systems selected by `compiler.os` and the C ABI. These are library declarations, not privileged language operations, and the compiler reserves none of their names. On Darwin and FreeBSD, `hosted/system` and `hosted/heap` reach the host only through them. On Linux they reach it through the public module `platform/linux`, which declares Linux's system calls in source as ordinary assembly blocks and owns the process entry `_landin_start` (D279); a hosted Linux executable links statically by default, with no C runtime or library, and `--link=libc` links C's runtime instead (D280). `hosted/system` turns descriptors and pointer-and-length argument views into ordinary values and maps foreseeable host failures onto declared atoms; it opens and closes files and names the streams but reads and writes none, so it is no world (D476). `hosted/blocking`, built over a system handle, reads and writes, and threads its `world(provider)` concept as the authority for opening files and touching streams [1660] [1680]. The required `world.write_some` reports counted progress for one attempt, with no transfer on failure and no host call for an empty slice. `world.same_file` follows path aliases and compares file identity before any destructive output open; a missing output returns false, while failed input lookup or other output lookup failures refuse. It assumes stable names, rather than providing race-safe output opening. D153 states these ordinary library contracts and their provider obligations, and D276 the boundary that replaced its compiler-emitted bridge. ### [1990] Firmware and machine directives have explicit target contracts D229 enables the constrained Cortex-M0 firmware path. The request selects `--target=cortex-m0 --firmware-entry=NAME` and an assembly or executable output. NAME is a source declaration in the entry module, not a linker symbol or a hosted `main` convention. It must identify one defined, nongeneric ordinary `() -> none` or `() -> noreturn` routine, or a naked `() -> none` routine, with no declared error outcome. Source duplicate names, missing entries, invalid signatures and duplicate request options are errors. Entry selection does not require `public`. A different explicit `link(symbol: text)` does not change which source declaration is selected. Hosted entry and linkage rules remain [1970]/[1975]. The image follows the profile the program's device description selects (D542, D543): its regions, where each part of the image is placed, its stack and its vector table. A program that imports no description is given the constrained reference profile, `platform/cortex_m/reference`: 32 KiB flash at zero and 16 KiB RAM at `0x20000000`, the initial SP `0x20004000`, aligned to eight bytes, the upper 4 KiB of RAM reserved for stacks, so static RAM ends no later than `0x20003000`. That is a constrained test profile, not permission to use a board's larger flash. The firmware request refuses a compiler-framed routine when its known frame alone, including saved registers and reserved homes, exceeds the selected stack reservation. This does not bound total stack use across calls or interrupts; those paths remain programmer obligations. The compiler creates the profile's vector image, as many words as its description counts, aligned to its length rounded up to a power of two and no less than 128 bytes, at its boot address (D545). An `rp2040-boot2` image begins instead with the description's second stage, the naked routine it marks `link(boot_stage)`, assembled into the 256 bytes before the table and sealed with the boot ROM's checksum in their last four (D587, D588). An `rp2350-image-block` image's table is followed directly by the IMAGE_DEF block its boot ROM searches the first 4 KiB of flash for (D637, D638). Its first two words are the initial SP and compiler reset function. The slots a handler may take are the profile's (D544): its core's architectural exceptions and 16 + IRQ for each interrupt its description names; every other slot is zero, which in the reference is core slots 4–10 and 12–13 and slots 21 and 42–47 of its 48. Other unspecified handlers enter the compiler's terminal unhandled-exception loop. There is no VTOR relocation, exclusive-access primitive or priority grouping. A Thumb-2 level selects its own instructions: hardware division (D255), the long multiply (D605) and, at `armv8-m.main`, acquiring loads and releasing stores (D606). With a float unit (D615) an exception taken in a float context stacks the extended frame (D618), and a fibre's context holds d8-d15 and FPSCR (D620); without one there is no FPU frame. On `rv32` (D660) the image begins instead with its entry word, `_landin_firmware_entry`, a jump to compiler reset, and the table follows at the first address its alignment allows, one jump per slot (D662, D686). Reset clears mstatus.MIE, writes mtvec as the core's interrupt model needs, sets sp to the stack's top, copies and clears as below, fences, sets MIE and calls the entry. A handler is entered through compiler-owned code (D680): a stub saves ra, t0-t6 and a0-a7 and calls an `extern(interrupt)` routine, which is an ordinary routine, and its unwind rules return to mepc; a naked routine is jumped to from a slot the hardware enters and owns its `mret`; there is no nesting. The unhandled loop first records mcause, mepc, mtval, the interrupted sp and a count in `_landin_firmware_trap_*` cells a probe reads as memory (D656). A description's stage runs from the entry word, before reset (D684), and an `esp-app-image` profile's executable is followed by the image its ROM loads, `OUT.bin` (D683, D685). Reset masks configurable interrupts, initializes reserved r9 and the root r11 to zero, and, when the description has a float unit (D615), gives CP10 and CP11 full access in CPACR followed by DSB and ISB, before anything can execute a float instruction, leaving lazy stacking at its reset default (D618). It then copies text and read-only data a description places in RAM (D1359), then initialized RAM data and RAM code, each from its load address, skipping a copy whose source is already its destination, and clears BSS. `--firmware-layout=ram` derives an in-place SRAM image instead of the default boot image (D900); a debugger establishes the core and device state before entering its startup. DSB and ISB precede unmasking and transfer to the selected entry. It does not call user module initializers [1460]/[1940], construct a hosted environment, allocate memory or run a scheduler. This reset contract assumes execution through the hardware reset vector, with no NMI or fault during initialization; a custom NMI/HardFault handler cannot assume initialized storage before reset has completed it, nor, where reset copies the text, that its own code is there yet. D232 routes ordinary entry return and failed language checks to the selected panic handler, or the terminal default. Naked fallthrough retains its undefined-instruction guard. Hardware faults retain hardware fault dispatch; no failure is returned to a nonexistent hosted caller. `none` remains absence of a result, not the distinct `noreturn` return form (D231). `extern(interrupt)` and `extern(naked)` are distinct structural function conventions, separate from ordinary and C functions. Definitions are nongeneric, have exactly `() -> none`, and declare no error set. Machine conventions are also available in function types. Values retain that exact convention through assignment, parameters, aggregates and generic matching. Taking their function value is allowed; converting to ordinary/C convention or calling it with ordinary source call syntax is refused. A vector reference is a machine entry, not such a call. Interrupt bodies may call ordinary functions and must handle any declared failure locally. Traps still trap. There is no implicit keep attached to either convention. On exception entry ARMv6-M saves r0–r3, r12, incoming LR, return PC and xPSR on the interrupted stack, adding the architectural alignment word when needed. With a float unit, an exception that interrupts a context with an active float state stacks ARMv7-M's extended frame, s0–s15, FPSCR and a reserved word as well, whose space is reserved and filled lazily (D618). Handler mode uses MSP; thread mode may use MSP or programmer-established PSP. Ordinary and interrupt routines preserve each r4–r7 register their emitted instructions use, and with a float unit d8–d15, which only an assembly block can name, so a framed routine that holds one saves all eight (D617). An ordinary routine with no calls, no inline assembly, and no transient stack changes may use SP-relative homes, leave r11 and LR untouched, and save only the low registers it uses. Other routines construct a previous-r11/incoming-LR eight-byte record before publishing r11; they also save the low register used to carry r11 and round the low save area for eight-byte call alignment. r8 and r10 are untouched, r9 remains reserved, and a published r11 is restored. Incoming LR in an interrupt record is EXC_RETURN, not a code address. The epilogue uses BX LR; the hardware restores volatile state, flags and the interrupted stack. `0xfffffff1`, `0xfffffff9` and `0xfffffffd` are respectively supported returns to a handler, a thread using MSP, and a thread using PSP; with a float unit `0xffffffe1`, `0xffffffe9` and `0xffffffed` are the same three returns from an extended frame, and the epilogue's BX LR takes either. The NVIC implements four programmable priority levels (the upper two priority bits), with fixed NMI/HardFault priorities and no priority grouping. Higher-priority interrupts may nest; same/lower priority ones remain pending. PRIMASK masks configurable exceptions, not NMI/HardFault or DMA. The compiler adds no interrupt masking around source memory events. Eight-byte alignment at ordinary calls, callee saves, no red zone and the private r12 zero-success/nonzero-failure outcome are unchanged. Zero is not added to any ordinary source atom domain. A naked body consists of one `assembler.block` statement. It has no compiler frame, saved registers, local bindings, ordinary source calls, source branches, cleanup or implicit return. Its text may contain labels, explicit branches and machine return instructions; an appended trap handles fallthrough. The programmer owns stack selection, alignment, callee saves, r9/r11 obligations, LR/EXC_RETURN and any calls written in the assembly. A naked selected entry runs after compiler reset initialization; it does not replace the reset loader. This is the explicit exception to [1550]'s frame guarantee. It does not permit an ordinary routine to omit its frame. `assembler.block` takes a quoted or raw fixed text literal in a routine body, optionally followed by operands [1630], and nothing else: D1662 removed the positional value that once followed the text, and the parser refuses one, which the grammar derives as an ordinary argument. The fixed text is not a runtime argument. D248 records the operand form. [1820]'s `arguments` derive operands after any call's positional arguments, because which callee a name denotes is not the grammar's to say; the checker refuses them on every call but `assembler.block`. A module tool directive takes expressions only. An operand is `in name: type at register = expression`, `inout name: type at register = expression`, `out name: type at register` or `out _ at register`. Its name is its `{name}` template slot and, for an output, its result field; it declares nothing any scope can see, and two operands of one block cannot share a name. Its type is an exact enabled integer scalar no wider than one register of the target, or `f32` or `f64` (D630): not bool, a pointer, a distinct type or a type formal. An integer is placed at an integer register or `general`, a float at a float register or `float`, and a profile with no float registers refuses a float operand. An input is evaluated once, in written order, before the block, in the declared type's context; a narrower integer is zero- or sign-extended to the full register as its type says, and a float occupies its register's low bits at its own width. An output takes the low bits of its register. `inout` passes its input in and its output out of one register, and its output has its input's type. A block with no named output is `none`; with one, it is that output's scalar; with more, it is the anonymous aggregate of [0990] whose fields are the named outputs in written order. Binding, assignment, destructuring, discard [1020] and D244 treat that value as they treat a call's. A register is a name the selected target's table answers for, never text: | | Cortex-M0 | Hosted x86-64 | Hosted arm64 | RV64 Linux | RV32 | | --- | --- | --- | --- | --- | --- | | instruction text | ARMv6-M unified | AT&T | GNU or Apple arm64 | GNU RISC-V | GNU RISC-V | | integer operand registers | `r0`–`r7` | `rax` `rbx` `rcx` `rdx` `rsi` `rdi` `r8`–`r15` | `x0`–`x17`, `x19`–`x28` | `x5`–`x7`, `x9`–`x31` | `x5`–`x7`, `x9`–`x31` | | `general` chooses from | `r0`–`r7` | `rax` `rcx` `rdx` `rsi` `rdi` `r8`–`r11` | `x0`–`x17` | `x5`–`x7`, `x10`–`x17`, `x28`–`x31` | `x5`–`x7`, `x10`–`x17`, `x28`–`x31` | | float operand registers | `d0`–`d15` with an FPv5-D16 unit (D615), else none | `xmm0`–`xmm15` | `v0`–`v31` | `f0`–`f31` | none | | `float` chooses from | `d0`–`d7` with the unit | `xmm0`–`xmm15` | `v0`–`v7`, `v16`–`v31` | `f0`–`f7`, `f10`–`f17`, `f28`–`f31` | none | | every ordinary block overwrites | `r0`–`r7`, flags, and with the unit the `float` row and FPSCR's flags | the `general` and `float` rows, flags | the `general` and `float` rows, flags | the `general` and `float` rows | the `general` row | | saved by the routine when a block names one | `d8`–`d15` with the unit | `rbx`, `r12`–`r15` | `x19`–`x28`, `v8`–`v15` | `x9`, `x18`–`x27`, `f8`, `f9`, `f18`–`f27` | `x9`, `x18`–`x27` | | never named | `r8`–`r15` and their aliases, `sp`, `lr`, `pc`, `msp`, `psp`, `control` | `rsp`, `rbp`, `rip` | `sp`, `fp`, `lr`, `x18`, `x29`, `x30` | `x1`–`x4`, `x8` and their aliases; `x0` by an operand | `x1`–`x4`, `x8` and their aliases; `x0` by an operand | A fixed register is its full-width name; `general` and `float` are the two classes, spelled the same on every target, and each asks the compiler to choose a register of its row it does not otherwise name in the block. Every register an operand names is distinct from every other, and a block cannot ask a class for more registers than it has left once its fixed registers and every register its text names are set aside; the two classes count apart. Every ordinary block may overwrite the overwritten row; a register the routine saves must be declared, as an operand or as `out _ at register`, which is what makes the routine save and restore it. A discarded output names one fixed register. The text writes `{name}` where an operand's register belongs, spelled at the width its type selects (`%eax` or `%rax`, `w9` or `x9`, `r3`; RV64 and RV32 use their full-width `xN` name for every enabled integer width; a float register is `%xmm3` at both widths, `s3` or `d3` on arm64, `f3` on RV64, and on a Cortex-M float unit `s6` for an `f32` at `d3` and `d3` for an `f64`); `{{` and `}}` are literal braces. Every `{name}` must name an operand, every `general` operand must be written in the text, and every register the text names at any width must be declared or overwritten and never be one no block names. Frame pointers, stack pointers, link registers, the platform register and Cortex-M0's reserved r9 are therefore never named, and no register is reserved by the language beyond them. RISC-V's `x0`, `zero`, reads as zero and discards every write, so an ordinary block's text may name it as a source or a destination, as in `sw zero, 4(t0)` or `csrrw zero, mscratch, zero`; no operand names it, since an input there would be lost and an output would read zero (D1320). arm64's `v8`–`v15`, whose low halves AAPCS64 preserves, and RV64's `f8`, `f9` and `f18`–`f27` (`fs0`–`fs11`) are declared as the saved integer registers are, at whatever width the text names them: `d8`, `s8` and `q8` are all `v8`, x86-64's `ymm3` and `zmm3` are `xmm3`, and on a Cortex-M float unit `s16` and `s17` are the halves of `d8`, one of the eight its routine saves. RV64 and RV32 operands use canonical `xN` and `fN` names, while raw text may use the ABI's `a`, `t` and `s` aliases and their float `fa`, `ft` and `fs` forms. An alias identifies the same register for declaration checks and exclusion from a class, so naming `s1` requires declaring `x9` and naming `fs0` requires declaring `f8`. The private failure registers are overwritten: a failure outcome is copied out as its call returns and is never live across a block. Every block is a conservative read/write, call and trap boundary in IR, on every target: memory knowledge is invalidated and memory operations cannot be moved across it, and it runs exactly once each time it is reached, never removed, duplicated or merged, in order with other blocks, volatile accesses, atomics, barriers and calls. The memory effect is fixed; no block declares a narrower one (D248). This compiler boundary alone issues no hardware barrier and establishes neither device completion nor cache coherence. D227's external-writer obligations remain. The text is at most 4096 decoded ASCII bytes, or 32768 in a naked Xtensa body (D903), using LF, horizontal tabs and printable characters. Every rule below reads a line without the blanks and tabs around it (D1054). A line may end in the selected target's own line comment, from its marker to the end of the line: `@` on Cortex-M0, `//` on arm64 and `#` on x86-64, RV64, RV32 and Xtensa, the spelling that target's GNU or Apple assembler reads (D597). In an ordinary and a naked block alike the comment is removed before any other rule reads the text, so nothing in it is an instruction, a register, a label or a `{name}` slot, and the emitted assembly does not hold it. Every other comment form is refused, naming the target's own: `/*`, another target's marker, and on Cortex-M0 and arm64 a line that begins with `#`. A number is the assembler's syntax and takes no digit separator; the refusal names the number to write. Directives, statement separators, labels and symbol assignments are refused in an ordinary block, which is straight-line: it cannot branch, call, return or change control mode, on x86-64 behind an instruction prefix or in a far form either (D1117), except that Cortex-M0 `svc` enters the SVC exception handler at vector 11. That handler decides whether execution resumes after `svc`; this exception does not admit other control transfers in an ordinary block. At the default `armv6-m` level the accepted spelling is a bounded subset of ARMv6-M unified assembly; its instruction allowlist is an implementation limit, pinned by the machine checks. At the Thumb-2 levels, `armv7-m`, `armv7e-m` and `armv8-m.main`, the checker retains the text and straight-line restrictions, and the assembler enforces the selected architecture's instruction set. `UDF` and `BKPT` are refused in ordinary blocks at every level because they enter exception handling. Naked blocks additionally admit labels, branches, BL/BLX/BX, PUSH/POP, UDF and the MSP/PSP/CONTROL system registers, and take no operands. CPS changes PRIMASK at every level and may change FAULTMASK at a Thumb-2 level; barrier operands are `sy` or omitted. BASEPRI and FAULTMASK system registers are available at those higher levels. Unsupported system registers remain refused. On hosted x86-64, arm64 and RV64 the checker refuses control transfer by mnemonic and leaves which instructions exist to the platform assembler. The system call, x86-64 `syscall`, arm64 `svc` and RV64 `ecall`, returns to the next instruction and is not a control transfer there (D281). RV32 reads RV64's rule, except that firmware's `wfi` resumes at the next instruction and is admitted, and its `ecall`, an exception that enters the unhandled loop, is refused (D670). Unencodable operands and instructions remain explicit assembler failures under the pinned flags, never a target upgrade. Assembly must not overwrite compiler spill or frame storage, saved registers or immutable source storage through an indirect address, leave the stack pointer changed, on x86-64 leave the direction flag set, or leave a float unit's rounding mode or exception flags other than it found them: x86-64's MXCSR, arm64's FPCR and FPSR, RV64's `fcsr` and a Cortex-M float unit's FPSCR (D630). An instruction's implicit register effects are the programmer's to declare, as `cpuid`'s write of `rbx` is. Arbitrary machine text cannot prove those obligations. This compiler lowers ordinary assembly on every implemented architecture. The shorthand form retains its Cortex-M contract, and naked routines retain theirs on Cortex-M. Naked routines are admitted on hosted x86-64, arm64 and RV64 as well: their text is verbatim, keeps the uniform text rules but may transfer control, takes no operands and is followed by a trap (D279). The synthetic target has no registers and refuses assembly outright. Placement is a declaration annotation: `link(section: text, align: integer, vector: integer, keep, symbol: text, region: text)`. Only supplied attributes apply, and duplicate attributes/annotations are errors. Section names are at most 80 ASCII letters, digits, underscores or dots, with a nonempty suffix. Functions select `.text.*` (flash) or `.ramtext.*` (RAM execution with a flash load image, in a region code runs in, D688); immutable data selects `.rodata.*`, mutable data `.data.*` or `.bss.*`. An explicit BSS initializer must be `zeroed` or the integer literal `0`. Compiler `.landin_` section names are reserved. Alignment is a decimal power of two from 1 through 256 and is a minimum placement alignment; type layout and `alignof` do not change. Alignment and vector indexes use decimal integer literals, with the ordinary digit separators allowed; nondecimal prefixes and computed expressions refuse. Without a section annotation every datum/routine has its own input section; mutable zero images use BSS and immutable images use flash. `keep` marks the containing input section as a retention root. Naming the same section deliberately coalesces its objects, and keep on any of them retains that section. Relocations from retained sections retain their targets. Unreferenced sections are garbage-collected. Symbol linkage does not itself retain a section. Cortex module data may give one explicit ASCII identifier as its symbol; symbols cannot collide with other explicit declarations or compiler startup/private Arm helpers. Function symbol spelling retains [1975]'s existing rules. Ordinary and C aggregate layout do not change. `vector: N` associates a defined interrupt/naked routine with one unique exception slot the selected profile implements (D544): in the constrained reference 2, 3, 11, 14, 15, 16–20 or 22–41. Slots are absolute vector indexes, not IRQ numbers; external IRQ n is slot 16 + n. `region: text` places the declaration in a region of the selected description (D547), and `boot_stage` marks a description's second-stage boot routine, which its boot kind places (D587). Zero, reset, reserved slots, duplicates and ordinary/C routines are refused. Emitting such an annotation requires an explicit firmware-entry request. The compiler-owned kept vector image carries a relocation to the handler; an unreferenced interrupt routine without keep can still disappear. Thumb function relocations retain bit zero; data addresses are not tagged as code. Linker-defined startup addresses distinguish load from execution locations. Existing static function/text-address images remain relocations, not calls or user-code initialization. The compiler does not enable an arbitrary source initializer referring to a linker symbol; fixed assembly can name the documented `_landin_firmware_*` startup symbols. Executable emission retains assembly, object, compiler-generated linker script, ELF and map as explicit outputs; `--linker-script=FILE` links with a developer's script instead, held to D546's contract. The driver passes each host effect through `Landin.Platform`, checks output/source aliases before writes, uses ARMv6-M Thumb/AAPCS soft-float assembler flags with fatal warnings, and links with no hosted startup, default libraries or libc. Only the selected private `thumb/v6-m/nofp/libgcc.a` helper closure is admitted. This does not enable the general C source surface. The derived script checks flash bounds, static RAM/stack overlap and the vector address/size; unresolved symbols and relocation or encoding failures remain reported tool failures. Before emission the program's static images are held to the selected profile's capacities (D537): every written image, including one section GC would drop, to the region text is placed in, 32 KiB in the reference, or the vectors' when reset copies the text (D1359), and every mutable written image to the data region, 16 KiB in the reference. The linker stays the authority for the map itself. Hosted placement annotations, arbitrary section addresses, weak symbols, inline hints and general tool directives remain explicit refusals. No request is silently ignored. ### [1995] A stack switch resumes another stack, and every frame checks its stack [1675] teaches fibres through `core/fibre` and leaves unsaid what the two stack builtins under it do, where a fibre may lose the core and what a routine owes the stack it runs on. `compiler.stack_prepare(stack, entry, argument)` takes a `[]mut u8`, a function value of type `(argument: usize) -> noreturn` and a `usize`, and gives the `usize` stack pointer a later switch resumes. It aligns the top of `stack` down to the target's call alignment and lays a first frame that, when resumed, calls `entry(argument)`, ends the frame-pointer chain and its unwind information there, and holds the stack's limit: the slice's base plus the target's margin. A slice too small for that frame and the margin traps `stack_exhausted`. `compiler.stack_switch(save, resume)` takes a `ptr mut usize` and a `usize`. It saves the callee-saved registers, the frame pointer and the current stack's limit on the current stack, stores the stack pointer through `save`, resumes the context `resume` names with its limit, and returns when something resumes the saved one. Each evaluates its arguments once, left to right (D450, D472). On Cortex-M0 a prepared stack runs on the process stack pointer and the saved context records which stack pointer it resumes (D460). Both are admitted on every target with a native backend and on no other; an argument outside this contract, or a target that does not admit them, is L0344 (D453). A switch is a full compiler memory boundary: no ordinary access is carried across one in a register. A fibre gives the core away only inside a call to an entry of the provider that runs it, and a provider states which of its entries may switch; one that does not wait never does. The fibres of one provider are one CPU execution context in D227's sense, a switch is sequenced-before within it, and a fibre does not move between threads. Threads are not a provider of `core/fibre`'s concepts (D446). In a program whose whole program holds a `compiler.stack_prepare`, every ordinary routine compares the stack pointer less its frame with the current stack's limit after its frame record and before it reserves its frame, and below it traps `stack_exhausted` at its declaration's site, with nothing of its frame written; a call area larger than the target's unchecked figure is checked the same way. The stack the program started on has no limit. A call-free routine whose frame is within the unchecked figure, a naked routine, the selected panic handler and, on Cortex-M0, an interrupt handler are not checked; the margin pays for what runs below a checked frame (D471, D472). A program with no `compiler.stack_prepare` has no check, and its code is unchanged. `stack_exhausted` is `core/panic`'s fifth kind, and D232's handler takes the five-atom domain (D451). The current stack's limit is the running thread's: on Linux and FreeBSD a word of its thread storage [1996], on Darwin the slot of a pthread key the program makes before Landin code runs and reads directly, and on firmware one cell (D497, D506). A thread whose limit is zero, the one the program started on and a C thread calling into Landin, never traps until a switch installs a prepared stack's. On static Linux the routines that make the first thread's storage, platform/linux's `_landin_start...`, run before the thread has a thread pointer and are not checked (D504). Off Linux, the default report claims one latch before it moves to the report stack that every thread shares, and a thread that finds the latch claimed writes nothing and waits for the process to end (D498, D507). ### [1996] Each thread has its own instance of thread storage [1610] and [1640] say what a link annotation names and places, and nothing of threads. `link(thread)` before a module binding gives it one instance in every thread (D496). A thread's reads and writes, its `addr` and its `inout` arguments reach that thread's instance and no other; the instance begins zeroed when its thread begins, so the binding is `mut`, takes no value and has a type with a zero image (L0347, L0328). It places no routine and takes no `symbol` or `section`, which would name or place one instance for every thread (L0347). Every name of a shared binding is placed. On a hosted target the instance is in the system's thread storage: ELF thread-local storage in the local-exec model on Linux and FreeBSD, laid by platform/linux's start in a static Linux program and by the C library otherwise, and Darwin's thread-local variables. On firmware it is ordinary module storage, which interrupt handlers share as they share any. An instance's address is valid while its thread runs, which is as long as any frame of that thread lives, and the origin rules treat it as a module binding's: it may be passed, returned and kept in the thread's frames, and in its thread storage only as an integer, since thread storage holds no pointer (L0328). A store of it, or of a reference the body took from it, into a module binding without `link(thread)` is refused, since every thread reads that binding (L0314, D772). Keeping it anywhere else another thread reads it after the thread has ended is the program's to avoid, as for any pointer a thread hands another (D505). ## THE DECISIONS THIS DOCUMENT TOOK A rule above is one of two things, and a reader cannot tell them apart by reading it: a transcription of something `tour.md` already decided, or a decision taken because the tour said nothing and an implementation could not proceed without one. The decisions are listed here with what the tour said before, what was chosen, and what a competent reader could have chosen instead — because a decision written in the same voice as a transcription looks like it was always there, and [1050] was missed twice by a reader who assumed exactly that. A decision leaves this register only when new evidence closes it: a program that cannot be written, a target that cannot be reached, or a paragraph of the tour that turns out to have settled it after all. Completed implementation does not remove a decision, because its alternative and fixture remain useful review evidence. The history records the delivered vertical slice; this register does not repeat its implementation diary. The register is the fourteen sections that follow, and they are the subjects `tour.md` teaches, in the order it teaches them, so a question about arrays is answered in one place whichever document it is asked of. It was chronological until the documents were reorganised by subject, which is why the numbers now run out of order: D1 and D2 are scope decisions and sit beside D233, which was taken far later. Within a section, too, related decisions sit together whatever their numbers. A heading is a stable citation target, and nothing that cites one has to know where it sits. ## DECISIONS: DECLARATIONS, NAMES AND SCOPES What a declaration introduces, which scope holds it, and which words no declaration may use. ### D1 — A named return lives in the signature scope **The tour said** that a named return is assigned like any other place and that `return` leaves [1810], and that every named return must be assigned before the function returns [0930]. Neither says which scope declares it. **Chosen:** the signature's, beside the parameters [1840]. So `f: (r: u32) -> (r: u32)` is one name declared twice in one scope, and the body can assign the return from inside any arm. **The alternative:** the body's scope. Then a parameter and a return could share a name, and the body would shadow the return rather than assign it. **Pinned by** `negative/return-shares-a-parameter-name`. ### D2 — Each arm of an `if` is its own scope **The tour said** nothing. [0140] permits an inner scope to shadow an outer name and [1090] says a bare block is for scoping, but a bare block is not in the kernel and no paragraph says an arm opens a scope. The sentence that now says so is in [1840] and was written here. **Chosen:** every arm and the `else` is a scope, and they are siblings. A name declared in one arm is not visible in another, nor after the branch closes. **The alternative:** one scope for the whole body, so a binding in an arm outlives it. Defensible, and it is what a language without block scoping would do — but then two arms could not use the same local name, which is the commonest thing a branch does. **Pinned by** `positive/arm-scopes-are-siblings`, `negative/name-from-another-arm`, `negative/name-after-the-branch-closes`. ### D10 — A module binding with no value holds zero **The tour said** that a binding may carry no value and must be assigned before use [0080], and that values at module level must be known at compile time [1460]. Neither says what one with no value holds, and the two do not combine: [0080]'s "before use" is a rule about paths through a body, and [1460] says nothing runs before the entry point, so at module level there is no path and no moment in which an assignment could happen. **Chosen:** zero, and false for a bool [1940]. Reading one before anything writes it reads zero. `positive/binding-declared-only` stays a positive fixture, and `mut counter: u32` is module state a function updates. **The alternative:** two, and both were defensible. Refuse a module binding with no value, on the strict reading that no value is not a known value — which is tidy, and costs `mut counter: u32 = 0` at every declaration of module state, where the `= 0` says nothing a reader did not know. Or keep the declaration and refuse the read, which is [0080] taken literally — but at module level "before use" is a question about which function runs first, and that is a whole-program analysis this specification does not have and the kernel is not equipped to answer. **Pinned by** `positive/binding-declared-only`, `positive/module-binding-with-no-value-reads-zero`. ### D218 — A local's written type precedes its own name **The tour said** that the left of `:` introduces the name and the right supplies its type or value [0110]. [1840] explicitly put the initializer before the new binding. It did not settle the written type's lookup scope; the ordinary-local implementation installed the name first, unlike D185's condition-binding implementation. **Chosen:** an ordinary local's written type and initializer both resolve in the incoming lexical scope, before that local is introduced. This includes names nested inside reference types, fixed-array bounds and generic actuals, and applies with or without an initializer. A local may therefore shadow an enclosing type or fixed formal while using it in its own declared type. `mut t: t = value` uses the enclosing `t` for the type; following statements see the new runtime binding. An absent enclosing name is still unknown, and an already declared local in the same block still makes a duplicate. This agrees with D185's condition bindings. It does not change collected module or signature scopes, enable local type declarations, or make a name visible in its own initializer. A generic body resolves the outer type/fixed formal's identity before concrete substitution, just like its other uses. **The alternatives:** introducing the local before resolving its type makes its spelling hide the very type or fixed bound being declared. Retaining that rule only for ordinary statements makes the equivalent condition binding behave differently. Resolving all names against the enclosing block would instead lose earlier locals from the incoming scope. All are declined. **Pinned by** `positive/r491-local-type-scope`, including a generic list-element copy derived from prototype 3, `negative/r491-local-self-reference`, `negative/r491-local-self-initializer`, `negative/r491-local-shadowed-type`, `positive/condition-declarations` and `negative/condition-declaration-body-shadowing`. ### D225 — Control words are reserved everywhere **`complete` and `with` withdrawn by D1651.** Both left the keyword production with the forms that used them, and are ordinary names; the rest stands. **The discrepancy:** [1760] reserved `if`, `then` and `end`, while other already enabled control forms still used identifier tokens. An earlier review repair first fixed declarations and assignments under that contextual contract, but ordinary expression reads remained ambiguous. The intended language rule is that a control word cannot also be an identifier. **Chosen:** add `begin`, `break`, `complete`, `continue`, `defer`, `do`, `for`, `loop`, `match`, `unchecked`, `undo`, `while` and `with` to [1760]'s keyword production. Each is reserved in every name position, regardless of whether its control form appears in the program. Parentheses provide no escape. `begin = 10` is illegal; an ordinary binding must use another name, such as `begin_value`. Existing block, match, loop, transfer, completion and cleanup semantics are unchanged. Other contextual words, including `of`, `caller`, `range` and `arena`, retain their existing rules. **The alternatives:** contextual control-word priority plus a parenthesized name escape preserves dual meanings, while broader contextual lookahead must resolve genuinely ambiguous expressions. Reserving the words removes both problems at the lexical boundary. Existing declarations using these words must be renamed; this compatibility change is explicit and supersedes the earlier contextual-name repair and the matching part of D187. **Pinned by** `negative/r491-reserved-control-assignment`, `positive/r491-contextual-statements`, `positive/r491-bare-block-examples`, and the parser case `control words are reserved`. The bounded case covers all thirteen tokens, longer identifiers and forbidden declaration, parameter, result, field, label, member and parenthesized-name positions. The derived parser, container and hosted prototype controls retain their control-flow and cleanup contracts; reservation adds no execution or aliasing rule. ### D233 — A shared declaration is one declaration per name, with one initializer evaluation **Superseded by D1656 for bindings, fields and atoms.** Each names one thing; a parameter, named-return or payload list keeps the shared form, with the written prefix and type applying to each name as below. **The tour said** that several names may share one declaration, the same form field lists already use [0100], and showed `public red, green, blue: u8` beside an atom list. Atom lists were enabled; shared bindings, fields, parameters and returns were refused by name until the initializer and convention questions their implementation needs were decided. **Chosen:** `binding`, `field`, `parameter` and `named_return` take [1740]'s `identifiers` list where they took one name. A shared declaration means the declarations written one per name, in written order, each carrying the complete written prefix — `public`, `mut`, `link(...)`, `caller`, `escaping`, `in`, `inout` or `sink` — the same type and the same suffix, `at` or `from`. A prefix applies only when written before the first name, so `(a, inout b: T)` is not a shared parameter. An initializer is evaluated once, as the first name's; each later name is initialized with a copy of the first name's value, so `mut low, high: u32 = next_seed()` calls once and leaves two independent places. A module declaration without a value holds zero for every name (D10); with one, the later names copy the first name's static image. The type, `at` bounds and `from` sources are written once and checked once: a type that names nothing is one report and two packed fields at one position are one overlap. Debug information lists every name as the ordinary variable, field or parameter it is. Two parsing rules follow from the list. A comma followed by names that reach `:` starts the next named return rather than extending a `from` list, because [0110] makes the name left of `:` the one being introduced. A run of names ending at `:` or `:=` begins a binding where [1800]'s one-token lookahead decides between a statement and a value. The shared form needs a written type. `a, b := e` stays L0010 citing [0100], because it reads as a destructuring [1810] and nothing written once could be shared. A condition binding (D185), a type declaration, a type or fixed formal, a function and a variant part keep one name each and meet the same L0010. These are recorded boundaries, and the second note says "this is a recorded source-form boundary". **The alternatives:** evaluating the initializer once per name, as though the declaration were retyped, was declined: an expression written once runs once, as [0560]'s repeated expression already does, and duplicated side effects would be invisible at the one place they are written. Refusing initializers on shared declarations was declined as less useful for no less work. Applying a convention only to the name it precedes was declined because `(a, inout b: T)` would then hold two conventions in one list, while [0100]'s field-list reading gives every name the whole prefix. Admitting `a, b := e` with a copied inferred type was declined for the destructuring reading. **Pinned by** `positive/shared-names-in-lists`, `runtime/shared-declarations-evaluate-once`, `negative/r491-shared-declaration` and `negative/shared-type-names-nothing`. `negative/shared-packed-fields-overlap` and `negative/shared-link-symbol-duplicates` pinned shared fields and bindings, and left with them (D1656). ### D1656 — One name per declaration: `a, b: T = v` leaves **The tour said** at [0100] that `a, b: T = v` declares each name with its own copy of one value, and D233 made it one declaration per name with one evaluation of the initializer and a shared `mut` warning. The library and the bindings write none. **Chosen:** the form leaves. Each name is declared on its own line, which is what [0100] already said it meant; D233's one-evaluation rule and its shared warning go with it. A parameter, result or payload list keeps its own form. The maintainer chose this on 2026-11-21, answering the candidate list the third roadmap's simplification phase decides. **The alternatives:** keeping it for atom lists in examples, three lines that read as well written out. Declined. **Pinned by** `negative/one-name-per-declaration`, whose fix writes a line a name for an atom list, a module and a local binding and a struct field (D1887, D1888), and `positive/shared-names-in-lists`, the lists that keep the form. D233 is marked superseded for what leaves. ### D1887 — An atom list and a struct block's fields name one thing each **The tour said** at [0100] that several names may share one declaration "as fields in a struct already do", with `north, south, east, west: atom` among its examples. D1656 named bindings and kept parameter, result and payload lists, and did not say which of the two a struct block's field line or an atom list is. **Chosen:** both leave with the bindings. A struct block's field line and an atom declaration are declarations, a name a line like every other, and only the three lists D1656 keeps write `a, b: T`; the declined alternative it records was keeping the form for atom lists. The refusal and its fix are the binding's. **The alternatives:** keeping shared field lines and atom lists, which leaves the form in two places D1656's reasoning covers. Declined. **Pinned by** `negative/one-name-per-declaration`. ### D246 — A refusal by name says what the form is, not which work decided it **The discrepancy:** [1830] required a named refusal's second note to say "which work enables it", and every note printed `ROADMAP.md` and a work item of the first roadmap, followed by what the item did: recorded the boundary, withdrew the form or transferred it. By the time the first roadmap closed no note was a promise any more. Each named a finished item that had recorded a boundary, withdrawn a form or transferred one to a successor, so the item told a reader nothing the rest of the sentence did not. Pointing at `ROADMAP.md` for it pointed at a file that no longer holds that item's text. D190 had already had to move one refusal's item by editing a string, and D196 another, because an item finishes long before the diagnostic that names it stops being printed. **Chosen:** the second note states what the refused form is: "this is a recorded source-form boundary", "this form is withdrawn; " followed by what replaces it, or "this is transferred to Language evolution". The compiler records that as a standing in each refusal table, a recorded boundary, a withdrawal or a transfer, in place of the item it named, and the Report body writes the note from the standing alone. The first note, the paragraph, the codes L0010 and L0304 and every primary message are unchanged. The construct inventory holds each row with a refusal to explaining it in the row's own disposition, and a transferred refusal's row to naming the successor. **The alternatives:** keeping a pointer that outlives its item was declined for the reason above. Naming the decision, D212 or D236, in place of the item was declined: a decision is stable, but it is the reason for the refusal and not what the refusal is, and a reader who wants the reason reaches it from the paragraph the first note names. A fourth standing, "pending", for a construct the kernel will enable was left out because no refusal is one. If one is added, its note says the construct is not enabled yet, and which work enables it stays `ROADMAP.md`'s to say. **Pinned by** `negative/r491-shared-declaration`, `negative/arena-block-names-owner`, `negative/arena-type-names-owner`, `negative/r491-volatile-pointer`, `negative/refused-widths-name-their-owner`, `negative/r740-parameterized-application-boundary` and `negative/cortex-refused-type-named`, whose recorded reports carry the notes, and the parser case `shared declarations have a named refusal`. ### D251 — A warning is the compiler's, never the language's **The discrepancy:** [1850] says a rule that permits something does not also warn about it, and nothing in the language defines a warning. The catalogue has had a warning severity since the first slice and no code used it. A lint is a judgement the language does not make; the risk of one is a second opinion that disagrees with the rules, or a verdict that depends on it. **Chosen:** a warning is a catalogued code at warning level, raised by the compiler and never by a rule of the language. By default it never refuses a program: the exit status stays 0, and an accepted program is emitted exactly as it would be without it. The observation must follow from facts the compiler already established; an automatic edit is a separate claim. An exact fix is offered only when the compiler can prove that applying those edits preserves meaning and does not swallow comments or neighbouring source. Otherwise the warning carries its observation and explanation without a fix. Shadowing is never warned about, as [1850] says; D1342 later warns of a declaration that takes a predeclared type's name, which hides no declaration of the program's. Invocation policy lives in `refine check` and `refine compile`, not in source syntax. `--warnings=default|all|none` chooses a baseline. `default` selects the compiler's recommended warnings, `all` selects every warning, and `none` selects none; the two current warning families are both recommended, so `default` and `all` currently agree. Repeated `--warn=CODE|all`, `--allow=CODE|all` and `--deny=CODE|all` respectively enable, suppress and enable with error severity. The baseline is applied first, wherever it is written; subsequent controls are applied in their written order, and the last matching control wins. A code must name a live warning in the catalogue: language errors cannot be suppressed or downgraded. A denied warning fails the invocation with status 1 before artifact production or native tool execution. Its diagnostic retains its code, locations, notes and fixes, and identifies the command-line policy that promoted it. This is a consumer's acceptance policy; the program remains legal Landin. A normally enabled warning has status 0 and does not change generated bytes. Quiet mode only controls progress and does not select warnings. The language server uses the recommended warnings; command-line controls belong to compilation requests and are refused for formatting, queries and server startup. The first warning is L0326: a local binding declared `mut` [0060] that no assignment, step, `inout` argument or mutable view needed, found where the checker's own [1900] check answers from that `mut`. Its fix removes `mut` and the blanks after it, never a comment or a line end, and is offered only where those bytes are all that separate the word from the name. Other spacing still permits the warning, without a fix. A shared declaration [0100] is warned about only when none of its names needed `mut`, because one word serves them all. A module binding is never warned about, because a linked routine or a debugger may write it. The warning runs only on a program the checker accepted and only in a routine body it checked, so an uninstantiated generic says nothing. L0349 warns about an unused immutable local whose initializer is a direct integer, float, character or boolean literal, including a single negation of an integer or float literal. The checker finds no resolved reference to the binding and offers deletion of its whole line as an exact fix when the binding is alone on that line and has no attached doc comment. Other layouts and commented declarations still warn, without a fix. It does not warn on a shared declaration and only examines a checked routine body. Calls, names, aggregate construction and other expressions are excluded: deleting those could remove work. A module binding is excluded for the same external-use reason as L0326. **The alternatives:** no lints at all, which [1850] reads as. That leaves the compiler unable to say what it knows about a program it accepts, and pushes the judgement into a second tool whose rules drift from the checker's. Unused imports were declined as a first lint: an import adds its module to the program and its conformances to the one register [1280], so removing one can change what the program means. Unused immutable locals with an initializer that may do work are still declined: quieting one by adding a discard [1930] would judge that work as wasted. A direct scalar literal has no such work, and deleting its unused declaration is an exact repair where the layout permits one. Requiring every warning to include an edit was the original policy. It hid the same observation when a comment or layout prevented a safe repair. Advisories and explicit invocation controls separate those concerns. Numeric warning levels were declined: they suggest a confidence ordering that these independent checks do not have. In-source suppression was not added: the initial controls belong to the invocation and change no language syntax. **Pinned by** `negative/mut-never-written` and `negative/unused-pure-local`, which apply the fixes and compile the results clean; `negative/warning-advisory` and `fixes/advisory warnings preserve source`, which report without editing comments or multiline declarations; the command and native CLI policy checks; and the `codes:` of every accepted fixture whose program warns. ### D254 — A doc comment is the run of lines directly above a declaration **From** [0030] and [1780]. **The tour said** that a doc comment attaches to the declaration that follows it, and nothing about what "follows" means when a blank line, another comment or code comes between, or when two doc comments are stacked. Nothing read a doc comment until an editor asked what a name was. **Chosen:** [2000]. The run of doc comment lines directly above the line a declaration begins on, read top to bottom; anything else on a line, a blank line among them, ends the run, and a doc comment beside code or below a declaration is about nothing. A declaration that does not begin its line, such as a parameter, has none. The language gives a doc comment no other meaning, so this decides only what a tool shows. **The alternatives:** the nearest doc comment above, however far, which hands a file's opening comment to whatever is declared first; a blank line allowed between, which makes a section heading the documentation of the first declaration under it; and a doc comment after the declaration on the same line, which [1780]'s line comment already serves and which would make every trailing remark documentation. **Pinned by** `server/doc comments are the run above` and the `hover` session under `compiler/tests/server/`. ### D381 — A refusal that reached a hiding local names the local and what it hides **The discrepancy:** [0140] lets an inner scope shadow an outer name, and [1450] lets a parameter or local shadow an import. Neither said what a refusal says when the shadowing is the mistake. A result named `time` hid `import core/time`, and `time.duration` in a type position was refused as "`duration` is not declared in any scope this reaches"; a parameter named `allocator` hid the concept of that name, and `any allocator` was refused as "`allocator` does not name a concept". Both pointed at what was looked for and neither at why it was not found. **Chosen:** when a use is refused because its name, or a qualified name's prefix, reached a parameter, result or local, and that declaration hides an import, a concept or another module declaration of the same name, the refusal says so: "`time` here is the result `time`, which hides `import core/time`, so `time.duration` names no type", with the hiding declaration labelled "this hides `import core/time`". L0201 in a type path, L0301 in a member selection and L0341 in a concept position each do this, and a concept reference that names no concept is one report however many positions read it. Which programs are accepted does not change; L0201 may now carry one secondary label, the hiding local, where it carried none. **The alternatives:** refusing the shadowing itself, which [0140] and [1450] admit and the library relies on; a warning on every local that hides an import, which fires on programs nobody misread; and naming only the import in a note, which leaves the reader to find which local hid it. **Pinned by** `negative/local-hides-an-import` and `negative/parameter-hides-a-concept`. ### D1260 — A nearer declaration shadows a predeclared type, whatever it declares **The tour said** at [1790] that the scalar and text-view names are predeclared and are not keywords, and at [0140] that an inner name hides an outer one. A type position that spelled one was looked up lexically, but only a type declaration or a type formal found there replaced the predeclared type: a nearer function, binding or parameter of the spelling left the position naming the predeclared type, so `x: u8` beside a function named `u8` meant the scalar while `u8(v)` called the function. One spelling had two meanings in one scope, chosen by where it stood. **Chosen:** ordinary lexical shadowing. The nearest visible declaration of the spelling is what a type position names, whatever it declares, and one that is no type is refused there with L0338, whose note says that the predeclared type is named only where nothing declares the spelling and that the declaration wants another name. The predeclared type is what the position names only when lookup finds nothing. A function named `u8` can therefore not write `u8` in its own signature, a local named `i64` ends the type's use for the rest of its block, and a parameter named `usize` ends it for the rest of the signature and the body. Calls and value uses are as they were: they already resolved by ordinary lookup. The library and the examples declared no non-type under one of the sixteen spellings. Besides the two controls that had pinned the asymmetry, one test program did: `compiler/tests/darwin/transport.ldn` numbered parameters `i0` to `i9`, so `i9: i8` followed a parameter named `i8`, and they are now `n0` to `n9`. **The alternatives:** keeping the asymmetry as the rule, with a type position falling back to the predeclared type past any non-type, which lets `u8: (v: u8) -> (r: u8)` be written and leaves a reader of `x: u8` to find out that the nearest `u8` is not what it names; continuing the lookup outward past a non-type, which no other name does; and reserving the sixteen spellings, which [1760] declines and D1066 works around for C names. D1342 later warns at such a declaration, keeping this rule. **Pinned by** `negative/a-non-type-shadows-a-predeclared-type`, whose report is recorded, `resolution/predeclared types use lexical lookup` and `lowering/calls respect resolved declarations`, whose functions named as a scalar now write their signatures in other types. ### D1342 — A declaration that takes a predeclared type's name is warned about **The tour said** at [1790] that the sixteen predeclared type names are in no scope and not reserved, and D1260 made the nearest declaration of a spelling what a type position names, whatever it declares. A program may therefore name a function `u8`, a local `i64` or a parameter `usize`, and from there on no type position the declaration reaches can name the predeclared type: the next `x: u8` is L0338, or, under a type declaration named `u8`, quietly another type. **Chosen:** D1260's rule stays, and L0692, a warning under D251's policy, is given at every declaration in an active configuration whose name is one of the thirteen scalar names or `utf8`, `utf16` or `cstring`, whatever it declares: a function, an atom, a type, a concept, a module or local binding, a variant case, a type or fixed formal, a parameter, a named return, a pattern, traversal or destructured binding and a call's error name. Like L0684 it is raised only in a program with no error, since a type position the declaration reaches is already L0338, whose note names it. It offers no fix: which name was meant is the author's. This is the one warning about a name, and it is no warning about shadowing in [1850]'s sense: the predeclared types are in no scope, so the declaration hides no name the program declared. Generated bindings already avoid the spellings (D1066), and the library and the examples declared none. D1260's controls keep their declarations: the negative fixture's report holds errors and so no warning, the resolution and lowering cases do not read warnings, and the checker case `conversions require one value`, which calls user functions named `u8` and `utf8`, now accepts them with this warning and nothing else. **The alternatives:** reserving the sixteen names, which [1760] declines and D1066 works around for C; warning only where a type position the declaration reaches spells the name, which the L0338 or the other type already shows, and which misses the declaration a later edit trips over; warning only for declarations that are no type, which leaves `u8: type = u16`, the most misleading of them, unsaid; and saying nothing, where D1260 left it. **Pinned by** `negative/a-predeclared-type-name-taken`, whose report is recorded and whose program takes each name kind's spelling once, a type declaration among them, and holds a field and a function type's parameter named `u8`, which declare nothing in a scope and are not warned about. ### D1261 — An `else` binding its block never reads is warned about **The discrepancy:** [1030] has two blocks for a call-site recovery, `else (e) ... end`, which binds the error, and `else begin ... end`, the bare block as the value, which binds nothing. A reader who knew only the first wrote `else (problem)` with `problem` never read, nothing said that the second exists, and D370's repair for statements under a bare `else` wrote ` (problem)` itself, so the compiler's own fix produced the unused name. **Chosen:** L0684, a warning under D251's policy, at an `else (name)` whose block has no reference to `name`. Its note names the forms that bind nothing: `else begin ... end` runs a block and `else value` stands in for the result. `_ = name` is a reference and silences it, as it must stay legal. One place is exempt: in the arm of an `if`, an `else` with no name is the `if`'s own [1820], so the name is what makes the recovery the call's, and nothing is said. Like L0326 it is raised only in a routine body the checker checked and in an active configuration. It offered no fix: replacing `(name)` with `begin` is the edit, and D1341 later proves it and offers it. D370's repair now writes ` begin`, the block the statements written under the bare `else` already fit, and its message names that block. **The alternatives:** saying nothing, where it stood; refusing an unused binding, which makes a lint a rule of the language against D251; a new block form after a bare `else`, which D370 declined and which the grammar does not need, having `else begin`; and warning in an `if` arm too, where the only repairs are parentheses round the call or the name the warning objects to. **Pinned by** `negative/unused-else-binding`, whose report is recorded and whose program holds each exempt form, and `negative/statements-after-a-bare-else-name-its-binder`, whose fix the `fixes` suite compiles clean, without a warning. ### D1341 — L0684's fix writes `else begin` for the unread binding **The discrepancy:** D1261's warning named the form that binds nothing and offered no edit, so an editor showed the warning with nothing to apply, and every `else (problem)` the warning found was retyped by hand. **Chosen:** L0684 carries one exact fix, which replaces the bytes from the end of `else` to the binding's `)` with ` begin`: `else (problem) ... end` becomes `else begin ... end`, and the one-line `else (problem) 0 end` becomes `else begin 0 end`. It is exact under D251 because the warning is raised only where no reference in the block names the binding and the program has no error, so the bare block runs what the bound one ran and every name in it means what it meant; the `if` arm where leaving the name out would hand the `else` to the `if` [1820] is never warned about. The fix is offered only when the replaced bytes are the parenthesised name and spaces or tabs on one line, so it never removes a comment or a line end; otherwise the warning stands alone. It reaches every consumer of a fix: the human report's `help`, the JSON report's `exact` fix and the language server's preferred quick fix, and since D1847 `refine fix`, which applies every exact fix; `refine fmt` applies no fix, since D252's layout changes no token. **The alternatives:** writing `else value` for a one-value block, a second edit whose result an `if` arm can reread as the `if`'s own `else`; a `Likely` fix, which a batch tool would not apply although nothing about the rewrite is a guess; and a fix that also takes a comment or a line end inside the parentheses, which removes source the warning is not about. **Pinned by** `negative/unused-else-binding`, whose `program.fixed` the `fixes` suite compiles with an empty report; `negative/unused-else-binding-beside-a-comment`, whose comment and line end keep the warning without a fix while its spaced binding has one; and the server session `unused-else-binding-repair`, whose code action is the preferred edit. ## DECISIONS: NUMBERS AND LITERALS How a literal is written, what it means, and which scalar types the kernel has. ### D3 — Signed integers are two's complement **The tour said** nothing: the word complement appears nowhere in it. [0300] gives wrapping operators and [0320] gives a sign-keeping `>>`, and neither means anything without a representation. **Chosen:** two's complement, stated in [1870]. So `i8` holds -128 and not -127, and `-128` is writable. **The alternative:** leaving it to the target. Then `i8 = -128` would be a program whose legality depended on the machine, which [0310]'s refusal of implicit conversion exists to prevent. **Pinned by** `positive/literal-at-the-widest-value`, `negative/literal-below-its-type`. ### D4 — `usize` is a distinct type from `u64` **The tour said** only that `usize` and `isize` are pointer-width integers [0160]. It does not say whether that makes `usize` a name for `u64` on a machine whose pointer is eight bytes wide. **Chosen:** distinct, on every target [1870]. Adding a `usize` to a `u64` is refused everywhere. **The alternative:** the same type where the widths agree. That is what a C programmer expects, and it costs this: a program would compile on `linux-x86-64` and be refused on a 32-bit target for a reason no paragraph of the specification could state. **Pinned by** `negative/usize-is-not-u64`. ### D5 — A typed sibling gives an untyped literal its type **The tour said** that an integer literal takes the type of its context and is checked at that point [0190], and that with no context it is `i32` [0200]. It never says what a context is. That list is in [1880] and was written here. **Chosen:** eight positions give a literal a type, and one of them is the other operand of a binary operator. So in `x + 1` with `x: u8`, the `1` is a `u8`. **The alternative:** only a declared type is a context. Then `x + 1` would make the `1` an `i32` by [0200] and immediately refuse it against `x`, so every literal in an expression would need a conversion the kernel does not have. This is the decision with the least room in it, and it is still a decision. **Pinned by** `positive/literal-takes-a-sibling-type`. ### D162 — Decimal f32 and f64 values keep IEEE bits through runtime operations **The tour said** that f16, f32 and f64 exist [0170], that a float literal is recognisably distinct from an integer [0210], that decimal exponents and separators are accepted [0220], and that signed zero and arithmetic-produced IEEE special values are observable [0240]. It did not state the type of a contextless float, whether one width could arrive before the others, how a finite decimal overflow is treated, or whether module folding may inherit the compiler host's arithmetic. **Chosen:** f32 and f64 are enabled. A decimal literal has digits on both sides of its dot and may have `e` or `E`, an optional sign, and a nonempty decimal exponent; underscores follow the integer digit-run rule. It takes f32 or f64 from context and otherwise defaults to f32. Integer and float literals remain separate classes with no implicit conversion. The literal rounds once to IEEE binary32 or binary64; a finite spelling that would become infinity is L0300. Unary minus flips the IEEE sign bit, preserving negative zero and a NaN payload. At runtime `+`, `-`, `*`, `/`, unary minus and all six comparisons use the value's IEEE width. Division by signed zero yields infinity or NaN rather than [1950]'s integer refusal or trap. Equality is false for an unordered NaN, inequality true, and every ordered comparison false. Values retain their raw bits through local and module scalar storage, fixed arrays, ordinary structs, internal parameters and returns. Representation-class routine sharing treats a float as distinct from a same-width integer. The first external C boundary continued to refuse float signatures until its float register classes were supplied. D204 and the current [1975] subsequently define that separate C float path; the limit in this decision does not override them. A module float at this decision may use a literal, its unary minus or `zeroed`, also inside a static aggregate image. Float arithmetic in a module image remained a named refusal: the target-neutral folder does not borrow the compiler host's rounding mode or NaN behavior. D166 subsequently enables hexadecimal floats [0230], D167 enables the named `infinity` and `nan` members [0240], and D175 enables module float arithmetic and comparison. f16 and explicit integer/float conversions [0310] remain separate hosted increments. **The alternatives:** default to f64, admit decimal literals only with an explicit type, treat a float's same-width integer carrier as interchangeable, lower float operations through integer arithmetic, or evaluate module values with the Ada host's float types. Those choices contradict the tour's inferred f32 examples, lose IEEE behavior, make routine sharing change operations, or make cross-compilation depend on the host. **Pinned by** `runtime/float-decimal-runtime`, `negative/float-literal-not-enabled`, `negative/float-literal-overflows-context`, `negative/float-remainder-is-integer-only`, `negative/float-type-not-enabled`, `negative/integer-literal-not-a-float`, `negative/malformed-float-exponent`, `positive/r440-external-float` for the later f64 C-boundary admission, `negative/external-aggregate-boundary` and `negative/r440-c-slice-parameter` for the boundary's continuing carrier refusals, the lexer cases, and the `float.ieee` guarantee row. ### D163 — A character is one decoded Unicode scalar with fixed type u32 **The tour said** that [0250]'s character literal is a codepoint typed `u32` and [0270] gives literals one closed escape set. It did not say whether the byte escape denotes a character, whether raw source may contain more than one scalar, or which stage rejects a nonscalar `\u{...}` value. **Chosen:** the kernel admits a single-quoted literal only when its content decodes to exactly one Unicode scalar value. Raw content is one shortest-form UTF-8 scalar. The simple escapes `\n`, `\r`, `\t`, `\e`, `\\`, `\"` and `\'` denote their codepoints, and `\u{...}` denotes one scalar written in hexadecimal. The byte-only `\xNN` form is not a character spelling. Empty, multiple, malformed UTF-8, unknown-escape, surrogate and above-`10FFFF` contents are lexical L0322; an unclosed quote remains L0014. The literal's type is always `u32`, including in an inferred binding. A different scalar context is L0301 rather than an implicit conversion. Its decoded value uses the existing integer constant carrier, arithmetic, comparison, module folding and aggregate images; the IR and backend need no character-specific operation or representation. Lexing, checking and lowering call one decoder so they cannot disagree about the scalar. **The alternatives:** treat `\xNN` as a codepoint, infer an integer type from context, retain UTF-8 bytes as the value, or permit a quoted grapheme cluster. Those choices erase [0270]'s byte/codepoint boundary, contradict [0250]'s fixed type, or turn a scalar literal into the text representation work [0600] owns. All were declined. **Pinned by** `runtime/character-literal-codepoints`, `negative/character-literal-byte-escape`, `negative/character-literal-empty`, `negative/character-literal-invalid-codepoint`, `negative/character-literal-multiple`, `negative/character-literal-needs-u32`, the decoder and lexer cases, and the `source.lexical` and `types.values` guarantee rows. ### D164 — Raw byte text uses matching quote runs and exact indentation **The tour said** that [0280]'s raw literal has the same number `N` of quotes on each side, with `N` at least three, interprets no escape, and strips the closing delimiter's indentation from every line. It did not define whether a longer quote run closes a literal, how indentation mismatches are handled, or which currently enabled text carrier receives the bytes. **Chosen:** the kernel admits raw literals in D161's direct read-only `[]u8` context. The maximal opening quote run chooses `N`; the first later run of at least `N` quotes closes the token, consumes exactly `N`, and leaves any additional quotes for following tokens. Runs shorter than `N` are content. Backslashes and [0270]'s apparent escapes are ordinary bytes. Raw source content must remain shortest-form UTF-8, and the view carries the same uncounted trailing NUL as quoted text. At this decision a literal without a direct byte-slice context defaults to the then-deferred `utf8`; D181 later enables that default. A closer is line-leading when an earlier line ending is followed only by spaces or tabs before it. That exact byte prefix is removed at the start of every nonblank content line that begins after a line ending; content on the opener's own line is unchanged. A nonblank line with a shorter or different prefix is lexical L0323; horizontal bytes on a blank line are discarded. Line endings, including the one immediately after an opener or before the closer, remain content. An inline closer has no indentation to remove. A mismatched or absent closing run remains the existing unterminated-literal L0014. After indentation is removed, raw and quoted literals with equal byte content share D161's one pooled read-only datum. Checking, module images, aggregate fields, calls and lowering otherwise use the same slice path; neither IR nor the backend learns a raw-literal operation. **The alternatives:** fix the delimiter at three quotes, close on a shorter run, silently leave under-indented lines unchanged, count visual columns rather than exact source bytes, interpret escapes, or allocate raw and quoted content separately. Those choices contradict [0280], make tabs target/editor dependent, or duplicate representation that is observably identical after decoding. All were declined. **Pinned by** `runtime/raw-literal-bytes`, `negative/raw-literal-inconsistent-indentation`, `negative/raw-literal-needs-read-only-slice`, `negative/raw-literal-write`, `negative/unterminated-raw-literal`, the raw decoder and lexer cases, and the `source.lexical` and `text.literal-storage` guarantee rows. ### D166 — Hexadecimal floats are converted from source bits, not host floats **The tour said** that [0230]'s hexadecimal float literals express every representable value exactly, including subnormals. It did not define the required exponent syntax, the result of a spelling between two representable values, or whether the compiler may ask its own floating-point implementation to read the value. **Chosen:** a hexadecimal float is `0x`, a nonempty hexadecimal digit run, a dot, another nonempty hexadecimal digit run, and a required `p` or `P` binary exponent. The exponent has an optional sign and a nonempty decimal digit run. Each digit run admits [0220]'s separators but neither begins nor ends with one. Like D162's decimal form, the literal takes f32 or f64 from context and otherwise defaults to f32; it remains a float rather than sliding into the integer class. Conversion reads the hexadecimal significand as bits and combines it with the written binary exponent. An exactly representable normal or subnormal value therefore reaches its target with the exact bits [0230] promises. A value between target values rounds to nearest with ties to even, including at zero, the subnormal/normal boundary and an exponent carry. Underflow may produce zero. A finite spelling that rounds to infinity is L0300, as for D162's decimal form; a zero significand remains zero even with an arbitrarily large exponent. The conversion uses only bounded integer accumulation of the significant, round and sticky bits. It does not parse through an Ada floating-point type, so cross-compilation does not inherit the host's width, rounding mode or handling of subnormals. The resulting IEEE pattern follows every D162 storage, aggregate, internal-call, arithmetic and comparison path without new IR or backend operations. An absent or incomplete binary exponent is lexical L0321. Enabling this form removes the scanner's final deferred token family; L0010 continues to name parser-level constructs that [1830] leaves disabled. **The alternatives:** use the compiler host's hexadecimal conversion, accept only spellings already exact in the contextual width, or retain an arbitrary precision significand. The first makes a target value host-dependent, the second contradicts ordinary literal rounding, and the third retains far more source state than the precision, round bit and sticky bit require. All were declined. **Pinned by** `runtime/float-hexadecimal-runtime`, `negative/hex-float-overflows-context`, `negative/malformed-hex-float-exponent`, the lexer cases, and the `float.ieee` and `source.lexical` guarantee rows. ### D167 — IEEE special values are inherent type-qualified constants **The tour said** that [0240] writes infinity and NaN as members of a float type, that unary minus supplies their negative forms, and that NaN comparison is unordered. It did not say whether the qualifier or the surrounding context chooses the width, which NaN payload a source name denotes, whether a signed NaN retains that sign, or whether the names are valid module images. **Chosen:** the kernel enables exactly `f32.infinity`, `f64.infinity`, `f32.nan` and `f64.nan`. The type before the dot is an inherent part of the value: it does not convert to another contextual float width, so a width mismatch is L0301. No other scalar type has these members, and no other member of f32 or f64 is a named value. An unknown type-qualified member is also L0301 rather than an unresolved module or runtime field selection. Infinity has the ordinary positive IEEE pattern. `nan` denotes one canonical quiet NaN: `0x7FC00000` for f32 and `0x7FF8000000000000` for f64. Unary minus flips only the sign bit of either named value, preserving the quiet NaN's payload. These bits use the existing float IR carrier, storage, internal-call, arithmetic and comparison paths; no new runtime operation or backend opcode is introduced. A named special and its unary minus are compile-time scalar leaves, not member reads from storage. They are therefore valid in module scalar images and in the scalar leaves of module arrays and structs wherever a float literal is valid. General module float arithmetic remains D162's L0304 boundary at this increment and is subsequently enabled by D175. f16 and explicit integer/float conversions remain separate hosted increments. **The alternatives:** infer the width from context despite the written type, spell the values as unqualified lexical literals, preserve an unspecified or host-chosen NaN payload, or reject them from static images as field reads. Those choices respectively make the qualifier misleading, add another token family for values the tour writes as members, make generated target bits depend on the compiler host, or deny a constant spelling where an equivalent literal image is already accepted. All were declined. **Pinned by** `runtime/float-named-specials`, `negative/float-special-name-unknown`, `negative/float-special-on-integer-type`, `negative/float-special-width-mismatch`, the direct checking case, and the `float.ieee` guarantee row. ### D190 — u128, i128 and f16 are refused by name D228 subsequently enables packed unsigned field representations; the historical quotation below records the earlier kernel boundary. D237 later transfers u128, i128 and f16 to the Language evolution successor with new consumer, target and compiler evidence; the refusal below keeps its code, now says "`u128` is not in this version of the language", and its note now names that transfer. **The tour said** that the integers are u8, u16, u32, u64, u128, i8, i16, i32, i64 and i128 [0150], and that the floating-point types are f16, f32 and f64 [0170]. It teaches the language and does not schedule work, so it said nothing about which of those widths the kernel enables or about what would have to be built for the rest. [1870] answers the first half — "u128 and i128 [0150], the packed widths [0730] and f16 [0170] are described in this tour and are not enabled yet" — and answered the second half nowhere. **Chosen:** the refusal of u128, i128 and f16 is the specification's, and the work that would enable them is not the text, literal and loop work that enabled f32 and f64. The refusal itself was unchanged in every respect a program can observe: the checker still matched the resolved spelling, still reported L0304 with "`u128` is not enabled yet", and still attached [1830]'s two notes naming the paragraph and the enabling work. Only the second note changed, to name work that would decide the widths rather than the work that had deferred them; D237 later made that note "this is transferred to Language evolution" and D246 made it state the form's standing. This is an ownership correction and not a language change, and the reason it can be one is that the refusal was already normative. [1790]'s `scalar_name` production spells thirteen names and has never spelled these three, so the enabled kernel grammar does not admit them and never has; a program writing one is refused by the specification and not by a schedule. What was wrong was a single entry in the compiler's own table, which named the hosted construct work because D162 happened to belong to it when it enabled f32 and f64 and deferred f16 — not because that work's scope, "text, literals, patterns, loops, `unchecked`, modules, builtin directives and hosted entry behavior", ever included widening the scalar set. [0150] is already a paragraph split across owners: the packed widths u4, u12 and u23 that the same paragraph names belong to the freestanding register work [0730], and nobody reads that as the hosted construct work owing a bit-field allocator. The construct-applicability register keeps [0150] and [0170] accounted for by the hosted construct work, because that work accounted for those paragraphs as far as the kernel enables them — D162 gave [0170] its two enabled widths and D168 through D176 gave [0150]'s enabled ones the complete conversion matrix. Only the residual refusal moves, which is exactly what D188 did for [0660]'s composite positions and D189 for [0480]'s multi-atom form. A row whose construct one piece of work accounts for and whose remaining refusal another decides is the register's ordinary shape, not an exception made here. What enabling them would inherit is written down so that the refusal is scoped rather than vague, and it is five things and not one. - `Landin.Types.Magnitude` is `range 0 .. 2 ** 64 - 1` and `Landin.Types.Folded` is `range -(2 ** 64 - 1) .. 2 ** 64 - 1`. At 128 bits neither is an Ada range type on any host: `Folded`'s symmetric form needs 129 bits and `Magnitude`'s upper bound needs an unsigned 128. Both become software carriers, and so does the single `type Pattern is mod 2 ** 64` that `Landin.Stages.Checking`, `Landin.Stages.Lowering` and `Landin.Backend.X86_64` each fold with. - A 128-bit scalar is the first one the backend's one-accumulator memory model cannot hold in a register: `Held_Size` is `Byte_1 .. Byte_8` by declaration, and the SysV classification is two INTEGER eightbytes at 16-byte alignment. - Its arithmetic is add/adc, sub/sbb and a three-multiply `mul`, and a division and remainder x86-64 has no instruction for — `divq` divides a 128-bit dividend by a 64-bit divisor for a 64-bit quotient and faults when that quotient does not fit. Either an emitted software sequence or a dependency on a support library, and the second contradicts D166, D169 and D175's standing refusal to borrow arithmetic this compiler does not own. - f16 is the whole D162--D176 float programme re-run at binary16: decimal and hexadecimal literal conversion at p=11 and emax=15 with subnormals, D167's canonical quiet NaN at that width, D169's rounding across a three-by-three width matrix, D175's module fold, and runtime arithmetic that baseline x86-64 cannot do at all, since F16C is Ivy Bridge and later. That is an ISA baseline change affecting every emitted binary and the Linux gate, or a software encode and decode around every operation. - Enabling f16 reopens a settled decision rather than extending one. D170 records that "the enabled integer range cannot overflow either float width", which is true only while f16 is absent: binary16's largest finite value is 65504, so a u32 of 65520 or more rounds to infinity, and the `conversion.integer-to-float` guarantee row would move from class `static` to class `trap` and would owe trapping runtime evidence. One design answer is recorded here so it is not rediscovered: f16 arithmetic should promote through f32 and round once. binary32 carries 24 significand bits and 24 >= 2 * 11 + 2, so a single rounding of the f32 result to binary16 is the correctly rounded binary16 result for `+`, `-`, `*` and `/`, and the double rounding is innocuous. Whether the promotion is emitted or the operations are done in software is a target question and stays open. **The alternatives:** implementing them inside the hosted construct work was weighed and declined as out of proportion to what that work is for. It is four to six increments — the two carriers above, the backend pair, the float programme at a third width, and the reopened conversion guarantee — and none of the hosted path's evidence needs any of it. Giving the two widths dedicated hosted work so they land before the macOS arm64 and Cortex-M slices was the closest alternative; it was declined because f16 must exist on every target once it is enabled and the baseline Linux x86-64 ISA cannot do binary16 arithmetic at all, which makes it target work and not hosted work. Splitting the two owners — f16 to the freestanding float slice, u128 and i128 to the deferred-behaviour decisions — was declined for the same reason. Amending [0150] or [0170] to delete the three names was declined because they are language the tour teaches and no evidence says the language should lose them. Leaving the compiler's table naming the hosted construct work while the widths were decided elsewhere was declined because [1830]'s note was then a promise to a user about where to look, and a note naming finished work is a wrong answer to that question. No document exercises any of the three. Nothing in `tour.md`, `spec.md`, `examples.md` or the five prototypes writes u128, i128 or f16 in an example, which is the honest measure of how much design pressure exists for them today: none that has been recorded. **Pinned by** `negative/wide-integer-not-enabled`, `negative/float-type-not-enabled`, `negative/refused-widths-name-their-owner`, whose recorded report is where "this is transferred to Language evolution" is executable text rather than a comment and which is the only fixture in the corpus that reaches `i128` at all, and the `types.values` guarantee row. ### D219 — Either integer range endpoint supplies literal context **The tour said** that an integer literal takes its context [0190], defaults to i32 without one [0200], and may appear at either end of a traversal [1150]. D159 required one integer type for the two bounds but did not specify which endpoint supplies context. The implementation previously defaulted an untyped lower bound before considering a typed upper bound, although an upper literal already took a typed lower bound's type. **Chosen:** either typed integer endpoint supplies the type of an untyped integer peer. With two untyped integer bounds, both take i32. Literal values and untyped integer arithmetic must fit that chosen type under [1880]; this includes refusing a negative lower literal when the upper bound is unsigned. Two bounds that already have different integer types still disagree. A float, character or other already typed value does not silently become another integer type. The iteration element keeps the selected integer type. This makes the prototypes' `0..>` keeps its sign [0320]. It says nothing about the amount's type. **Chosen:** the same type as the value being shifted [1890]. So shifting a `u8` by 300 is refused, because 300 is not a `u8`, while shifting it by 40 is accepted and yields zero. **The alternative:** any integer type for the amount, or one fixed type such as `usize` for every shift. Either would accept `x << 300` and produce zero, which is what [0320] says an over-wide amount does — so this decision makes the specification's own example the boundary case rather than the rule. **Pinned by** `negative/shift-amount-takes-the-left-type`. ### D8 — A zero divisor is refused when it is known, and traps when it is not **The tour said** that integer division truncates toward zero and that the remainder takes the sign of the dividend [0290], and nothing else. It does not say what a zero divisor does, and [0300] does not reach it: a quotient that does not exist is not a result that overflowed. **Chosen:** [0310]'s shape, in [1950]. Refused where the compiler knows the divisor, trapped where it does not, and refused at module level always. `%` goes with `/`, because the divisor is the same operand. **The alternative:** a defined value, which is the only other thing on offer. AArch64's `SDIV` answers 0 and x86-64's `IDIV` raises a hardware fault, both measured — so the Linux x86-64 and Darwin arm64 targets already disagree, and adopting either would make one program mean two things or make the other target pay for a value nobody asked for. Leaving it to the machine is the same alternative D4 refused, in the same words. **Pinned by** `negative/divisor-is-zero`, `negative/remainder-by-zero`, `negative/divisor-is-zero-in-a-body`, `positive/divisor-is-not-known`, and for the trap `runtime/a-zero-divisor-traps` and `runtime/a-zero-remainder-divisor-traps`. ### D9 — A negative shift amount is refused when it is known, and traps when it is not **The tour said** that shifts fill with zeros beyond the width for any amount and that a signed `>>` keeps its sign, and that there is one form only [0320]. It says nothing about a negative amount, and D6 is what makes one writable: the amount takes the left operand's type, so a signed left operand admits a negative one. **Chosen:** the same shape as D8, in [1950], so that the two operands no operation can take are one rule and not two. **The alternative:** three, and each is some language's answer. Read the amount as unsigned, so -1 is beyond the width and [0320] already says the answer is zero — which is exactly what Cortex-M0 does, measured, and it turns a likely bug into a silent zero. Reverse the direction, which is Swift's answer, and which [0320]'s "One form only" is the sentence against. Or mask the amount to the width, which is what x86-64, AArch64, Java and C# all do, measured on the first two — but [0320] has already declined masking for over-wide amounts, since it says they fill with zeros rather than wrap around, so masking here would make one operator answer two ways. **Pinned by** `negative/shift-amount-is-negative`, `negative/shift-amount-is-negative-in-a-body`, `positive/shift-amount-is-not-known`, and for the trap `runtime/negative-left-shift-traps` and `runtime/negative-right-shift-traps`. ### D11 — A trap is a deliberate synchronous stop **The tour said** that overflow traps [0300] and a runtime conversion whose value does not fit traps [0310]; [1950] adds two operands that trap when their value is not known. None says where a trap happens, whether it returns, what follows it, or whether the host's report is program behaviour. **Chosen:** [1960]. A trap happens at the operation's point in evaluation order, never returns, and permits no later Landin action. Its operating-system encoding is not stable. The default Linux x86-64 handler uses a deliberate `ud2`, so the language does not inherit whichever fault or value an arithmetic instruction happens to provide. **The alternative:** leave each operation to its machine instruction, or call a runtime routine. The first has already been ruled out by D8's measured x86-64 and AArch64 disagreement, and would wrongly trap the defined remainder of the lowest signed value by -1 on x86-64. The second can give a stable report, but makes that report an interface the language must preserve and a runtime every freestanding target must supply. **The deferred obligation:** [1670] promised the fixed two-scalar, never-returning handler when the original kernel could not express its atom set or return form. D231 supplies `noreturn`; D232 now supplies source handler selection, check dispatch and optional site mapping on every implemented target. The original default trap remains the constrained default. The alternative declined above was a mandatory reporting runtime instead of that contract, not [1670] itself. **Evidence:** `runtime/checked-overflow-traps` and `runtime/a-zero-divisor-traps` run on Linux x86-64 and are held to having ended without returning a status, which is the whole of what this decision makes observable. The first is the one that tells a trap edge from no edge: without it the addition keeps its low byte and the program returns normally. Neither says which signal ended it, because this decision is what says that question has no stable answer. **Pinned by** `runtime/checked-overflow-traps`, `runtime/a-zero-divisor-traps`, and the conversion traps the paragraph above asked for: `runtime/float-to-integer-out-of-range-traps` and `runtime/float-to-integer-nan-traps`. `runtime/range-subtype-store-traps` pinned a range subtype's trap until D1661 removed the form. ### D13 — An amount at or past the width gives zero on every shift **The tour said** two things about a shift that do not agree at the boundary: that shifts "fill with zeros beyond the width, for any amount", and that "Signed >> keeps the sign" [0320]. Its example is a `<<`, so it settles nothing for the one operator where the two sentences meet. D6 makes the question reachable, since the amount takes the left operand's type and a signed left operand admits an amount of any size. **Chosen:** the zeros sentence governs every shift, so an amount at or past the width gives zero and a signed `>>` is not an exception. With `minus_one: i32 = -1`, `minus_one >> 31` is -1 and `minus_one >> 32` is 0. A backend therefore tests the amount against the type's own width rather than letting the processor mask the count — x86-64 masks to five bits at 32-bit and six at 64, which is the masking [0320] already declined for over-wide amounts. **The alternative:** let "keeps the sign" govern at every amount, so a signed `>>` saturates to all sign bits and `minus_one >> 32` is -1. It is continuous where this rule has a step, and it is what x86-64's `sar` gives for free once the count is clamped. It was declined because it makes one operator answer two ways — zeros for `<<` and for unsigned `>>`, sign bits for signed `>>` — where the tour states the zero-fill rule for shifts as a class and states the sign rule about which bits `>>` brings in, not about what an exhausted shift leaves behind. **Pinned by** `runtime/shifts-fill-with-zeros-beyond-the-width`, whose `i32` and `i8` bindings of `-1 >> 32` and `-1 >> 8` and whose `u64` binding of `1 << 64` are each zero on the hardware. ### D14 — A measurement is a `usize`, and only the target knows it **The tour said** that `sizeof`, `alignof` and `lenof` measure, and that on an array or a literal the length is a compile-time value [0370]. It writes `w1 := sizeof u32` with the inferred form, so nothing in it says what type a measurement has, and [0200]'s default is about an integer _literal_ rather than about this. **Chosen:** `usize`. A size and an alignment are counts of bytes on the machine being compiled for, which is what [0160] says `usize` is for, and a measurement that defaulted to `i32` would need a conversion at every use where a width is wanted. `lenof` has the same result type. It takes a direct identifier naming a fixed array or slice; [0370]'s slice length is a runtime value. D31 also admits a parenthesized nonempty array literal. Other general expression operands remain outside [1820]'s measurement grammar. The spelling stays contextual rather than joining [1760]'s reserved words. **Where the answer comes from** is the other half of this decision and the half with teeth. A scalar `sizeof` or `alignof` is not folded by the checker or the lowering: `Landin.IR` carries `Measure_Size` or `Measure_Align` with the type asked about, and the backend answers, because a byte size needs a target. That is the seam [0320]'s zero-fill already sits on, and it keeps the IR target-neutral — the same source emits 8 for `sizeof usize` against the Linux x86-64 description and 4 against the synthetic 32-bit one. A fixed array is measured from its resolved structural type, whether [1790] writes it inline or D15 reaches it through aliases. Its size is its element count multiplied by the target's size for the scalar element, and a nonempty array's alignment is that element's target alignment. Lowering preserves those questions as the existing scalar measurement, `usize` Number and Multiply IR; it adds no array-measurement opcode and asks no host question. The internal zero-element shape keeps size zero and alignment one; this says what a shape already representable inside the checker means and does not decide whether source may spell one. A fixed array's element count is already part of its type (D17), so `lenof name` lowers to the existing `usize` Number IR with that count. It does not read the named storage and does not require the binding to be definitely assigned. **The alternative:** `i32`, which is what an untyped literal would default to and so the least surprising answer for a reader who has only read [0200]; declined because it makes the common use — comparing against or multiplying by a width — start with a conversion. Or folding in the checker, which would put a target fact in a stage this repository has kept target-neutral on purpose, and which `Landin.IR`'s own header already argues against for the shifts. **Pinned by** `positive/measurement-of-a-type`, `positive/measurement-of-fixed-arrays`, `positive/lenof-uninitialized-fixed-array`, `negative/measuring-refused-types`, `negative/lenof-scalar`, `negative/lenof-unresolved-name`, `runtime/lenof-named-fixed-arrays`, `runtime/measurements-answer-for-the-target`, and the backend case that emits one source against two target descriptions. ### D165 — Compound assignment retains one destination and one operator **The tour said** that assignment is a statement, listed thirteen compound spellings [0390], fixed destination-before-value evaluation [0410], and said that `inc x` means what `x += 1` means [0400]. It did not say whether the destination was re-evaluated for its implicit read, whether it had to be assigned already, or whether a compound form inherited every failure boundary of its binary operator. **Chosen:** `place op= value` evaluates `place` once, reads its existing scalar value, evaluates `value`, applies the corresponding [1820] binary operator and writes the result through that retained place. The thirteen forms are `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, `+%=`, `-%=` and `*%=`. Destination evaluation and its implicit read both precede the right-hand expression. A computed index or pointer path is retained as an internal address, not reconstructed after the expression. The destination must be assigned on every arriving path because the operation reads its old value; success leaves it assigned. It needs the same binding or reference write permission as plain assignment. Both operands have the destination scalar type under [1890]: ordinary arithmetic admits integers and floats, while remainder, wrapping, shifts and bitwise forms admit integers only. Known zero integer divisors and negative shifts retain [1950]'s L0306. Runtime checked overflow and impossible integer operands retain [1960]'s trap; the three wrapping forms and admitted shifts remain total. Float division by signed zero retains D162's IEEE result. This is one read-modify-write language operation but makes no atomicity or concurrency claim. Aggregates, slices, `any`, functions, pointers and atoms have no applicable binary operator and are L0301 rather than acquiring a copy-update meaning. **The alternatives:** desugar by copying the place syntax into both sides of plain assignment, evaluate the right-hand side before reading the old value, let an unassigned destination become initialized, or define separate compound operator rules. Those choices duplicate observable calls in indexes, reverse [0410], permit a read of indeterminate storage, or let two spellings of one operation drift. All were declined. **Pinned by** `runtime/compound-assignment`, `runtime/compound-assignment-overflow-traps`, `negative/compound-assignment-as-expression`, `negative/compound-assignment-float-remainder`, `negative/compound-assignment-immutable`, `negative/compound-assignment-unassigned`, `negative/compound-assignment-zero-divisor`, and the `arithmetic.known`, `arithmetic.runtime`, `arithmetic.total` and `assignment.flow` guarantee rows. ### D168 — Integer conversion checks a mathematical value, not its bits **The tour said** that [0310] writes conversion as a type applied to a value, rejects an impossible compile-time conversion, and traps when a runtime value does not fit. It did not say whether signedness changes reinterpret a pattern, whether every enabled integer width participates, or how a module conversion is folded without compile-time execution. **Chosen:** the kernel enables an application of any enabled integer type to one integer value. The source keeps its own integer type and the destination is the applied type; no contextual or implicit conversion is introduced. The mathematical source value must lie between the destination's inclusive minimum and maximum. Widening a signed value therefore preserves its sign, a negative value never converts to unsigned, and crossing to a signed type rejects an unsigned value above that signed maximum. There is no truncation, wrapping or same-width bit reinterpretation. An integer literal operand is checked immediately in the destination context. A conversion of a module-known integer expression is folded through the same target-aware integer fold as its source; an impossible known result is L0300. At runtime the neutral IR retains the source and destination integer types, and the Linux backend sign- or zero-extends the source before comparing it with the destination bounds. An out-of-range value reaches [1950]'s existing `ud2` trap; an in-range value stores the destination-width pattern. The same conversion opcode continues to carry [0470]'s pointer-to-integer address check. Conversion from a float to an integer and conversions involving bool remain L0304 at this increment. D169 subsequently admits conversion between the two enabled float widths, D170 admits conversion from an enabled integer to either float width, D171 admits the remaining float-to-integer direction, and D172 admits bool as an integer source, and D173 admits integer-to-bool conversion. Float-to-bool conversion and the deferred u128, i128 and packed integer widths gain no spelling through this increment. **The alternatives:** reinterpret the low bits, make narrowing wrap, allow a negative signed value to cross to same-width unsigned, or give module conversions a runtime initializer. Those choices contradict [0310]'s fit and trap rule, make signedness a representation cast, or contradict [1460]'s rule that nothing runs before the entry point. All were declined. **Pinned by** `runtime/integer-conversions`, `runtime/integer-conversion-out-of-range-traps`, `runtime/integer-conversion-signed-overflow-traps`, `runtime/integer-conversion-unsigned-overflow-traps`, `negative/integer-conversion-known-binding-out-of-range`, `negative/integer-conversion-known-out-of-range`, and the `conversion.integer` guarantee row. ### D169 — Float-width conversion rounds an IEEE value, not its carrier **The tour said** that [0310] writes conversion as a type applied to a value, rejects an impossible compile-time conversion, and traps when a runtime value cannot convert. It did not say how f64 narrows to f32, whether underflow or loss of precision is impossible, or what happens to signed zero, infinity and NaN. **Chosen:** the kernel enables f32 or f64 applied to one float value. An untyped float literal is checked directly in the destination context, as every contextual literal is under [1880]. A typed f32-to-f64 conversion is exact. A typed f64-to-f32 conversion rounds to nearest with ties to even, including at the subnormal boundary; loss of precision and underflow to signed zero are ordinary IEEE rounding rather than failures. Signed zero and infinity retain their sign and class. A NaN remains a quiet NaN with its sign; its payload after a width change is not a language-visible identity. A finite f64 which would round beyond f32's greatest finite value is the one impossible width conversion: L0300 rejects it when the source is known under [1880] or [1940], and an otherwise identical runtime conversion traps. Converting infinity is not overflow because infinity is a value of both float types. Module-known conversions fold their IEEE carrier bits with bounded integer work, including the narrowing round bit and sticky bits, so cross-compilation does not borrow the compiler host's float conversion. Runtime Linux x86-64 uses the corresponding SSE width conversion and explicitly distinguishes a finite result overflow from an infinity or NaN source. The existing target-neutral conversion operation now admits every numeric result. D170 subsequently admits its integer-to-float direction, D171 admits its float-to-integer direction, D172 admits bool as an integer source, D173 admits integer-to-bool conversion, D174 admits float-to-bool conversion, and D176 admits bool as a float source. **The alternatives:** require exact representability, silently produce infinity on finite overflow, trap on gradual underflow, expose a NaN payload mapping, or fold module conversions through a host float. Those choices make ordinary IEEE narrowing impractical, contradict [0310]'s impossible-conversion rule, discard gradual underflow, turn an unspecified IEEE payload into source identity, or make cross-target output depend on the compiler host. All were declined. **Pinned by** `runtime/float-width-conversions`, `runtime/float-width-conversion-overflow-traps`, `negative/float-width-conversion-known-out-of-range`, and the `conversion.float-width` guarantee row. ### D170 — Integer-to-float conversion rounds the mathematical integer **The tour said** that [0310] makes conversion explicit and distinguishes an impossible known conversion from one which traps at runtime. It did not say whether integer-to-float conversion requires exact representation, how it rounds, or whether the upper half of u64 participates. **Chosen:** the kernel enables f32 or f64 applied to a value of any enabled integer type. The source is the integer's mathematical value, not its carrier bits. An untyped integer operand first takes [0200]'s default i32 source type; a wider literal therefore writes an explicit integer conversion before the float conversion. There is still no implicit conversion between numeric classes. An exactly representable integer is preserved. Every other value rounds to nearest with ties to even. Every enabled integer, including u64's maximum and i64's minimum, lies inside the finite range of both f32 and f64, so precision loss is ordinary rounding and no integer-to-float conversion can report L0300 or trap. The result of converting integer zero is positive zero. The module folder derives the IEEE exponent and retained, round and sticky bits with bounded integer work. The Linux backend sign- or zero-extends narrower sources before SSE conversion. Because SSE's qword conversion is signed, a u64 above i64's maximum is halved with its low bit retained as sticky information, converted, and doubled; this produces the same nearest-even result without reinterpreting the source as negative. The neutral conversion verifier admits this one mixed-class direction. D171 subsequently admits the other direction; D172 admits bool as an integer source, D173 admits integer-to-bool conversion, D174 admits float-to-bool conversion, and D176 admits bool-to-float conversion. **The alternatives:** require exact representation, saturate at a float boundary, reinterpret an unsigned carrier as signed, use a compiler-host float for module images, or make the conversion implicit. Those choices discard the ordinary IEEE conversion rule, invent a failure despite the float range, lose the upper half of u64, make cross-target output host-dependent, or contradict [0310]. All were declined. **Pinned by** `runtime/integer-to-float-conversions`, `negative/float-to-bool-known-invalid`, and the `conversion.integer-to-float` guarantee row. ### D171 — Float-to-integer conversion truncates before checking range **The tour said** that [0310] makes conversion explicit, rejects an impossible compile-time conversion, and traps when a runtime value cannot convert. It did not say how a fractional float becomes an integer, whether the fractional part participates in the range check, or what infinity and NaN mean as integers. **Chosen:** the kernel enables every enabled integer type applied to an f32 or f64 value. A typed source retains its float width. An untyped float operand first takes [0210]'s default f32 type, so the source is rounded to f32 before conversion; there is still no implicit conversion between numeric classes. D760 subsequently refuses an untyped literal operand whose f32 rounding changes the integer the conversion gives. The finite source is truncated toward zero, then that mathematical integer is checked against the destination's inclusive range. The ordering matters: `u8(-0.75)` is zero and succeeds, while `u8(-1.0)` fails; `i8(-128.9)` is -128 and succeeds, while `i8(-129.0)` fails. Infinity and NaN have no integer result and always fail. A known failure is L0300 under [1880] or [1940], and an otherwise identical runtime failure traps under [1950]. The module folder decodes the IEEE sign, exponent and significand with bounded integer work and checks the truncated magnitude without using the compiler host's floating-point conversion. The Linux backend performs the same carrier decode directly rather than using SSE's indefinite overflow result, which cannot distinguish every valid u64 value from failure. The neutral conversion operation consequently admits either numeric class in either direction; D172 subsequently admits bool as an integer source and D173 admits integer as a bool source; D174 subsequently admits float as a bool source. **The alternatives:** round to nearest, floor negative values, saturate at the destination boundary, reinterpret the carrier bits, use a compiler-host float for module images, or assign an integer sentinel to infinity or NaN. Those choices either invent a different ordinary conversion rule, hide [0310]'s required failure, make cross-target output host-dependent, or give nonfinite values a mathematical integer they do not have. All were declined. **Pinned by** `runtime/float-to-integer-conversions`, `runtime/float-to-integer-out-of-range-traps`, `runtime/float-to-integer-nan-traps`, `negative/float-to-integer-known-out-of-range`, `negative/float-to-integer-known-nan`, `negative/float-to-bool-known-invalid`, and the `conversion.float-to-integer` guarantee row. ### D760 — A float literal's f32 rounding may not change an integer conversion **The tour said** at [0210] that a float literal is distinct from an integer and at [0310] that a float converts to an integer by truncating toward zero. D162 gave a float literal with no context f32, and D171 converted such an operand at that width, so `u64(1.0e18)` was 999999984306749440: the literal lost its low digits to f32's 24 bits before it was converted, and nothing in the program or the report said so. **Chosen:** an integer conversion whose operand is an untyped float literal, negated any number of times, converts it as an f32 still, and is refused, L0350, when the literal's f64 value would convert to a different integer, or one of the two converts and the other does not. The report names both outcomes, and its note names `f64(...)` around the literal for the written value and `f32(...)` for the rounded one; either is typed, and a typed operand keeps its width and is never compared. A literal whose rounding leaves the integer alone, `i64(45.7)` or `u8(-0.75)`, converts as before, and an operand that is an expression of literals rather than a literal is not compared. The comparison is the checker's exact decimal evaluation at each width and D171's truncation, so it does not depend on the host. **The alternatives:** give the operand of an integer conversion f64 as its context, which changes the meaning of conversions that already compile and gives a literal a type from a conversion, a context [0310] does not give it; refuse every untyped float literal converted to an integer, which refuses `i64(45.7)`, the tour's own example, for a rounding that changes nothing; and a warning, which compiles the surprising value all the same, when writing `f32(...)` already says the rounding was meant. **Pinned by** `negative/float-literal-rounded-before-conversion` and `runtime/float-to-integer-conversions`. ### D172 — A bool has the integer image zero or one **The tour said** that bool is a scalar type [0180] and that conversion is an explicit type application [0310]. It did not assign a numeric image to false or true, or say whether every numeric value has a truth value. **Chosen:** the kernel enables any enabled integer type applied to a bool value. False converts to zero and true converts to one. Both values lie in every enabled signed and unsigned integer range, so this direction is total: it cannot report L0300 or trap. Typed and inferred module values fold to the same image, and runtime conversion zero-extends the bool's one-byte carrier before storing the destination width. This increment does not define truthiness. Applying bool to an integer or float remains L0304, as does applying a float type to bool. D173 subsequently admits only zero and one from the integer direction, and D174 settles the float-to-bool direction including negative zero, infinity and NaN. D176 later maps bool's already-fixed images into the two enabled float widths. **The alternatives:** use all-bits-one for true, preserve an unspecified bool carrier, or simultaneously admit numeric-to-bool truthiness. Those choices make the result depend on representation or settle a distinct semantic question without program evidence. All were declined. **Pinned by** `runtime/bool-to-integer-conversions`, `negative/float-to-bool-known-invalid`, and the `conversion.bool-to-integer` guarantee row. ### D173 — Only the canonical integer images convert to bool **The tour said** that conversion is explicit and an impossible conversion is refused when known or traps at runtime [0310]. D172 fixed bool's integer images at zero and one, but did not say whether conversion back accepts only those images or assigns truth to every nonzero integer. **Chosen:** the kernel enables bool applied to any enabled integer value. Integer zero converts to false and integer one converts to true; every other value is impossible. An untyped integer first takes [0200]'s default i32 type, preserving the rule that conversions retain a typed source rather than giving the literal a bool context. A direct literal or module-known chain outside zero and one is L0300. A runtime source is zero-extended from its own width, compared with one, and traps before storing the one-byte bool result when it is larger; a signed negative carrier therefore fails the same comparison without being mistaken for true. Module images fold the source integer before reserving data. The neutral conversion operation now admits bool on either side of the integer boundary. Float-to-bool remains L0304 at this increment. D174 subsequently settles signed zero, fractional values, infinity and NaN rather than inferring them from the integer image rule. **The alternatives:** make every nonzero integer true, accept any value whose low bit is one, saturate into the bool domain, or reinterpret the low byte. Those choices make conversion hide a noncanonical value or become a bit cast, where [0310] instead provides a checked boundary. All were declined. **Pinned by** `runtime/integer-to-bool-conversions`, `runtime/integer-to-bool-out-of-range-traps`, `negative/integer-to-bool-known-out-of-range`, `negative/float-to-bool-known-invalid`, and the `conversion.integer-to-bool` guarantee row. ### D174 — Float converts to bool only at its canonical images **The tour said** that conversion is explicit and impossible conversions are refused when known or trap at runtime [0310]. D172 fixed false and true at the mathematical integer images zero and one, while D173 accepted only those integer images on conversion back. Neither decided how the IEEE values around those images behave. **Chosen:** the kernel enables bool applied to f32 or f64. Positive and negative zero both convert to false because they compare equal as IEEE numbers. Exactly positive `1.0` converts to true. Every other value, including negative one, fractions, infinity and NaN, is impossible. An untyped float first takes [0210]'s default f32 type, preserving its source width before conversion. A direct or module-known impossible source is L0300; the equivalent runtime case traps. Static folding decodes the IEEE carrier with bounded integer work. The Linux backend ignores the sign bit only while recognizing zero, then requires the complete positive-one carrier, so negative zero succeeds but negative one does not. This was recorded as completing explicit conversion among the enabled scalar types, but D172's bool-to-float refusal still remained in the checker; D176 closes that omitted direction without introducing implicit truthiness. **The alternatives:** make every nonzero float true, accept any value that truncates to zero or one, reject negative zero, or make NaN true because it is not equal to zero. Those choices import truthiness, make conversion silently discard a fraction, or distinguish IEEE zeros where ordinary comparison does not. All were declined. **Pinned by** `runtime/float-to-bool-conversions`, `runtime/float-to-bool-invalid-traps`, `negative/float-to-bool-known-invalid`, and the `conversion.float-to-bool` guarantee row. ### D175 — Module float arithmetic is an IEEE carrier fold **The tour said** that module values are known before execution [1460], that the known subset contains operators over known values [1940], and that f32 and f64 arithmetic and comparisons have IEEE behavior [0290], [0350]. D162 left module float operators deferred because using the compiler host's float operations would make cross-compilation inherit that host's rounding mode and NaN behavior. **Chosen:** the kernel enables module-level f32 and f64 `+`, `-`, `*`, `/` and all six comparisons. Operands may be any [1940]-known float expression, including forward or chained module names, conversions, named infinities and NaNs. Their results may initialize scalar bindings or scalar leaves of module arrays, repetitions, structs and variant images. The shared target-neutral evaluator decodes IEEE carrier bits and uses bounded integer significands for addition and division and a double-width integer for the exact product. Every finite result rounds once to nearest with ties to even and retains gradual underflow. Exact cancellation produces positive zero; otherwise the IEEE sign rules preserve signed zero. Arithmetic overflow and finite division by signed zero produce signed infinity rather than L0300 or a trap. Invalid operations and arithmetic with a NaN produce the width's D167 canonical positive quiet NaN; NaN payload propagation is not a source-visible identity. Comparisons equate the two zeros, order finite values and infinities, and leave NaN unordered, so only `<>` is true for an unordered pair. Checking, static aggregate-image lowering and Linux datum emission call the same evaluator. No module initializer runs, no float operation is added to a datum at runtime, and no compiler-host floating-point operation decides an image. The ordinary runtime path remains the SSE implementation D162 already enabled. **The alternatives:** fold through Ada float operations, reject overflow or division by zero because integer module folds do, preserve a host-selected NaN payload, flush subnormals to zero, or keep float comparisons out of module bool images. Those choices respectively make cross-compilation host-dependent, contradict IEEE arithmetic, expose an unspecified carrier detail, lose gradual underflow, or leave [1940]'s operator subset inconsistent by operand class. All were declined. **Pinned by** `runtime/module-float-arithmetic`, the direct checking vectors, and the `float.ieee` guarantee row. ### D176 — Bool converts to exact positive float images **The tour said** that conversion is explicit [0310], that bool has only false and true [0180], and that f32 and f64 carry IEEE binary32 and binary64 [0170]. D172 fixed bool's mathematical images at zero and one but deliberately left a float type applied to bool refused. D174 was then recorded as completing the enabled scalar conversion matrix even though that refusal remained. **Chosen:** the kernel enables f32 or f64 applied to a bool value. False converts to exactly positive floating zero and true converts to exactly positive floating one. Both images are exact in binary32 and binary64, so this direction is total: it cannot report L0300 or trap, and it does not introduce truthiness or an implicit conversion. The target-neutral fold writes the destination width's exact IEEE carrier for literal, named and computed module-known bool values, including scalar leaves of array and struct images. Runtime Linux code zero-extends the canonical one-byte bool and converts that zero or one into the selected SSE width. The neutral conversion verifier admits bool as a source for either numeric class. At this decision, f16 and [1975]'s external floating-point ABI remained deferred; the internal scalar conversion changed neither boundary. D204 subsequently enabled f32 and f64 in the selected C ABI. f16 remains refused. **The alternatives:** reinterpret bool's byte as float bits, produce negative zero for false, route through a contextual integer conversion, or keep the direction refused. Those choices contradict D172's mathematical images, make the result representation-dependent, add a conversion not written by the program, or leave the claimed scalar matrix incomplete. All were declined. **Pinned by** `runtime/bool-to-float-conversions` and the `conversion.bool-to-float` guarantee row. ### D266 — A conversion may apply the type as written **The tour said** that conversion is a type applied to a value [0310]. D15 makes an alias another name for the same type; D168--D176, D188, D199 and D213 decide which values a type may convert. Requiring a name before the value's opening parenthesis nevertheless made an immutable byte view require an alias, even though `[]u8` already writes that type. **Chosen:** a conversion may write any enabled type expression as its head. `[]u8(text)` and `byte_view(text)`, where `byte_view: type = []u8`, apply the same exact type. This changes spelling only. The scalar conversion matrix, range constraints, distinct identity and exact-base extraction, text validation, reference permission and origins, known-value folding, runtime traps and `unchecked` behavior remain the existing rules. No implicit conversion, ordinary composite identity conversion or pointer permission change follows. Nominal bodies, atom unions, `distinct` and range constraints still require their declarations; this adds no anonymous type or identity. A written application has one expression inside its final parentheses. Starting with a bracket, a single bound followed by `]` and an element type begins an array-type application, and empty brackets followed by an element type begin a slice-type application. Thus `[2]i32(hidden)` extracts the array representation of an appropriate distinct value, while `[4, 5]`, `[4 of 5]`, `[of 5]`, `[4, of 5]` and bare `[]` retain their literal, repetition and empty-slice meanings. A comma or contextual `of` within that outer bracket prevents a type prefix. Once an element type starts, an absent value list or an incomplete nested type is a malformed written application, not an empty slice or an array followed by another expression. The element type must start on the bracket's line. A following declaration boundary, `name:` or `name :=` (including `mut name`), instead leaves the bracketed expression complete. Thus an array literal followed by another declaration on the same line retains its existing meaning. A complete following assignment destination, an indexed call head or a destructuring list followed by `:=` likewise starts the next statement. Recognizing those boundaries does not reinterpret an incomplete type prefix: for example, `[]u8[0]` without a following assignment or call remains malformed. `ptr(value)` retains [0470]'s contextual integer-to-pointer conversion and its untracked origin. `ptr T(value)` instead applies the written pointer type, so it can extract D213's exact distinct representation but cannot convert an integer to a pointer. `ptr mut T` retains its written permission. A parenthesis immediately after `ptr` begins the contextual conversion unless its balanced list is followed by `->`, which identifies a function pointee type. `any(value)` likewise retains its contextual construction; `any C(value)` applies a written erased type. A leading balanced parameter list followed by `->` begins a function signature. When the complete signature is followed by `=`, including on the next line, it retains the anonymous-function meaning; otherwise the signature is a written conversion prefix. Other parentheses retain their expression and struct-literal meanings. Written `extern(c)`, `extern(interrupt)` and `extern(naked)` signatures retain their convention and target restrictions; extracting a machine-convention function value does not permit an ordinary call to it. Type prefixes nest as in declarations, for example `[][2]u8(hidden)` and `ptr []u8(hidden)`. At the terminal name the last parenthesized list supplies the value. A preceding positional type-argument list remains part of the head: `tag(u32, 7)(value)` applies that concrete type, and `[]array(u8, 2)(hidden)` applies the slice of that concrete element type. Names inside type arguments, function parameter and return lists, and array bounds are parsed in their own delimited positions. Ordinary single-list calls, labelled constructors and generic applications retain their existing classification. A written conversion admits neither labels, multiple value arguments nor call-site recovery. A balanced second list followed by `:=` starts a destructuring binding, so an ordinary call immediately before that binding remains complete rather than becoming a generic type head. An application must first denote an enabled type: D135's existing alias-result restrictions still refuse a generic slice or function alias, in a declaration and in a written conversion alike. The application is a primary under [1820], and ordinary unary and binary precedence applies to its result. Its value is evaluated exactly once at the same point as an alias conversion [0410]. Its result cannot be indexed, selected or called directly, including through parentheses; bind it first, as for an ordinary call result. Type checking refuses an otherwise grammatical application when that exact destination and source lack an existing conversion. **The alternatives:** admit only slice heads, infer a type from every literal followed by parentheses, reinterpret `ptr T(n)` as `ptr(n)`, allow arbitrary postfix operations on conversion results, or add identity conversions while extending the spelling. Those choices leave other alias-reachable types without a written form, change existing literal or origin rules, change expression precedence and the call-result boundary, or grant conversions this extension was not asked to decide. Requiring an extra separator between the type and its value was declined because the balanced type-argument lists already distinguish the head from its one final value list. **Pinned by** `positive/written-type-composite-extraction`, `positive/written-type-text-conversions`, their runtime counterparts, `runtime/written-type-literal-pointer-controls`, `runtime/written-type-operand-order` and the `written-type-` prefix boundary, refusal and origin fixtures. ### D177 — A module bool is a static image, not routine control flow **The tour said** that bool has only `false` and `true` [0180], that its logical words return bool [0340], and that `and` and `or` short-circuit from left to right [0410]. [1460] says nothing runs before the entry point, while [1940] admits every [1820] operator over module-known values. D24 already applies those rules to scalar leaves of module aggregate images. The remaining scalar path nevertheless lowered `and` and `or` through routine-style CFG, and the backend's datum fold correctly rejected its `Branch` instruction. **Chosen:** the kernel makes every scalar module bool a target-neutral static image. The one shared lowering-time folder evaluates literal, named, forward and chained module-known operands, comparisons, `not`, `and` and `or`; its existing logical cases visit the left operand first and visit the right operand only when the result still depends on it. The same folder continues to write bool leaves in fixed arrays, repetitions, structs and variants. A bool datum's neutral block carries no computed value, and datum emission reads its canonical zero-or-one image directly, so no initializer is executed and no CFG `Branch` reaches data emission. Routine expressions keep their existing CFG and observable short-circuit behavior. This is an implementation conformance repair, not a new source rule. Checking still validates every written subtree before folding: short-circuiting does not hide an ill-typed operand, a call, an impossible integer operand, or another initializer that [1940] refuses. Module value lookup remains independent of declaration order [0130], and a cycle remains refused even if another declaration could skip a reference to it. **The alternatives:** teach the backend datum fold to interpret CFG, add a non-short-circuit logical opcode, or retain a second scalar-only syntax folder. Those choices respectively turn static data into executable control, contradict [0410], or let scalar and aggregate images disagree. All were declined. **Pinned by** the lowering case `module bools become static images`, `runtime/module-known-short-circuit-bools`, `negative/module-bool-from-itself` for the cycle, the generated IR, and the `module.images` guarantee row. ### D200 — A comparison takes one register-sized value with one equality **The tour said** at [0350] which six comparison operators exist and at [1890] that they want one type on both sides and give a bool back. It did not say which types may stand on those sides. The compiler compared type kinds alone, so `ptr u8 == ptr u32` was accepted and lowered as an address compare, and `[]u8 == []u8` or `any C == any C` passed the checker and was an internal defect in lowering. **Chosen:** a comparison operand is a scalar of [1790], an atom set (identity only, as [1890] already said), a pointer, or a function value. Atom equality and inequality compare declaration identities across any two structural sets; neither set must include the other. This changes no store or call-argument subset rule. Two pointers compare by address and must point at one type; permission does not enter, because [0440] lets a mut pointer stand where a plain one does and an address comparison writes through neither. Two function values must agree in signature, as before. A slice, an erased `any` value, a fixed array and a struct are refused at the operator with L0301, naming the operand. **The alternatives:** elementwise equality for slices and arrays, fieldwise equality for structs, and base-and-length identity for slices were each considered. Elementwise equality needs a defined equality for the element, which reopens the question one level down and silently costs a loop; base identity for slices answers a question nobody asks. All were declined for the pre-v1 slice; a later version can add an operator or a `core` routine without changing what the compiler accepts today. **Pinned by** `negative/slice-comparison-refused`, `negative/any-comparison-refused`, `negative/pointer-comparison-referent-mismatch` and `positive/pointer-comparison-same-referent`, `runtime/r490-generic-atom-identity`, `runtime/r490-lexical-module-observation` and the verifier case `atom comparisons keep identity`. ### D224 — Ordinary module arithmetic has a wider folding range **The tour said** that a module value is known before entry [1460] and ordinary runtime arithmetic traps on overflow [0300]. The bootstrap IR's decision explicitly admitted `x: u8 = 200 + 100 - 100`: the intermediate 300 exists only in the folder. [1940]'s phrase about a fold that no type holds left the final image and its intermediates insufficiently distinguished. **Chosen in the bootstrap and retained:** ordinary module integer arithmetic uses the signed, symmetric folding range derived from the widest enabled integer magnitude, `-(2**64 - 1)` through `2**64 - 1`. Every intermediate stays within it, and the final image must fit its source type. Neither the host word size nor a 32-bit target narrows that folding range. Literal typing, explicit conversions and the type-dependent wrapping, bitwise and shift rules remain separate. Runtime arithmetic keeps its source width and overflow checks. This records existing behavior; it adds no compile-time execution or unbounded integer type. **The alternatives:** checking every intermediate at the destination width would reject the already adopted u8 example. Unbounded mathematical folding would remove the kernel's explicit limit, and silently wrapping a module fold would replace an error with a different image. None describes the existing contract. **Pinned by** the extended `positive/module-fold-that-fits`, the existing `negative/module-scalar-fold-overflow`, and `module folds use their own integer range`. The bounded IR control checks exact images and retained runtime u8 operations on both target widths, plus final-image and positive/negative fold-range overflow refusals. Container capacity arithmetic inside a function remains subject to the runtime rule. ### D1090 — Inside a module fold, a conversion and a width-dependent operator take only what their type holds **The tour said** at [0310] that an impossible conversion of a value known at compile time is a compile error, and D224 gave ordinary module arithmetic a wider folding range while saying that conversions, shifts, bit operators and wrapping operators keep their own type-dependent rules. The fold compared only its final value with the binding's type. So `a: i64 = i64(u8(k))` with a `k` of 1000 held 1000, `(200 + 100) >> 1` as a `u8` was 22, the 300 having been cut to eight bits first, and a range subtype applied inside a larger expression reached the backend unchecked. **Chosen:** the wider range belongs to `+ - * / %`, comparison and unary minus alone. A conversion inside a module value takes only a value its target holds: an integer its integer type holds and zero or one for `bool`; a range subtype's bounds held there too until D1661 removed the form. A shift, `&`, `|`, `^`, `~` and a wrapping operator take only operands their operand type holds; a shift's amount stays under [0320]'s own rule. A value that is not held is L0300 at the conversion or the operand, naming the value and the type, and a binding that reads the refused one reports nothing more. A wide intermediate that only ordinary arithmetic and a comparison meet folds as D224 says. **The alternatives:** cutting the value to the type's width, which is what D224 itself declines, an image nobody wrote in place of an error; and narrowing every intermediate to its type, which takes back D224's wider range. Both are declined. **Pinned by** `negative/module-fold-operand-outside-its-type`, with `runtime/module-negative-mask-operand` for a negative operand its signed type holds. ## DECISIONS: POINTERS AND RAW STORAGE Addresses, the absent pointer, and the operations that read storage the language does not otherwise describe. ### D189 — A one-atom pointer union is a pointer whose empty case is zero **Amended by D1657.** Its examples' inline struct bodies are written with `struct ... end`; the pointer union stands. D235 later gave two or more atoms beside a pointer a two-cell union and retired `Reference_Union_Extent`'s two-atom arm, and D1659 withdrew that form: a pointer union holds one atom, and two or more beside a pointer are L0696. The one-atom representation below is unchanged. D429 later admits a comparison with one of the union's own atoms, so the comparison refused below is one between two unions or with a pointer. **The tour said** that there is no null, that "maybe a pointer" is an ordinary union of an atom and a pointer type, that with one atom the compiler represents it as a plain pointer with 0 for the empty case, and that the spelling does not decide how a union of several atoms and a pointer is laid out [0480]. It did not say how such a union is written past the one shown example, how the empty case is constructed, how the present case is named in a match, what the union may not do that a pointer may, or which origin the empty case carries. **Chosen:** [1795]'s `atom_union` admits one `pointer_type` member beside its atom names, and a union that flattens to exactly one atom identity and exactly one pointer type is the type `ptr [mut] T` carrying that atom as its empty case. It occupies one target pointer carrier with zero reserved for the atom, which is what `Landin.Checking.Reference_Union_Extent`'s one-atom arm has measured since local lifetime checks were built and now has a caller for. Order does not matter: `ptr mut u32 | none_found` and `none_found | ptr mut u32` are the same type, because [1870] already says a union is structural. The atom's singleton widens into the union and so does the bare pointer, in the direction [1870] gives atom sets; neither direction reverses, so a plain pointer fills a union parameter and a union does not fill a `ptr T` one. The union is not a pointer, and the six positions that would read its carrier as an address are refused by name because each is a path to a dereference of the reserved zero: `.val` in a read or an assignment target, `addr` of a `.val` reached through one, an integer conversion, `any` construction, a comparison, and an argument or result position wanting `ptr T`. The first five are L0335 here; the last is [0440]'s existing reference-agreement refusal. `ptr(n)` into a union position is L0335 for the same reason, and `zeroed` stays the aggregate-value L0304 because [1870] states that no zero or default atom exists — an all-zero image is not the atom even though the atom's representation is zero. `match` [1210] is the only way through. Its two cases are the atom name and the reserved word `ptr`, which needs no new keyword because [1760] already reserves it, and which is a syntax node of its own rather than a name, so resolution has nothing to look up. A `ptr` arm may carry one binding of the plain pointer type; it is optional, definitely assigned on entry to the arm, and read-only, and `inout` on it is L0333 citing [1220] because writing through it would write the union's own carrier and not a payload; D433 later admits `sink` on it. A case named twice is L0311, a case named by neither an arm nor `_` is L0312, and `_` must be last, which are the same three rules an atom set already has. A `ptr` arm on an atom-set or variant subject is L0333. The empty case contributes no origin at all, and in particular never the `Untracked` fact [0470]'s integer-to-pointer conversion sets, because that fact *suppresses* the frame-escape refusal. On a return edge provably carrying this empty case, [0790]'s exact `from` contract has no actual reference origin to compare; it does not reinterpret absence as an untracked reference. The bound pointer takes the subject's own origin, so a union built from `addr local` still refuses an escaping use of the binding with L0314. Lowering is one comparison against zero and the CFG branch a match already emits; the empty case lowers to a `usize` zero rather than the atom's dense nonzero code, which is the one place a wrong carrier could be produced. Two or more atoms beside a pointer is refused by name with L0304 citing [0480] until its layout is decided (D235). The tagged carrier [1870] describes needs an IR pair, storage, an ABI position and a backend of its own, which is a representation increment and not this one; [1870]'s sentence about that placement is kept and qualified rather than deleted, and `Reference_Union_Extent`'s two-atom arm stays as the recorded measurement. A union of two pointer types is L0338: there is one carrier and nothing to tell two pointers apart with. **The alternatives:** giving the union its own `Landin.Types.Type_Kind` would have named every site the checker must guard, at the cost of a much larger diff and a disturbed `Settled` band; the flag on the pointer descriptor was chosen instead because the representation genuinely is a pointer, and the six positions above are the audit that flag owes, which is why each is pinned by a negative fixture of its own rather than by the guard alone. Making the `ptr` arm's binding required rather than optional would be easier to explain and less useful for a discard-shaped arm. Spelling the present case `_` with narrowing would need flow-sensitive typing, which the kernel has none of, and a type-named arm is not in the grammar. Admitting the union inline in a `type` position rather than only through [1795]'s named declaration would be a change no atom union has today. Laying the multi-atom case out now would have made this increment a representation increment. All were declined. D206 supersedes the null-construction gap recorded below: [1975] now requires known-zero refusal and an always-on dynamic check, and allocator absence uses the union. The following is the state D189 handed to that work, not a present permission to construct a null pointer. `ptr(0)` remains accepted [0470] and `runtime/core-mem-allocators` uses it as a failure sentinel five times, so null is still mintable on the pointer side even though [1580] states that it is refused. That contradiction is real, it is not resolved here, and it belongs to [1580] and the C boundary with the rest of the foreign-boundary work, which records it rather than leaving [0480] looking closed while its headline sentence is evadable. **Pinned by** `positive/pointer-unions`, `runtime/pointer-unions`, `negative/pointer-union-holds-one-atom`, `negative/pointer-union-two-pointers`, `negative/pointer-union-dereference`, `negative/pointer-union-assignment-target`, `negative/pointer-union-address-of-referent`, `negative/pointer-union-any-construction`, `negative/pointer-union-case-named-twice`, `negative/pointer-union-present-arm-named-twice`, `negative/pointer-union-is-not-a-pointer`, `negative/pointer-union-match-not-exhaustive`, `negative/pointer-union-frame-escape`, `negative/pointer-union-comparison`, `negative/pointer-union-integer-conversion`, `negative/pointer-union-from-an-integer`, `negative/pointer-union-inout-binding`, `negative/pointer-union-zeroed`, `negative/pointer-case-arm-is-not-an-atom`, the generated lexical and IR records, and the `pointer.optional` guarantee row. `negative/r440-parser-frame-arena` also pinned it until D288, through the derived parser's entries, a union returned `from` an `escaping` arena; the parser now takes the arena handle by value and its entries borrow nothing, and that fixture's L0314 is the checked `arena_over`'s refusal of frame backing. ### D206 — Null construction cannot evade the pointer union **The tour said** at [0470] that integer construction loses origin, at [0480] that pointers are non-null, and at [1580] that `ptr(0)` is refused. D189 left the compiler's contrary integer-conversion path for this boundary to close. **Chosen:** [1975] refuses known zero after target-width conversion, including closed folds, and checks dynamic converted zero even inside `unchecked`. Pointer-union transport remains one target carrier, with no origin in the atom arm and the original origin in the narrowed pointer arm. [0790]'s exact `from` comparison applies only on an edge that actually returns the reference; a provably empty arm has no origin and is not `Untracked`. A call-site `else` still handles failure, not absence: a successful union is matched normally. Allocator and disposed backing use named atom/pointer unions; a successful `dispose` clears to the atom and a repeat reports `empty`. **The alternatives:** keeping zero as an untracked pointer contradicts the niche. Testing before narrowing misses target-width zero; removing the check in `unchecked` reopens the contradiction. Replacing null with `ptr(1)` hides absence in a false allocation. A second tagged wrapper wastes a word where the existing one-atom union already expresses the state. All are declined. **Pinned by** `runtime/null-pointer-dynamic-traps`, `runtime/null-pointer-unchecked-traps`, `runtime/null-pointer-union-call-else`, `negative/null-pointer-union-call-else-frame-escape` and `runtime/core-mem-dispose-empty`, with `negative/r440-null-pointer-folded-zero` and `negative/r440-null-pointer-unchecked-zero` for the static refusals of a folded zero and of `unchecked` construction. `negative/r440-parser-frame-arena` pinned the narrowed arm's origin as well until D288, after which its L0314 is the checked `arena_over`'s and the derived parser's entries borrow nothing (D189). ### D1104 — A module pointer's address is folded and held to usize **The tour said** that a module value is an image the compiler builds [1460], and [1940] refuses a module integer whose fold its type does not hold, since an image has no moment in which to trap. [1975] converts the operand of `ptr(integer)` to the target's `usize` and refuses a known zero. The module check folded the address only to ask whether it was zero, so a negative or overflowing address, `ptr(base - back)` with `back` the larger, passed checking and stopped emission with an internal compiler defect. **Chosen:** the address of a module `ptr(integer)`, as a binding's value, an array element or a struct field, is folded like any module integer. A fold that overflows, or a value that the operand's own type or the target's `usize` does not hold, is refused with L0300 at the address. **The alternative** was to wrap the address into `usize` as a two's complement conversion would. It was declined: the same expression bound to a `usize` is refused, and a wrapped device address is a wrong address that nothing later reports. **Pinned by** `negative/module-pointer-address-does-not-fold`. ### D235 — Several atoms beside a pointer store the atom's own code beside the pointer **Superseded by D1659.** A pointer union holds one atom; two or more beside a pointer are L0696, the two-cell union is gone from every backend, and what follows is history. **The tour said** that "maybe a pointer" is an ordinary union of an atom and a pointer type, and that the spelling does not decide how a union of several atoms and a pointer is laid out [0480]; [1870] placed that form as a tag beside the pointer. D189 enabled the one-atom form as a pointer reserving zero and refused two or more atoms beside a pointer by name until its layout was decided, recording that the tagged form needs an IR pair, storage, an ABI position and a backend of its own. **Chosen:** a union that flattens — through aliases, parameterized aliases and member unions, ignoring order and repetition — to two or more atom identities and exactly one pointer type is one structural type: its atom set plus the pointer type, whose `mut` is part of the identity. It is a two-cell aggregate with no source declaration. The first cell is the atom-set carrier, holding the atom's own dense nonzero code exactly as a value of that set would; the second is one target pointer carrier. Code zero, which no atom has, marks the present case, whose non-null pointer the second cell holds. The cells take ordinary natural placement: 16 bytes aligned 8 on Linux x86-64 and Darwin arm64, 8 bytes aligned 4 on Cortex-M0. Every case is built in a cleared temporary and copied whole, so an atom case leaves its pointer cell zero, and a module image does the same. The union is passed, returned and copied as an ordinary aggregate, by address in the internal convention on every implemented target. Widening never reverses. An atom singleton or an atom set contained in the union's set widens by copying its code. A pointer of the member type, or one that relaxes to it by [0440], widens as code zero and the pointer. A one-atom union whose atom is in the set and whose pointer relaxes to the member widens with its zero carrier becoming that atom's code; a smaller several-atom union copies both cells. An `inout` or `sink` parameter takes only a place of exactly the same union. Match is D189's: arms name the set's atoms or `ptr` with an optional read-only binding, exhaustiveness covers every atom and `ptr`, and an atom outside the set, a duplicate or a missing case, an `inout` `ptr` binding and a `ptr` arm on another subject keep their reports. Lowering loads the code; zero selects the `ptr` arm and binds the pointer, and any other code dispatches exactly as an atom-set match. The positions D189 refuses for the one-atom form are refused identically: `.val`, `addr` of a `.val`, an integer conversion, `any` construction, a comparison, a `ptr T` argument or result, `ptr(n)` into one, and `zeroed`. The one-atom form retains L0301 for its invalid context; the many-atom form reports L0328 because it has no zero image. The pointer case carries the stored pointer's origin and an atom case none, so a union built from `addr local` still refuses an escaping use of its bound pointer. A module union takes an atom or another module union as its static image; an address initializer is the one-atom form's L0305. A call returning a plain pointer cannot fill a union through an atom `else`: that recovery would need a new lowering, and remains L0301. No IR instruction, ABI position or instruction selection is added. The code cell is typed with the union's atom set, and every backend already traps an atom-typed load that finds a non-member; the call-failure status channel was the one load allowed to find the zero sentinel. `Landin.IR.Admits_Reserved_Zero` now names both — that channel and a union's code cell in a frame slot — and the implemented backends ask it instead, reaching the zero-skipping selection they already had. The verifier holds a union nominal to exactly its code and pointer cells. DWARF describes the union as a structure named by its canonical spelling — atoms by spelling, ties by declaration identity, then the pointer type, for example `denied | none_found | ptr mut u32` — with an `atom` member at offset zero and a `ptr` member at the pointer's offset. GDB and LLDB show both members in an atom case and in the pointer case. **The alternatives:** a tag holding a case index, as a variant part does, was declined because widening from an atom set or a smaller union would then renumber rather than copy, while the code costs nothing more: pointer alignment already rounds a one-byte tag up to the pointer's width. Storing atoms in the pointer's low bits was declined because it depends on the pointee's alignment exceeding the case count, which a byte pointer never does. Reserving small addresses for the atoms, as the one-atom form reserves zero, was declined because Cortex-M0 flash begins at address zero with the vector table, so small addresses are real pointers there. Lowering onto a hidden variant part was declined for the same renumbering. Keeping the form refused was declined: the representation needed no new backend machinery, and [1700] reads atoms as one idea wherever they appear. **Pinned by** `negative/pointer-union-holds-one-atom`, which refuses the form since D1659. ### D238 — A device access is an operation over an ordinary pointer **The tour said** that a register is reached through a `volatile ptr` [0070] [0460] [0850], that a register is a parameterised type `register(t, read:, write:, reset:)` whose field reads as a `t` [0740], and that `set(X)` generates a packed struct of bool from an encoded union [0540] [0730]. D227 enabled scalar volatile accesses as `compiler.volatile_load` and `compiler.volatile_store`. D228 enabled the register image with its two explicit operations `compiler.register_read` and `compiler.register_write`, refused every synthesized device field update, and left the wrapper and `set(X)` unenabled. The `volatile ptr` shape was refused by name, and the checked-in device fixtures translated prototype 1 to D227 and D228 forms instead. **Chosen:** all three are withdrawn. A device access is an operation — D227's two scalar operations or D228's two register operations — over an ordinary pointer, and a generated module writes one small typed function per register over them, with the image's decode and encode beside it and its reset value as a constant. The encoded union still places each named bool field of a set, and the generator writes those fields out; inside a larger image they are offset by where the set begins, as D228 already says. The `volatile ptr` shape keeps its named L0010, now a withdrawal with the four operations as its migration guidance. `register(...)` and `set(X)` never had a named refusal and remain an ordinary parse error and an unresolved type application. [0070], [0460], [0470], [0540], [0730], [0740], [0760] and [0850] are rewritten to the operation form, and prototype 1's preamble records the withdrawal while its sketch keeps the historical spelling as the design record, as the device fixtures already did for `register` and `set`. The evidence is the executed derivation. The complete derived prototype-1 driver runs on Cortex-M under QEMU, with its synthetic device model, through the generated RP2040 modules' accessors and explicit bool image fields; it needed no volatile pointer type, no wrapper and no set former, and its derivation maps every sketch use to that form. D228 had already made the wrapper's central promise unrealizable as sugar: a field of `register(t, ...)` type would read and write through the device, D228 refuses every synthesized field update, and so the wrapper could only ever be the explicit read, local update and write that the generated functions spell. A `volatile` qualifier would be a second permission on every reference beside `mut`, which [0440]'s relaxation, `addr`, field projection and generic identity would all have to carry, while D227 already says what each access orders. `set(X)` is a type-level generator, which retained position RP3 and [1540] place in generator programs, and general SVD generation is the companion tool's. **The alternatives:** a pointer qualifier with volatile `.val` accesses and field projection was declined as a second permission axis for a surface no executed program needed. A builtin `register(t, ...)` type whose field accesses call D228's operations was declined because the explicit read/update/write it would hide is what D228 requires to stay visible. A builtin `set(X)` former was declined for RP3's reason. Keeping the three pending for a successor was declined because an executed driver is the evidence a successor would have waited for. **Pinned by** `negative/r491-volatile-pointer`, whose recorded report carries the withdrawal note, `runtime/r640-register-images`, `negative/r640-register-no-read`, `negative/r640-register-no-write`, the complete driver of `compiler/tests/driver/DERIVATION.md`, and the `packed.register` guarantee row. ### D243 — An `inout` reference place keeps its exact type **The tour said** that a mut reference satisfies a plain one and never the reverse [0440], and that an `inout` parameter may replace the value it was handed and the change comes back [0900]. It did not say which of the two directions an `inout` argument is. [0440]'s own example is an `in` parameter. **Chosen:** an `inout` argument whose parameter is a pointer or a slice must have exactly the parameter's reference type, permission included. `ptr mut T` does not fill `inout slot: ptr T`, and `[]mut T` does not fill `inout s: []T`. This holds however the call is made: directly, through a function value, with a field or an element as the place, forwarding an `inout` parameter, or passing an `inout` match payload on. An `in` reference parameter keeps [0440]'s relaxation, and a pointer union place was already exact [1870]. **A competent reader could have** applied [0440] at every reference argument, which is what the compiler did through 0.2.0. It is unsound: the callee stores a read-only reference into the place, and the caller then holds it as `ptr mut T` and writes through it. The program ```landin anchor: u32 = 5 store: (inout slot: ptr u32) -> none = slot = addr anchor end store ``` called as `store(p)` with `mut p: ptr mut u32` then wrote 7 into the immutable `anchor` without `unchecked`, which is [0440]'s reverse direction reached through [0900]'s way back. The other reading, that `inout` checks only the way in and the way out is the caller's problem, was declined because nothing the caller writes afterwards can show it: the store happened in another function. **Pinned by** `negative/inout-pointer-is-exact`, `negative/inout-slice-is-exact`, `negative/inout-pointer-through-function-value-is-exact`, `negative/inout-pointer-field-is-exact`, `negative/inout-pointer-forwarded-is-exact` and `negative/inout-pointer-match-payload-is-exact`. ### D429 — A pointer union compares with one of its own atoms **Amended by D1659.** A pointer union holds one atom, so the comparison is with that atom, true exactly when the carrier is zero; the several-atom case below is history. **The tour said** at [0480] that coming back out of a pointer union is a match, and D189 refused a comparison among the six positions that would read the carrier as an address, because comparing two carriers would tell the empty case from a pointer without matching. Asking only whether a union holds its atom therefore took a whole `match` ending in `true` or `false`; `platform/posix` converted a union to `usize` through one to compare it. **Chosen:** `u == a` and `u <> a`, where `u` is a pointer union of one atom or of several and `a` is an atom value whose atoms all belong to `u`'s set, answer whether `u` holds that atom, with the atom on either side. No address is read and none can be obtained: the pointer still comes out only through a `ptr` arm. A one-atom union holds its atom exactly when its carrier is zero; a union of several atoms holds one exactly when its code cell holds that atom's code, which is zero for the pointer case (D235). Both operands are evaluated, left first. Comparing two unions, or a union with a pointer, stays L0335, and its note now names both routes, the atom test and `match` with `ptr (p):`. **The alternatives:** equality between two unions, the same atom or both present with equal addresses, which is what `platform/posix` wanted, but adds pointer identity through the union and a compare-and-branch over two cells; it waits for a second consumer. Keeping every comparison refused and naming the `match` route. Neither revives D189's declined `_` narrowing: the subject keeps its type, and no binding is made. **Pinned by** `runtime/pointer-union-atom-comparison`, and by `negative/pointer-union-comparison`, which compares two unions. ### D1659 — A pointer union holds one atom **The tour said** at [0480] that a pointer may share its storage with atoms instead of a null. D235 gave two or more atoms a code word beside the pointer, and D429, D874 and D1115 build on it. All 28 of the library's pointer unions hold one atom. **Chosen:** a pointer union holds exactly one atom, stored as the zero address (D189); the form with two or more leaves, and the two-cell aggregate it needs leaves every backend's IR, call convention and widening. A pointer with several states is a one-atom union with an error set, or a record of a state and a pointer. The maintainer chose this on 2026-11-21, answering the candidate list the third roadmap's simplification phase decides. **The alternatives:** keeping the several-atom form, whose second cell every target carries for programs nobody has written. Declined. **Pinned by** `negative/pointer-union-holds-one-atom`, which refuses the form written in either order and in a signature, flattened from a one-atom union and reached by applying a parameterized alias, and by `negative/r490-union-alias-application-reports`, whose imported application makes one. The refusal carries no fix: the rewrite is the program's design. Fixtures that used the form in passing hold one atom now: `runtime/match-sink-binding`, `runtime/match-arm-names-several-cases`, whose pointer-union arm names the atom and `ptr` together, `runtime/r720-feature-interactions`, `runtime/pointer-union-atom-comparison`, and the debugging program's union, which GDB and LLDB show as the pointer it is. D235 and D874 are superseded and D429 amended. ### D2181 — A pointer union refused at an application names the template's union **The discrepancy:** D1659 refuses a pointer union of two or more atoms where a parameterized alias's application makes one, and the refusal stood at the application alone, while the one-pointer refusal beside it names the template's member. **Chosen:** at an application, L0696's "a pointer union holds one atom" names the template's union as its second place, "the template's union"; written in place, it names none. **The alternatives:** a note naming the template, which would spell in prose what a label shows. **Pinned by** `negative/pointer-union-holds-one-atom`, whose application `joined(optional)` names `t | denied`. ## DECISIONS: ARRAYS, SLICES AND TEXT Array identity and the contextual storage an array value is formed in, then slices and the text views over them. ### D17 — An array's identity is its length and its element **The tour said** that an array is a value, that assignment copies it and that its size is part of its type [0520]. It says what an array _is_ and never says when two of them are the same type, which for a struct [0710] answers by naming the declaration that wrote it. **Chosen:** structural. `[4]u8` and `[4]u8` are one type wherever they are written, and `[4]u8` and `[8]u8` are two, and so are `[4]u8` and `[4]i8`. D15's alias keeps that identity like any other, so `row: type = [4]u8` gives the same type a second name. The evidence is [0520]'s own sentence: size is part of the type, which is a description of a shape and not of a declaration — and [0370]'s `sizeof` and `lenof` ask a type what it measures without asking where it was written. **Why not [0710]'s rule:** that paragraph is about a struct, and it gives its reason in the same breath — a value typed as an anonymous struct "never becomes a same-shaped named type", because a struct body introduces a type where no existing type was. `[4]u8` introduces nothing: it describes a shape that the length and the element already determine. D15 makes a declaration without `distinct` name an existing type, and this is one. **The alternative:** nominal, one type per declaration, which would make two `[4]u8` declarations different types and put arrays under [0710] with structs. It was declined because nothing in the tour reaches for it and because it would leave a program no way to write the type of something it did not declare: `sizeof [4]u8` and a parameter of `[16]u8` both name a shape rather than a declaration, and under a nominal rule neither would mean anything. **An array of a struct** follows from this rather than needing its own answer, and is stated here so nobody reads the gap as a question. The array is structural and the element is whatever it is: two `[4]point` are one type exactly when the two `point`s are, which is [0710] doing its own work inside this rule and not an exception to it. D122 supplies the aggregate element carrier, D127 its known whole-element contexts, and D134 the computed ones; the earlier aggregate layout evidence did not pretend its scalar-only array shape represented them. **Pinned by** `positive/array-type-is-declared`, `positive/array-types-alias-and-agree`, `positive/measurement-of-fixed-arrays`. ### D18 — An array index is `usize`, and an array fits the target's `usize` **The tour said** that `usize` is the unsigned integer for byte counts and indices [0160], that an array's size is part of its type [0520], and that an index is checked before its address is computed [0580]. It did not say whether every integer type could index an array or how large an array type could be. Its packed-register example used `u32`, which answered differently on targets of different widths without stating that it meant to. **Chosen:** an array index is exactly `usize`. An untyped literal in the index position receives `usize` as its context; a value already typed `u32`, `u64`, `isize`, or any other integer is refused rather than converted. The byte extent of an array must be no greater than the largest value the target's `usize` can hold. Thus `[4294967296]u8` is a type on a 64-bit target and is refused on a 32-bit one, while `[4294967295]u8` fits both. **Why the two answers are one rule:** [0580]'s address computation consumes a byte offset. Its index and its greatest object extent therefore share the one target width [0160] gives for addressing; neither inherits a fixed width from the compiler host. The count is not itself bytes — an element may occupy more than one — so legality is decided from `length * sizeof element`, without performing that multiplication after it has already overflowed. **The alternative:** accept any integer and compare it with the length. That looks permissive, but using a `u32` where the operation consumes `usize` is an implicit conversion, which [0190] does not provide, and using `i32` gives a negative case that the type of an index need not have. A fixed `u32` limit was also declined: it needlessly truncates a 64-bit address space and cannot follow a target narrower than 32 bits. **Pinned by** `negative/index-is-not-usize`, `negative/index-past-the-default-type`, the target-parametric checker case `array extent follows usize`, and `runtime/large-array-offset-is-addressed` on Linux x86-64. ### D19 — A known element of a local array is assigned independently **The tour said** that a local declared without a value has to be assigned on all paths before it is read [1910], that an array's elements are indexed from zero [0520], and that a compiler-known index is a literal or unary minus over one [1880]. It did not say whether assigning one element assigned the local or what fact a later element read required. **Chosen:** a declaration-only fixed-array local has one definite-assignment fact for each compiler-known element that the function reaches. Writing `items[2]` establishes only element two; reading or stepping `items[2]` requires that same fact on every arriving path, and says nothing about any other element. Branches intersect these facts exactly as they intersect a scalar local's fact. The compiler keeps only facts the function actually reaches, rather than allocating bookkeeping proportional to the array length. This decision does not define what a write through a computed local index establishes. Computed local indexing remains refused in this aggregate slice; computed indexing of module arrays remains enabled because D10 gives module state every element from the start. Whole-array local values and initializers remain refused as well; D20 admits the one direct storage-to-storage copy. **Why:** treating one element write as assignment of the whole local would permit an uninitialized read from every other element. Requiring every element to be written before any one can be read would make large arrays unusable and would contradict [1910]'s local, path-sensitive question. Sparse facts preserve both the element boundary and D18's target-sized array lengths. **The alternative:** one fact for the whole array, or a dense bit for every position. The first loses the safety check at the first partial write; the second makes compiler memory consumption depend on a target object that may be far larger than the host can enumerate. Both were declined. **Pinned by** `negative/local-array-element-not-assigned`, `negative/local-array-element-not-assigned-on-every-path`, `negative/increment-unassigned-local-array-element`, and `runtime/local-array-elements-are-independent` on Linux x86-64. ### D20 — A whole-array copy reads and assigns every element **The tour said** that an array is a value and assignment copies it [0520], that two arrays are one type when their length and element type agree (D17), and that a local declared without a value is assigned before it is read [1910]. It did not say how a whole copy interacts with the independent sparse element facts D19 later introduced. **Chosen:** `destination = source`, where both sides name fixed-array storage, reads every element of the source and assigns every element of the destination. The two array types must have the same D17 identity. A source local is wholly assigned when an earlier whole copy assigned it or when its sparse D19 facts cover its length; a zero-length source is therefore assigned vacuously. Module state is wholly assigned by D10. Self-copy follows the same rule, so it cannot turn unassigned storage into an assigned value. A direct storage name resolves to a module or local binding. The name of a type declaration, even one whose declared type is the required fixed array, owns no runtime storage and is refused by the existing whole-value L0304 rather than being lowered as a copy source. A branch merge intersects what the facts _mean_, not merely how they happen to be represented. Whole on both paths remains whole; whole on one path and sparse facts on the other keeps those sparse facts; sparse on both keeps their intersection. Completeness is decided by counting the sparse facts already present, never by walking an array extent that D18 permits to fill the target. This kernel admits an array name as a whole value only in this copy context; D50 later lets either endpoint be a directly selected fixed-array field. D21 reuses only the direct-name storage read for initializers; D51 later admits a directly selected fixed-array field as the source of a local initializer only. Parameters, returns, discards, and other general value positions remain refused until their own aggregate or function slices. No array literal is enabled by this decision; D23 later admits one contextual initializer. **Why:** expanding a copy into one operation per element would make compiler work and IR size proportional to a target object that the host may not be able to enumerate. Treating a copy as one compact storage operation preserves [0520]'s value semantics while the sparse whole fact preserves [1910] without pretending that a partial local was initialized. **The alternative:** enumerate every copied element in definite-assignment state and IR, or let any one element write establish the whole. The first is not representable for every D18 array and the second permits reads of bytes the program never assigned. Both were declined. **Pinned by** `positive/local-array-copy`, `negative/local-array-copy-from-unassigned`, `negative/local-array-copy-not-assigned-on-every-path`, `negative/array-type-name-is-not-storage`, and `runtime/whole-arrays-copy-between-storage` on Linux x86-64. ### D21 — An array is initialized from a whole-array storage name **The tour said** that a binding may name its type and give it a value in one form [0040], that an inferred form takes the value's type [0050], and that a local declared without a value is assigned before it is read [1910]. It said nothing about what value an array binding could receive at its declaration. **Chosen:** a local or module array binding is initialized from a direct storage name in either its explicitly typed form — `[mut] name: [N]T = source` — or its inferred form — `[mut] name := source`. For a local, both copy every element exactly as D20's assignment does between two storage places. `source` names a whole array: a module binding, a prior local wholly assigned by D19's sparse facts or by a D20 copy, or a prior local likewise initialized from a name. The explicit form requires the source's D17 identity to agree with its written type; the inferred form gives the destination the source's exact D17 length and element type. The destination is wholly assigned by the copy alone, and both mutable and immutable binding forms accept it because a declaration is not an assignment [0080]. The source must be a storage binding rather than a type declaration. A type name that happens to declare the contextual array type is refused with L0304; it cannot supply an initial image or a local copy address. At module scope `source` is exactly one resolved module storage name. Its initial-image chain follows declaration identities, across forward references and type-alias chains, and must terminate either at a module array whose initializer is omitted or at a module array whose initializer is D24's explicit literal. A chain that returns to a declaration is [1940]'s value worked out from itself. Each destination on the chain nevertheless owns distinct storage initialized with the terminal image rather than aliasing its source. Nothing runs before the entry point [1460], so no module-level copy instruction exists. D70 later permits the same module image chain to pass through one directly selected fixed-array field. The selection remains a contextual initializer link rather than a general array value. D60/D61 later apply the same declaration-identity chain to explicitly typed and inferred module ordinary structs. Their presently enabled terminal images are all zero, so no finite aggregate image is needed yet. Every other array initializer value remains refused: D51 later admits a directly selected fixed-array field for a local binding and D70 its module counterpart, D23 admits one contextual local array literal [0520], D24 admits its module counterpart, while an inferred literal, `zeroed` [0540], repetition [0560], a slice [0570], a call, and every other indexed or selected subexpression are each their own later slice. This decision does not enable a general array value or an array as a parameter, return, discard, or struct field. A local source is read before the binding's scope begins [0110], so a local cannot initialize itself and an outer storage name may be shadowed. **Why:** D20 already lowered a local whole-array copy to one `Copy_Array` instruction, D18's storage semantics already reached every ordinary local, and D19's flow state already gave a fully-copied array the single whole-array fact it needs. At module scope, following declaration identities proves the initial bytes without inventing initialization code or collapsing two storage symbols into one. In both scopes the restriction to a direct source name keeps compiler work and IR size independent of the target-sized D18 extent and defers every value form whose own semantic rule is a later slice. **The alternative:** widen the initializer to any array-typed expression, or make the inferred spelling synthesize a general array value. Either admits constructs this decision does not recognise — D23's local array literal, `zeroed`, a slice, a call result, a selection or an index result — and each is its own decision. Reading D17's shape directly from named storage instead keeps the same narrow source rule as the explicit form without synthesizing an array `Name_Reference` anywhere else. **Pinned by** `positive/local-array-initialized-from-source-name`, `positive/module-array-initialized-from-source-name`, `negative/local-array-initializer-from-unassigned`, `negative/array-initializer-length-mismatch`, `negative/array-initializer-element-mismatch`, `negative/module-array-initializer-shape-mismatch`, `negative/module-array-initializer-non-name-refused`, `negative/module-array-initial-image-cycle`, `negative/array-type-name-is-not-storage`, `runtime/local-array-initializer-copies-storage`, and `runtime/module-array-initializers-copy-images` on Linux x86-64. ### D22 — Computed local array indexes use the whole-array fact **The tour said** that indexing an array checks the bound at runtime [1950], that an index is `usize` [0160], that a local declared without a value is assigned before it is read [1910], that an array is a value and assignment copies it [0520], and that its elements are indexed from zero [0520]. D19 introduced one definite-assignment fact per compiler-known element and D20 introduced the whole-array fact a copy assigns, and neither answered what a computed local read must require or a computed local write must establish. **Chosen:** a computed local array index is admitted where a compiler-known one is. Reading `local[i]` for a runtime `usize` requires the whole-array fact to hold on every arriving path — the same fact D20's copy and D21's initializer record, and the fact D19's element facts add up to once every declared position has been assigned. Writing `local[i] = v` for a runtime `usize` establishes no element fact of its own, and does not clear an existing whole-array fact: a copy followed by a computed write followed by a computed read is legal, and a computed write into an uninitialized local followed by a whole-array read is still refused. `inc local[i]` requires the whole-array fact because it reads and writes. Module arrays are unchanged: D10 gives their state every element from declaration, so their computed reads meet no assignment requirement and their computed writes still assign nothing tracked. Every other refused value form — an inferred initializer not sourced by a direct storage name, a slice, `zeroed`, repetition, an array literal outside D23's one context, `lenof`, a general whole value of D46/D47's array-field struct outside D54's contextual copy and D55/D56's local initializers, or its array field as a whole value or place — stays refused. D48 separately admits one element selected through that field. **Why:** treating one computed write as a whole assignment would admit uninitialized reads from every other position, exactly the failure D19 declined to introduce for known indexes. Requiring the whole-array fact before any computed read is the minimum rule that keeps [1910] path- sensitive without inventing element-range tracking the compiler would then have to compute for expressions no target can enumerate. Preserving an existing whole fact through a computed write is what makes D20 and D21 usable: without it, a copy followed by any computed update would need to be re-established a position at a time, and no sparse column of D19's fits an extent D18 permits. **The alternative:** admit a computed read without a prior whole assignment (and leave every out-of-order write undiagnosed until run time), or have a computed write clear the whole-array fact. Both were declined for the same reason D19 refused to widen one element write to the whole local: they trade a compile-time refusal for a runtime that this compiler has no way to observe. **Pinned by** `positive/local-array-computed-element-after-whole-copy`, `negative/local-array-computed-read-not-whole-assigned`, `negative/local-array-computed-write-establishes-no-fact`, `runtime/local-array-computed-index-reads-and-writes`, `runtime/local-array-computed-index-traps`, and `runtime/local-array-computed-store-traps` on Linux x86-64. ### D23 — A written local array type gives a literal its shape **The tour said** that an array is a value whose size is part of its type [0520], that a binding may write its type and value together [0040], that an integer literal takes the type of its context [0190], and that expressions are evaluated left to right [0410]. It did not say which of those supplies the shape and element context while array values are being introduced a slice at a time. **Chosen:** a nonempty array literal initializes an explicitly typed local fixed-array binding: `[mut] name: [N]T = [first, ...]`. The literal contains exactly `N` elements, and the scalar `T` is the context for every element expression. Each element is evaluated and stored in source order. The fresh local is thereby initialized as a whole, so a later computed index meets D22's whole-array requirement without a preceding copy. This is one contextual initializer and not a general array value. D24 later admits the explicitly typed module form, D25 the inferred local form and D29 assignment to an existing array. A parameter, return, argument or discard still refuses the literal. An empty literal, repetition [0560], `zeroed` [0540], slices [0570], nested array values and non-scalar elements remain outside this slice. In particular, this literal rule still requires one expression; D136 later accepts the zero-length type `[0]T` without adding empty literal syntax. **Why the written type:** it gives both facts the checker needs without an array-value inference rule: D17's exact length and the scalar context [0190] applies to each expression. The literal's finite source run is also the one array extent it is sound for the compiler to enumerate. Lowering allocates the same compact frame slot as any local array and stores each source element into its position; it does not introduce an array-valued IR result or work proportional to a target extent that was not written in the literal. **The alternative:** first infer the literal's length and element type, then allow that value in every compatible position. That is [0530] plus general array values rather than [0520]'s smallest executable case. It was deferred to D25 so module initial images, copying temporaries, parameters and returns did not become unstated consequences of accepting one local initializer. **Pinned by** `positive/local-array-literal-initializer`, `negative/local-array-literal-length-mismatch`, `negative/local-array-literal-element-mismatch`, and `runtime/local-array-literal-initializes-elements` on Linux x86-64. ### D24 — A written module array type gives a literal its static image **The tour said** that an array is a value whose size is part of its type [0520], that a binding may name its type and give it a value in one form [0040], that an integer literal takes the type of its context [0190], that expressions are evaluated left to right [0410], that a module value is known when the compiler reads it [1940], and that nothing runs before the entry point [1460]. It did not say what shape the compiler admits as a module array's static initial image. **Chosen:** a nonempty array literal initializes an explicitly typed module fixed-array binding: `[mut] name: [N]T = [first, ...]`. The literal contains exactly `N` elements, and the scalar `T` is the context for every element expression. Each element is evaluated in source order and its folded value becomes that array position's byte image at compile time. Every element must be `[1940]`-known and its fold must fit `T` — a literal or a bool spelling, an operator of [1820] [1940] enumerates over those, or a name bound to another module scalar binding whose own value is known. A forward reference is admitted for the same reason [1740] admits one for a scalar module value: a module is a set and the order between declarations is decided by identity rather than by their placement in the source. D21's direct-name form remains admitted at module scope as well. Following declaration identity through a chain of `[mut] name := source` or `[mut] name: [N]T = source` bindings now terminates either at D10's omitted-initializer array (whose image is zero) or at a D24 literal (whose image is that literal's fold). Every destination on the chain still owns distinct storage, and each is initialized with the terminal image byte for byte — a chain does not alias its source. This is D24's sole new module array initializer form. D26 later admits `[mut] name := [first, ...]` after D25 settles [0530]'s inferred shape. An empty literal, `zeroed` [0540], repetition [0560], slices [0570], nested array values, non-scalar elements, calls, selections and index results all remain outside these slices. Requiring one expression in the literal grammar still excludes an empty literal; D136 later accepts the zero-length type `[0]T` independently. The [1820] operators [1940] admits over literals are folded during checking and again when lowering records the verified image: [0290]'s arithmetic, [0300]'s wrapping forms at the operand type's own width so `u8 = 255 +% 1` is zero and every unsigned or signed size wraps the same way, [0320]'s shifts, [0330]'s bitwise set, [0340]'s logical words with short-circuiting, [0350]'s comparisons and [0370]'s measurements. Both walks take their widths from Landin.Types.Width against the compilation's target facts; the backend separately folds verified numeric scalar IR, while D177 records a bool datum directly from this same static-image walk so logical CFG cannot reach datum emission. Thus a shift past the width gives zero at exactly the width [0320] promises and a bitwise `not` occupies the same bytes the backend emits. The positive operator corpus and the negative fold agreement fixtures pin that checking settles every value or invalid operand before lowering is allowed to record an image. A member selection [0420], an array element index [0570] and a nested array literal are refused as D24-excluded constructs; [1940] admits an operator of [1820] applied to leaves, and these three would need the source aggregate or array to have its own image resolved before this one — a stage each has to arrive with its own slice. The refusal walks each element's whole subtree, so `source[0] + 1` and `state.x == 3` are refused for the same reason a bare `source[0]` or a bare `state.x` is: the operator at the root is admitted but the leaf it stands on is not. The same [1940] boundary applies to a scalar module initializer: selecting `state.x` or `source[0]` needs a static aggregate or array image that the corresponding later slice has not yet supplied, so checking refuses it rather than leaving the backend to meet an unreadable value. A fold whose result walks past the compiler's widest kernel value is also refused with the same [1940] rule: an `18446744073709551615 + 1` and a `4294967296 * 4294967296` have no moment in which to trap and no folded value the compiler can hold, so each is refused at the element that produced the overflow rather than left to defect during image resolution. The same refusal applies to a scalar module binding whose value's fold overflows: `k: u64 = a + 1` where `a` is already `u64`'s maximum reports the overflow rather than silently deferring it to the backend and Constraint_Error at emit time. **Why the written type:** it gives the checker D17's exact length and one scalar context [0190] for every element, without introducing an array-value inference rule at module scope. The written literal is the one array extent it is sound to enumerate at compile time; every other D18 length reaches four billion positions and no reader will type them out. Requiring each element to be `[1940]`-known keeps [1460]'s "nothing runs before the entry point" as the rule that decides what a module value is, and the finite element run makes the module fold a per-position walk that a target loader can consume by writing one directive per element into the object. **The alternative:** admit a call or a general expression, or infer the length from the literal before settling the local rule. The first two turn `[1460]` into a promise this compiler cannot keep; the third would have coupled [0530] to static-image folding rather than first giving local and module bindings D25's one shape. D26 admits inference only after that shared rule; the first two alternatives remain declined. **Pinned by** `positive/module-array-literal-initializer`, `positive/module-array-literal-forward-scalar-reference`, `positive/module-array-literal-1820-operators`, `negative/module-array-literal-length-mismatch`, `negative/module-array-literal-element-mismatch`, `negative/module-array-literal-element-not-known`, `negative/module-array-literal-element-out-of-range`, `negative/module-array-literal-index-element`, `negative/module-array-literal-selection-element`, `negative/module-array-literal-nested-index`, `negative/module-array-literal-nested-selection`, `negative/module-array-literal-fold-overflow`, `negative/module-scalar-fold-overflow`, `negative/module-array-fold-agreement`, `negative/module-scalar-fold-agreement`, `negative/module-scalar-storage-selection`, `positive/module-scalar-wrapping-arithmetic`, `positive/module-array-literal-wrapping-arithmetic`, and `runtime/module-array-literal-holds-its-image` on Linux x86-64. ### D25 — A nonempty local literal infers one fixed-array shape **Partly superseded.** Its inferred shape stands: the first element gives the element type, an untyped integer defaulting to `i32`, every later element must have that type, and the extent must fit `usize`. That element type is any shape, not only a scalar (D241). Its sentence "repetition keeps [0560]'s scalar element and the module form keeps D26's" is superseded by D1664 and D1947, and the positions its second paragraph leaves "outside this slice" by D241; what follows is history. **The tour said** that a binding written with `:=` takes the type of its value [0050], that an integer literal takes the type of its context [0190] and uses the default integer when there is none [0200], that an array's size is part of its type [0520], and that the length may be inferred from a literal [0530]. It did not say which element supplies the scalar type or which value positions that inference enables. **Chosen:** a nonempty array literal directly initializing an inferred local binding has fixed-array type `[N]T`, where `N` is the number of source elements and `T` is the scalar type synthesized by the first element. When that first expression is an untyped integer, [0200]'s `i32` is its context and therefore `T`; every later element is checked in that same `T` context. D18's complete `N * sizeof T` extent must fit the target's `usize` before the shape is recorded. D23's existing lowering evaluates and stores the finite source run left to right, and the resulting local is wholly assigned. D241 later admits every non-scalar element in a local inferred literal; repetition keeps [0560]'s scalar element and the module form keeps D26's. D25 admits only the initializer in a local inferred binding. Its module counterpart remained refused until D26 connected the inferred shape to D24's separate [1940] static-image fold. A literal in general assignment, a parameter or return, an empty literal, a nested literal, repetition [0560] and every non-scalar element also remain outside this slice. In particular, inference does not create a general array-valued temporary. **Why the first element:** [0530]'s literal has no surrounding element type, while [0050] requires the value to answer with one type. Letting the first source expression answer and checking the rest against it gives [0410]'s source order a single deterministic context, applies [0200] without an invented numeric join, and needs no conversions [0310]. **The alternative:** search all elements for a common type, defer every integer until a later element supplies one, or infer module static images at the same time. A common-type search would introduce conversion or least-upper-bound rules the language has neither stated nor wanted; deferral would make element order affect when errors appear without changing their source order; module inference would merge [0530] with [1940]'s independently constrained image fold. All three were declined. **Pinned by** `positive/local-array-literal-inferred-length`, `negative/local-array-literal-inferred-element-mismatch`, and `runtime/local-array-literal-infers-and-initializes` on Linux x86-64. ### D26 — An inferred module literal has the same static image boundary **Partly superseded.** Its static-image rule stands: an inferred module literal takes D25's shape, and its elements form one [1940]-known source-order image, each binding of a name chain holding storage of its own. Its scalar element is lifted by D1947: the first element gives the element type whatever its shape, and [1940] still decides which elements form an image. The forms its third paragraph "does not admit" are superseded by D241; what follows is history. **The tour said** that `:=` takes the type of its value [0050], that the length may be inferred from an array literal [0530], and that every module value is known when the compiler reads it [1940]. D24 supplied static images only after a written array type, and D25 first settled how a nonempty literal infers one shape. **Chosen:** a nonempty array literal directly initializing an inferred module binding has D25's `[N]T` shape: its source count is `N`, its first element supplies scalar `T`, an otherwise untyped integer first element defaults to `i32` [0200], and every later element is checked in that same context. Once the shape is settled, every element must meet D24's module-image boundary: it is [1940]-known, target-aware folding produces a value held by `T`, and the values form one source-order static image. D21's direct-name chain may copy that image into typed or inferred module array storage, with a distinct datum for every binding. All D24 exclusions remain exclusions: no call, member selection, element index or nested array can supply an image element, and checked overflow or an out-of-range folded value is refused before lowering. D18 limits the inferred complete byte extent before the shape is recorded. A local inferred literal continues to use D25's runtime evaluation instead; only module scope folds an image. This does not admit a literal in general assignment, as a parameter or return, or as a general array-valued expression. It also does not admit an empty literal, repetition [0560], `zeroed` [0540], slices [0570], or a non-scalar element. No general array temporary is introduced. **Why reuse D25's shape before D24's fold:** inference answers only which fixed array the binding holds; [1940] independently answers whether module storage can have that value before anything runs [1460]. Keeping those checks sequential makes local and module `:=` mean the same type while preserving the module-only static-image restriction. **The alternative:** infer a different element type from the complete folded image, or make module inference choose a written-width type from each value. Either would make the same literal have a different type at local and module scope and would invent a numeric join or narrowing conversion [0310]. Both were declined. **Pinned by** `positive/module-array-literal-inferred-length`, `negative/module-array-literal-inferred-boundaries`, `negative/module-array-literal-inferred-fold`, and `runtime/module-array-literal-infers-static-image` on Linux x86-64. ### D27 — An explicitly typed module array may spell its zero image **Superseded by D241.** `zeroed` takes its type from every destination [1880] lists, a typed module array among them, and a module array given `zeroed` keeps D10's absent image in `.bss`; what follows is history. **The tour said** that `zeroed` denotes all-bits-zero when that image is valid for its context [0540], that a fixed array is zeroable exactly when its element is [0520], and that every module value is known when the compiler reads it [1940]. D10 already gives an omitted module initializer that image, but did not say where a program may request it explicitly while array values are enabled a slice at a time. **Chosen:** `zeroed` directly initializes an explicitly typed module fixed-array binding: `[mut] name: [N]T = zeroed`. The written D17 shape is its context. Every scalar element type the kernel currently admits has an all-bits-zero image, so the complete array has one without enumerating its `N` positions. Lowering records no finite datum image, exactly as for D10's omitted initializer; the backend therefore reserves the distinct module storage in `.bss`. A D21 direct name chain may copy this terminal zero image while retaining one storage object per declaration. This is a contextual initializer, not an array-valued expression or a runtime operation. D27 itself does not infer a type for `name := zeroed`; D28 separately admits a typed local array initializer, D30 an array assignment, D39 a typed module scalar initializer and D40 a typed local scalar initializer. Every inferred form remains refused. D27 introduces no IR opcode, temporary, startup copy, or source-order element evaluation. Repetition [0560], slices [0570], empty literals, non-scalar array elements, parameters, returns, arguments, and general whole-array value positions remain outside this slice. **Why preserve the absent image:** materializing `N` zero values would make host work and IR size depend on D18's target-sized extent and would emit bytes for a value the object format can reserve without storing. The absence already means exactly this image for D10, keeps zero storage in `.bss`, and remains distinct from D24/D26's finite literal image. **The alternative:** treat `zeroed` as a generally typed value, or infer an array shape from it. The first would silently admit local initialization, assignment, parameters, and other value positions that need their own runtime rules; the second has no source fact from which to derive either `N` or `T`. Both were declined. **Pinned by** `positive/module-array-zeroed-initializer`, `negative/inferred-zeroed-not-enabled`, and `runtime/module-array-zeroed-reads-zero` on Linux x86-64. ### D28 — A local zero image is one runtime storage operation **Superseded by D241.** `zeroed` takes its type from every destination [1880] lists, a typed local array among them, and the one-operation clear this decision first required is now stated by D32; what follows is history. **The tour said** that `zeroed` denotes all-bits-zero when that image is valid for its context [0540], that a fixed array is zeroable exactly when its element is [0520], and that a local binding may carry an initializer [1810]. D27 supplied one static module context but deliberately introduced no runtime operation, so it did not say how a local array obtains the same image. **Chosen:** `zeroed` directly initializes an explicitly typed local fixed-array binding: `[mut] name: [N]T = zeroed`. The written D17 shape is its context. Every scalar element the kernel currently admits has an all-bits-zero image, so one runtime storage operation clears the complete compact frame slot. The operation carries the destination identity, never one entry per element; its byte extent is derived from the target's width for `T`. The initialized local is assigned as a whole, so D22 permits a later compiler-known or computed index read. Lowering records one target-neutral `Clear_Array` instruction with no operands and no result. D57 later gives field zero of that destination-only operation a whole aggregate's padded extent as well; its array meaning is unchanged. The Linux x86-64 backend forms the slot address and takes the target byte extent. It emits bounded scalar zero stores for one to six bytes or exactly eight bytes; other extents retain the forward `rep stosb` clear. Compiler work and IR size therefore remain independent of the target-sized length D18 admits, and no array-valued temporary or hidden zero datum exists. This remains one contextual initializer. D28 does not infer a shape for `name := zeroed`; D30 separately admits array assignment, D39/D40 typed module and local scalar initializers, and D41 scalar assignment. `zeroed` as an argument, return, discard, nested or general expression remains refused. Module arrays continue to use D27's absent static image rather than this runtime instruction. Repetition [0560], slices [0570], empty literals, non-scalar array elements, parameters, and returns remain outside this slice. **Why one storage operation:** lowering one store per element would make compiler work and IR size proportional to an extent deliberately permitted to approach the target address space. Copying a synthesized zero array would instead invent storage and a source the program never declared. A destination-only clear says exactly what [0540] requires and leaves representation to the target backend. **The alternative:** treat `zeroed` as a scalar expression repeated `N` times, or enable it in assignment at the same time. The first imposes host enumeration and invents source-order evaluation where there is none; the second broadens the place/value boundary beyond fresh initialization and needs its own definite- assignment and evaluation decision. Both were declined. **Pinned by** `positive/local-array-zeroed-initializer`, `negative/inferred-zeroed-not-enabled`, and `runtime/local-array-zeroed-reads-zero` on Linux x86-64. ### D29 — Array literal assignment forms the value in its destination **Partly superseded.** The contextual literal assignment and its definite-assignment rule stand: the destination gives the literal its length and element type, every read is checked against the state arriving at the statement, and the array is assigned as a whole when the statement completes. Its write order is superseded by D1827: an element no longer sees an earlier write of the same statement, and a failure leaves the array unchanged. Its limit to "direct local or module storage names" and the positions where literals "remain refused" are superseded by D241; what follows is history. **The tour said** that assignment copies an array [0520], that an assignment evaluates its destination place before its value [0410], and that aggregate parts initialize in written order. D20 admitted only a direct storage name as the value, while D23 admitted a literal only for a fresh local binding. Neither said whether assignment of a literal needs a hidden complete value or exposes its element order in existing storage. **Chosen:** a nonempty array literal may be assigned contextually to a mutable fixed-array place: `place = [first, ..., last]`. The destination's D17 length and scalar element type are the context; the literal must contain exactly that many elements and each expression must have that element type. At this boundary the fixed-array places are direct local or module storage names. D52 later admits a directly selected fixed-array field under the same literal rule. [1900] still decides whether either may be written. The destination place is reached first. Then each literal element is evaluated left to right and written immediately to its one-based destination position before the next expression begins. A later expression can observe an earlier write to the same array, and a runtime failure can leave the completed prefix changed. Lowering emits the existing scalar expression and field-store sequence for each source element; it creates no hidden array-sized temporary and no new array IR operation. The compiler work and instruction run are proportional to the literal text the program wrote, not to an implicit target-sized extent. Definite assignment checks every right-hand-side read against the state arriving at the statement, then marks the destination array assigned as a whole only when the assignment completes normally. Thus assigning a complete literal makes a previously uninitialized array readable through a compiler-known or computed index, but an element written earlier in the same statement does not justify a source read that was unassigned on entry. This is one assignment context, not a general array value. Array literals remain refused as arguments, returns, discards, scalar operands, nested elements, and other expression positions. Empty literals, repetition [0560], slices [0570], non-scalar element arrays, and `zeroed` assignment remain separate slices. A direct storage-name assignment continues to use D20's one compact `Copy_Array`. **Why expose the writes:** evaluating every element before changing the destination would require a hidden second array as large as the value, obscuring a cost the language promises to keep visible. Writing each completed scalar uses only storage the program named and gives [0410]'s aggregate order an observable, deterministic meaning. Source text already contains one expression per store, so this does not introduce D18's host-enumeration problem. **The alternative:** synthesize a temporary array and copy it only after every element succeeds. That gives transactional-looking assignment and prevents later elements from observing earlier writes, at the price of an implicit full array in every frame and a second full traversal. It was declined. **Pinned by** `positive/array-literal-assignment`, `positive/module-array-literal-assignment-runtime-elements`, `negative/array-literal-assignment-length-mismatch`, `negative/array-literal-assignment-element-mismatch`, `negative/array-literal-assignment-reads-incoming-state`, and `runtime/array-literal-assignment-reads-old-value` on Linux x86-64. ### D1827 — An assigned aggregate is formed as if before its destination changes **The tour said** at [0410] that an assignment evaluates its destination before its value, at [0520] that assigning a literal to an existing array fills it in place in written order, so that a later element sees an earlier write, and at [0590] that whole-array arithmetic copies by value. D29 and the decisions that extended it (D37, D52, D53, D64, D65) wrote each element or field as it was evaluated, while D209 retained every array operand before the first write. `row = [row[1], row[0]]` therefore did not swap, and `row = -row` and `row = [row[1], row[0]] + zero` did different things to one array. **Chosen:** one rule for every aggregate value assigned to a place. The destination is reached first, as [0410] says. The value is then evaluated in its own written order, labels and elements left to right and a fill after them, and every read in it sees the destination as it was before the assignment. The destination changes only when the value is complete: a failure that leaves the value, an `else` that breaks out of a loop, a `return` or a propagated error, leaves the destination as it was. A trap does not return, and what a panic handler finds in the destination is not specified. The rule holds for a written array literal, a mixed repetition and a struct construction assigned to an existing place, whatever selects the place. `[n of v]` evaluates its one expression before it writes, a name is copied, a call or control value is formed in its own storage, and D209 retains its operands, so each of them already meets it. A binding's initializer writes storage that no expression can yet read. **How it costs nothing where nothing overlaps:** lowering still writes each element into the destination as it is evaluated when nothing shows that the value can observe the destination; otherwise it builds the value in a temporary of the destination's shape and copies it once. Overlap is shown by a name of the destination's root in the value, except inside an `addr` that selects without an index or a pointer; by a match or destructuring alias that may hold the destination's storage; by an exit or `try` inside the value; and, by how the destination is reached, by further reads. A local binding or a named return whose address its routine never takes is reached only by its name: a frame address cannot be kept in storage that outlives the frame ([0770]), a named result is its own slot until an exit commits it (D116), and a parameter taken by value is the callee's own copy (D95). Module storage, and a local or named return whose address is taken, are reached as well by a call and by a read through a pointer, a slice or an inout parameter. Any other destination, one reached through a pointer or an inout parameter among them, may also be any other module binding, or any local or named return whose address is taken, of aggregate or array type. A construction or a conversion to a type is not a call. The temporary is visible in the frame and its copy is one compact operation, as D209's snapshots are. **The alternatives:** D29's immediate writes, which make a literal that reads its destination mean something no reader expects and differ from D209's operators; a temporary for every assigned aggregate, which costs a frame-sized copy where nothing can overlap; and refusing a literal that reads its destination, which refuses the swap the rule exists for and still needs an answer for reads through pointers. All were declined. The maintainer took SC-26 as its own change on 2026-11-21 (D1653). **Pinned by** `runtime/array-literal-assignment-reads-old-value`, `runtime/mixed-array-repetition-assignment-reads-old-value`, `runtime/struct-array-field-literal-assignment-order`, `runtime/struct-array-field-repetition-assignment-order`, `runtime/struct-literal-order-and-fill`, `runtime/struct-construction-order`, `runtime/struct-literal-array-field-order`, `runtime/r490-generic-field-fill`, the lowering case `self-reading literals form apart`, and `runtime/aggregate-assignment-reads-old-value-through-aliases`, whose program swaps through a pointer, an inout parameter aliasing a module binding, a by-value argument that is also the inout destination, and a struct, and leaves a loop from an element's `else`. ### D30 — Zeroed assignment clears one complete array place **Superseded by D241.** `zeroed` may be assigned to every place whose type has a zero image, and the one-operation clear this decision first required is now stated by D32; what follows is history. **The tour said** that `zeroed` is the all-bits-zero image supplied by a context [0540], that assignment evaluates its destination before its value [0410], and that array assignment copies a complete value [0520]. D27 and D28 admitted that image only while creating module and local storage. They deliberately left an existing destination to a later definite-assignment and runtime decision. **Chosen:** `zeroed` may be assigned contextually to a mutable fixed-array place: `place = zeroed`. The destination's D17 length and scalar element type supply the context, and [1900] decides whether its direct local or module storage name may be written. Every scalar element the kernel currently admits has an all-bits-zero image, so the complete array has one [0540]. D49 extends this contextual assignment to one fixed-array field selected immediately from enabled struct storage without making the field a general array place or value. The destination is reached first; `zeroed` evaluates no source expressions and names no source storage. Lowering emits one `Clear_Array` carrying that local frame slot or module datum; D49 additionally carries the declaration-order field identity, never a target byte offset. The verifier resolves its complete array shape, and the backend derives the byte extent from target facts. Linux x86-64 uses bounded scalar zero stores for one to six bytes or exactly eight bytes; other extents retain `rep stosb`. There is no hidden zero datum, array temporary, source operand, or compiler enumeration of D18's target-sized length. A normally completed assignment marks a local destination assigned as a whole, so every compiler-known and computed element may then be read. There is no source-order prefix like D29's literal has: the source contains no elements and specifies no per-element evaluation. This does not promise an atomic machine operation; D227 defines concurrency and interruption limits. This is one contextual array assignment. It does not infer a type for `name := zeroed` or assign a scalar; D39 separately admits a typed module scalar initializer, while local scalar initialization remains refused. Nor does D30 admit `zeroed` as an argument, return, discard, nested value, or general expression. Module and local array initializers keep D27/D28's distinct static and runtime paths. Repetition [0560], slices [0570], non-scalar array elements, and other zero-accepting types remain separate slices. **Why reuse the clear:** lowering one scalar zero store per element would make compiler work and IR size depend on an extent whose source writes no finite run. Copying a synthesized zero array would invent both storage and a read. D28's compact destination-only operation already says the complete runtime effect and already follows target width for either storage kind. **The alternative:** make `zeroed` a general array value and feed it through D20's copy. That would silently admit arguments, returns and other value positions while requiring source storage for an image that has none. It was declined. **Pinned by** `positive/array-zeroed-assignment` and `runtime/array-zeroed-assignment-clears-storage` on Linux x86-64, together with the focused lowering and target-width backend cases for both storage kinds. ### D31 — `lenof` counts a literal without forming it **Scalar element lifted by D1664.** A measured literal is still checked, not formed, and nothing in it is evaluated, but its first element gives the element type whatever its shape, as an inferred literal's does; the sentences below that require a scalar element are superseded. **The tour said** that a literal's `lenof` is compile-time [0370]. D14 first implemented only a direct name, because a general expression operand would have made array values, calls, selections and slices one undivided decision. D25 later settled how a nonempty literal supplies a scalar element shape. **Chosen:** `lenof ([first, ...])` is a `usize` whose value is the number of expressions in the literal's source run. The literal must remain nonempty under [0520]. Its first element supplies D25's scalar type, including [0200]'s default for an otherwise untyped integer, and every later element must have that same type. This checks that the syntax denotes one array shape; it does not create an array value. None of the element expressions is evaluated, read, folded, lowered or stored. The count therefore remains valid when an element is an unassigned local, a call, a selection or any other well-typed scalar expression. At module scope those expressions do not become module initializer inputs: the complete measurement is known from syntax alone. Definite assignment likewise reads no names beneath the measurement. Lowering emits one existing `usize` Number holding the source element count. A static module binding records the same number directly. No array storage, temporary, element instruction, target query or backend operation is introduced. D18's maximum object extent does not apply because no object of the literal's shape exists. This admits only a parenthesized nonempty array literal beside D14's direct identifier. The parentheses are part of the measurement syntax, not a general expression operand: without them, `lenof[index]` continues to index an ordinary binding named `lenof`, as [1760]'s contextual spelling requires. The direct identifier form also measures a slice's runtime length [0370]; selections, indexes, calls and other general expression operands remain outside [1820]'s measurement grammar. Empty literal syntax remains deferred. D136 later accepts `[0]T` source legality independently of that syntax. **Why type-check expressions that do not run:** the brackets still claim one array literal, and D25 already gives that claim a deterministic scalar shape. Counting arbitrary comma-separated expressions regardless of their types would make malformed aggregate syntax valid only when placed beneath `lenof`. **The alternative:** evaluate the literal and then ask the resulting array value for its length. That would make calls and reads observable despite the count being fixed by syntax, require hidden array storage, and prematurely admit a general array value. It was declined. D333 supersedes this decision in part: `lenof` now takes a path, a slice and a call's result as well as a name and a literal, a call is always evaluated, and only a name or a path over a fixed array is measured without being read. **Pinned by** `positive/lenof-array-literal-does-not-read-elements`, `negative/lenof-array-literal-element-mismatch`, `positive/lenof-array-literal-takes-any-element`, which D1664 turned from a refusal, and `runtime/lenof-array-literal-is-compile-time` on Linux x86-64; the runtime case also keeps an ordinary array named `lenof` indexable. ### D32 — Full-array repetition evaluates one scalar once **Partly superseded.** Two rules stand. A repeated value is evaluated exactly once, before the fill. A whole clear, fill or copy of an array is one operation, never one per element, whatever the array's extent: D28 and D30 stated this first, and since both are superseded this decision holds it. Its limit of repetition to "an explicitly typed local initializer or an existing mutable array place", its scalar element and the forms that "remain refused" are superseded by D241 and D1664; what follows is history. **The tour said** that repetition writes `[N of value]`, or `[of value]` when a context supplies the length [0560], that expressions run left to right [0410], and that assigning an array copies its complete value [0520]. It did not say whether `value` runs once or once per element, nor how a contextual repetition is represented without materializing a target-sized temporary. **Chosen:** an explicitly typed local fixed-array binding may be initialized by `[N of expression]`, and a mutable fixed-array place may be assigned either `[N of expression]` or `[of expression]`. The written local type or destination supplies D17's exact length and scalar element type. When `N` is written, it must equal that length exactly. The scalar expression must have the element type, including [0190]'s contextual commitment of an untyped integer. At this boundary an assignment destination is a direct local or module array storage name. D53 later admits a directly selected fixed-array field under the same full-repetition rule. The destination is reached first for assignment. The repeated scalar expression is then evaluated exactly once, and its target-width bit pattern is stored in every element. Normal completion initializes or assigns the destination as a whole for [1910], so a later computed index meets D22's whole-array requirement. The operation is not promised atomic with respect to interruption or concurrency. Lowering evaluates the scalar into one ordinary value and emits one `Fill_Array` carrying that operand and the destination's compact frame-slot or module-datum identity. The verifier requires one scalar operand matching the destination element type and rejects a fill in a static datum initializer. The Linux x86-64 backend derives the element count and width from the destination shape and target facts, then uses the width-matched forward repeated store. Neither IR nor compiler work enumerates D18's extent, and no hidden array storage or temporary is formed. This first repetition slice deliberately requires an explicitly typed local initializer or an existing mutable array place. D33/D35 later admit counted local and module inference, D34 the typed module static image, and D36--D38 the mixed-prefix forms. Argument, return, discard, nested repetition and general array values remain refused. Since `of` remains [1760]'s contextual spelling rather than a reserved word, `[of, other, of]` remains an ordinary literal whose elements may name a binding called `of`; repetition is recognized only where the token after `of` can begin its scalar expression. Thus `[of + 1]` also remains an ordinary one-element literal. **Why once:** the source writes one expression, and evaluating it once makes the runtime work visible without multiplying side effects by a type-level count. A scalar register or spill plus one compact fill is sufficient even when D18 permits an extent the compiler host cannot enumerate. **The alternative:** lower repetition as if the source had written one copy of the expression per element. That would make side effects and compiler work proportional to a target-sized count and contradict the single expression the program contains. It was declined. **Pinned by** `positive/local-array-repetition`, `negative/array-repetition-count-mismatch`, `negative/array-repetition-element-mismatch`, `negative/array-repetition-countless-inferred-initializer-not-enabled`, `negative/array-repetition-reads-incoming-state`, and `runtime/array-repetition-evaluates-once` on Linux x86-64. ### D33 — A counted local repetition supplies its inferred shape **Partly superseded.** Its inferred shape stands: the count gives the length and the repeated value the element type, an untyped integer defaulting to `i32`, and the extent must fit `usize`; a zero count stays refused. Its scalar element is lifted by D1664: the repeated value gives the element type whatever its shape. The forms its third paragraph leaves "outside this slice" are superseded by D241 and D1947, except D241's recorded boundaries; what follows is history. **The tour said** that a literal may supply an omitted array length [0530] and that repetition writes a count before `of` when no surrounding type supplies one [0560]. It did not say whether the same count can supply the complete type of an inferred binding, or which expression supplies the element type. **Chosen:** a counted full-array repetition directly initializing an inferred local binding supplies `[N]T`. `N` is the written nonzero integer count. The one repeated expression supplies `T` by D25's deterministic first-element rule: an untyped integer receives [0200]'s default `i32`, an already typed scalar retains that type, and no common-type search or conversion is introduced. The resulting byte extent must fit D18's target `usize` before the compact shape is recorded on the repetition and binding. The repeated expression is read from incoming definite-assignment state and uses D32's lowering unchanged: it evaluates exactly once into one scalar IR value, followed by one compact `Fill_Array` for the inferred local frame slot. Successful initialization establishes the whole array. Neither checker nor IR enumerates the inferred extent. A written zero count remains refused in this inference position because the repetition supplies no element-bearing source run. D136 later accepts an explicit zero-length fixed-array type; that does not make repetition an empty array literal or give an inferred zero-count repetition an element type. A count-less inferred initializer, module initializer, mixed-prefix repetition, argument, return, discard, nested repetition and other general array value remain outside this slice. **Why the scalar expression:** unlike a literal source run, repetition has only one value-producing expression. Taking its settled scalar type gives every stored element the same type without inventing a second inference rule. **The alternative:** require a written array type for every repetition. That would leave the explicit count unable to do the same shape work as [0530]'s literal count, despite already being checked against that shape by D32. It was declined. **Pinned by** `positive/local-array-repetition-inferred`, `negative/inferred-array-repetition-extent-overflow`, `negative/inferred-array-repetition-reads-incoming-state`, `negative/inferred-array-repetition-zero-count`, `negative/array-repetition-general-value-not-enabled`, and `runtime/array-repetition-evaluates-once` on Linux x86-64. ### D34 — A written nonzero array shape admits either repetition spelling **Partly superseded.** Its repeated encoding stands: a written nonzero shape takes either repetition spelling, a module repetition folds to one compact pattern, a zero pattern is the absent image in `.bss`, and a zero contextual length is refused. The initializers and positions its fifth paragraph says "remain refused" are superseded by D241, and its inferred module form is D33's shape with this image; what follows is history. **The tour said** that `[N of expression]` may omit `N` when the type supplies its length [0560], and introduced repetition as a static pattern that lives in flash. D32 admitted only a counted explicitly typed local initializer, while D33 admitted a counted inferred local; neither slice supplied the module static image or explained what a zero folded pattern becomes. **Chosen:** an explicitly typed fixed-array binding at module or local scope may be initialized by `[N of expression]` or `[of expression]` when its written contextual length is nonzero. The written type supplies D17's complete shape. A written `N` remains an exact assertion of that same length, and the one expression is checked against the scalar element type. This lifts D32's count requirement for an explicitly typed local without changing assignment or D33's inferred rule. For module state, the expression obeys the same [1940] compile-time-known and D24 target-aware scalar-fold boundary as one element of a module array literal: literals, [1820] operators and module scalar names may compose; calls, storage selection, an element index and a nested array literal remain refused. The fold produces one scalar pattern. A nonzero pattern is represented in IR by that one `Folded` value plus D17's existing compact shape, including through any D21 direct module-array name chain. A zero pattern records no image, just like D10, D27 and D28, and therefore remains loader-zeroed storage rather than bytes in `.data`. Neither image resolution, copying, verification nor dumping enumerates the extent. The Linux x86-64 backend emitted a constant-size `.rept`/width-specific-directive/ `.endr` sequence for a nonzero repeated image. The scalar directive is `.byte`, `.word`, `.long` or `.quad` according to the target element width. In particular, the eight-byte form does not use GNU `.fill`, whose value operand contributes at most four bytes and would discard the high half of a `u64` pattern. An absent zero image stays `.bss`. D536 later writes a pattern of four bytes or fewer as one `.fill` on every target and keeps the repetition for eight-byte patterns. A repetition whose written contextual length is zero is refused at the repetition. This is a construct-specific nonzero requirement. D136 later accepts `[0]T` as source, while repetition over that zero contextual extent remains refused. D33's zero-count inferred refusal remains for the same reason. An inferred module initializer remained outside this slice until D35. A count-less inferred initializer, every mixed-prefix context other than D36's typed local, argument, return, discard, nested repetition and every other general array value position remain refused. **Why one image value:** repetition writes one expression and every destination position receives the same target-width pattern. Materializing one value per position would lose the compact representation precisely for D18's target-sized extents, and copying such a run through a module name would repeat the same fault. **The alternative:** use GNU `.fill count,size,value` directly. Its compact count is attractive, but GNU assemblers truncate `value` to four bytes, so it cannot faithfully emit an arbitrary eight-byte element. The width-specific repeated scalar directive keeps both compact source and all pattern bits. **Pinned by** `positive/local-array-repetition`, `positive/module-array-repetition`, `negative/array-repetition-zero-context`, `negative/module-array-repetition-element-not-static`, `negative/module-array-repetition-index-element`, `negative/array-repetition-countless-inferred-initializer-not-enabled`, and `runtime/array-repetition-evaluates-once` on Linux x86-64. ### D35 — A counted module repetition may infer its nonzero array shape **Superseded by D33 and D34.** An inferred module repetition takes D33's inferred shape, with an element of any shape (D1947), and D34's compact image; what follows is history. **The tour said** that a counted repetition may supply an inferred local's length and scalar element type [0560]. D33 implemented that local form, while D34 supplied the compact static image only when module state wrote its array type. **Chosen:** `[N of expression]` may directly initialize an inferred module binding when `N` is written and nonzero. The count supplies D17's length and the one expression supplies its scalar element type; an untyped integer takes [0200]'s `i32` default. The resulting byte extent must fit the selected target's `usize` by D18, exactly as for D25/D26/D33 inferred arrays. The repeated expression obeys [1940]'s known/static boundary and the same D24 target-aware fold and range checks as D34's typed module repetition. Literal and [1820] operator trees may reach through module scalar names; a call, storage selection, index or nested array value is refused before lowering. The checker folds the one pattern against the inferred scalar type, so no accepted out-of-range or overflowing pattern can reach lowering as a compiler defect. D34's representation and emission apply unchanged: a nonzero pattern is one compact repeated image, direct module-array name chains preserve it, and a zero pattern is the absent loader-zeroed image emitted in `.bss`. Zero count, count-less inferred repetition and every general array value position remain refused. D36 later admits the explicitly typed local mixed form, D37 its assignment and D38 the explicitly typed module image. **Why only counted:** without a written type or source run, `[of expression]` has no source for its length. The scalar can determine an element type but not an array extent, so accepting it would require a separate inference rule rather than completing the symmetry D33 began. **The alternative:** infer only locals and require every module repetition to write its array type. That makes storage duration alter whether an explicit count and scalar can determine the same D17 shape, while D34's static image already represents the result. It was declined. **Pinned by** `positive/module-array-repetition-inferred`, `negative/inferred-module-array-repetition-element-not-static`, `negative/module-array-repetition-index-element`, `negative/inferred-module-array-repetition-extent-overflow`, `negative/module-array-repetition-fold-range`, `negative/inferred-array-repetition-zero-count`, `negative/array-repetition-countless-inferred-initializer-not-enabled`, `negative/array-repetition-general-value-not-enabled`, and `runtime/array-repetition-evaluates-once` on Linux x86-64. ### D36 — A typed local may mix a literal prefix with one repeated suffix **Partly superseded.** Its rule stands: a typed destination may take a literal prefix and one repeated suffix when the prefix leaves a nonempty suffix, the prefix is evaluated before the suffix, the repeated value once, and the suffix is one fill. The contexts its fifth paragraph says "This slice admits no" are superseded by D241, except D241's recorded boundaries; what follows is history. **The tour said** that repetition may follow values already written between the brackets [0560], that expressions run left to right [0410], and that a local binding may write its fixed-array type [0040]. It did not state which contexts first admit that mixed form, whether the repeated expression runs once, or how the compact fill identifies only the suffix. **Chosen:** `[e1, ..., ek, of repeated]` may initialize an explicitly typed local fixed array of length `N` exactly when `1 <= k < N`. The written type supplies D17's length and scalar element type. Each prefix expression and the repeated expression must have that scalar type, including [0190]'s contextual commitment of an untyped integer. A prefix that reaches or passes `N` is refused because no nonempty repeated suffix remains. Lowering evaluates each prefix expression and immediately stores it into parts `1` through `k`, in source order. It then evaluates `repeated` exactly once and emits one compact `Fill_Array` beginning at one-based part `k + 1`. No hidden array temporary or array-valued IR result is formed. `Fill_Array` carries its one-based `First` part; every pre-D36 full fill passes `First = 1`. The verifier requires `First` to lie within the destination length as well as retaining the existing destination-shape and scalar-operand checks. Linux x86-64 offsets the destination by `(First - 1) * element_size` bytes and repeats exactly `N - First + 1` width-matched stores. The parser still does not reserve `of`. It recognizes the suffix marker only after a nonempty comma-terminated prefix and only when the token after `of` can begin an expression. Thus `[of, other, of]` remains an ordinary three-element literal and `[of + 1]` remains an ordinary one-element literal whose expression may name a binding called `of`. This slice admits no mixed module initializer, inferred binding, argument, return, discard, nested array or other general array value. D37 separately admits assignment to an existing mutable fixed-array place, and D38 separately admits the explicitly typed module static-image form. Full-array repetition remains governed by D32--D35, so a prefix length of zero is not a mixed form and does not narrow those existing contexts. **Why local and explicit:** it is the smallest context that already owns a runtime destination and supplies both `N` and the scalar type. Admitting module state would require a mixed static-image representation; inference would need a new length rule; assignment would expand D29/D32's contextual value boundary. Each remains independently testable rather than becoming an unstated result of this slice. **The alternative:** materialize the prefix and repeated suffix as a complete array temporary, then copy it to the local. That would hide the observable prefix-store order, allocate storage proportional to D18's target-sized extent, and discard the compact fill representation. It was declined. **Pinned by** the parser, checker, IR, verifier, lowering and Linux x86-64 public-seam cases; `positive/local-array-mixed-repetition`; `negative/array-mixed-repetition-prefix-too-long`, `negative/inferred-array-mixed-repetition-not-enabled`, `negative/array-mixed-repetition-general-value-not-enabled`, `negative/nested-array-mixed-repetition-not-enabled`; and `runtime/mixed-array-repetition-is-source-ordered` on Linux x86-64. ### D37 — A mixed prefix may assign a mutable fixed array **Partly superseded.** D36's mixed form on assignment, its prefix bound and its definite-assignment rule stand. Its write order is superseded by D1827: the prefix and the repeated value read the array as it was before the assignment. Its limit to "a direct local or module array storage name" and the contexts that "remain refused" are superseded by D241; what follows is history. **The tour said** that assignment reaches its destination before evaluating its right-hand side [0410], that a mutable binding may be assigned [1900], and that mixed repetition evaluates and stores its prefix before evaluating one repeated suffix [0560]. It did not say whether an existing array place could supply the mixed form's context, whether partial stores changed definite-assignment state, or whether both module and local storage used the compact suffix operation. **Chosen:** `[e1, ..., ek, of repeated]` may be the right-hand side of assignment to a mutable fixed-array place of type `[N]T` exactly when `1 <= k < N`. The destination supplies the complete length and scalar element type. Every prefix expression and `repeated` must have type `T`, including [0190]'s contextual commitment of an untyped integer. The existing place check retains [1900]'s mutability requirement, and a prefix that reaches or passes `N` is refused because no repeated suffix remains. At this boundary the place is a direct local or module array storage name. D53 later admits a directly selected fixed-array field under the same mixed rule. The destination is reached and evaluated before any right-hand-side expression. Lowering then evaluates each prefix expression left to right and immediately stores it into destination parts `1` through `k`. It evaluates `repeated` exactly once and emits the existing compact `Fill_Array` with `First = k + 1`. The same IR operation names either a local frame slot or a module datum; no array-sized temporary, array-valued result, verifier rule or backend operation is added. Definite-assignment checks every prefix and repeated expression against the state incoming to the assignment. Stores made while evaluating the mixed form do not make an initially unassigned destination readable by a later expression in that same right-hand side. Only successful completion establishes the complete destination as assigned. Inferred initialization, nested mixed forms and other general-value contexts remain refused. D38 independently admits explicitly typed module initialization; this assignment rule creates no static mixed image and no independently carried mixed array value, and only forms the result directly in existing mutable storage. **Why assignment:** D29 and D32 already establish the destination-first, contextual assignment boundary for finite literals and full repetition. D36's ordered prefix stores and `Fill_Array.First`, plus their verifier and backend paths, express the mixed case without another representation. Extending only this boundary preserves the independently testable initializer and general-value refusals. **The alternative:** form a complete temporary and copy it after all expressions finish. That would reverse the observable immediate-store semantics, consume storage proportional to D18's target-sized extent, and make the compact suffix fill transient rather than the destination operation. It was declined. **Pinned by** the checker and lowering public-seam cases; `positive/array-mixed-repetition-assignment`; `negative/immutable-array-mixed-repetition-assignment`, `negative/array-mixed-repetition-assignment-element-mismatch`, `negative/array-mixed-repetition-assignment-prefix-too-long`, `negative/array-mixed-repetition-assignment-reads-incoming-state`, the retained initializer, inferred, nested and general-value refusal fixtures; and `runtime/mixed-array-repetition-assignment-reads-old-value` on Linux x86-64. ### D38 — A typed module mixed repetition has a compact hybrid image **Partly superseded.** Its hybrid encoding stands: a typed module mixed repetition is its finite folded prefix and one suffix pattern, never expanded, and stays a written `.data` image when its suffix is zero. The mixed forms it says "remain refused" are superseded by D241, except D241's recorded boundaries; what follows is history. **The tour said** that repetition is for static patterns in flash [0560], that a module value must be known when the compiler reads it [1940], and that a mixed prefix leaves one expression to fill its suffix. It did not say whether an explicitly typed module array could use that mixed form, how its static image was represented, whether a zero suffix selected `.data` or `.bss`, or whether a through-name copy preserved the representation. **Chosen:** `[e1, ..., ek, of repeated]` may initialize an explicitly typed module fixed array `[N]T` exactly when `1 <= k < N`. The written type supplies `N` and `T`; every prefix expression and `repeated` must have type `T`, and each must be compile-time known under [1940]. Every fold uses the selected target facts and must fit `T`, including each prefix independently and the one suffix value. Inferred module initialization, nested mixed repetition and every general-value mixed form remain refused. Lowering folds the finite prefix in source order and the repeated expression once. IR records a **hybrid image** consisting of those `k` folded prefix values, one folded suffix value, the element type and the declared length. It never records `N - k` copies. Image verification checks the finite prefix and one suffix value; the dump renders the same finite run followed by `repeat`; direct-name image resolution copies that compact representation through chains. None of lowering, IR, verification, dumping or copying walks or allocates in proportion to `N`. A hybrid remains a present image when its suffix value is zero, because its nonempty written prefix makes it explicit `.data`; Linux x86-64 emits the prefix with width-matched scalar directives and then a constant-size `.rept N - k` around one zero directive, which D536 writes as one `.zero`. A full repetition of zero retains D34's absent image and loader-zeroed `.bss`. For every nonzero suffix the backend uses the same `.byte`, `.word`, `.long` or `.quad` directive, so a 64-bit pattern reaches the assembler with all eight bytes rather than GNU `.fill`'s truncated value field. **Why a hybrid image:** a finite prefix plus one suffix pattern is the source's own information and is sufficient to emit every byte. Expanding the suffix would make compile time, host memory, verifier work, dump size and assembly size depend on D18's target-sized extent; treating a zero suffix as absent would discard the nonzero prefix and misclassify initialized data as `.bss`. **The alternative:** lower the initializer to a complete per-position static image. That would reuse D24's literal run but erase the compactness guaranteed by repetition and make a legal target-sized declaration an impractical host-sized compiler computation. It was declined. **Pinned by** the checker, IR, verifier, lowering and Linux x86-64 backend public-seam cases; `positive/module-array-mixed-repetition`; `negative/module-array-mixed-repetition-prefix-not-static`, `negative/module-array-mixed-repetition-suffix-not-static`, `negative/module-array-mixed-repetition-fold-range`; the retained inferred, nested and general-value refusal fixtures; and `runtime/module-mixed-array-repetition-holds-hybrid` on Linux x86-64. ### D536 — A static image's runs are written without expansion **The tour said** that repetition is a static pattern that lives in flash [0560], and D34, D38 and D132 kept every run compact through lowering, IR and the assembly text. It did not say what the assembler does with that text. GNU as and LLVM both expand `.rept` in memory, its body's text once per copy, and GNU as keeps what it expanded, so a compact `.rept 100000000` around a nested row asked a 76 MB object for gigabytes of assembler memory. **Chosen:** every native backend writes a run of one element through the one set of helpers in `Landin.Backend`, so the four, arm64 for Linux, FreeBSD and Darwin alike, agree on its form: - A run that writes only zero bytes is one `.zero`: a repeated zero scalar, a hybrid's zero suffix, and a repeated aggregate or array element whose whole image is zero, with its padding. - A run of a scalar of one, two or four bytes is one `.fill count, size, value`, which both assemblers hold as one fragment. - What is left, a run of a nonzero composite element, of an address, of an atom, or of an eight-byte scalar whose high half `.fill`'s four-byte value field would drop, is repeated. A count above 256 is written in base 256: for each nonzero digit, a `.rept` of that digit around as many nested `.rept 256` as its place, around the body. A count up to 256 is one `.rept` as before. - Inside a body that is itself repeated, a zero gap or a scalar run of at most 16 bytes is written as plain values, `.byte 0, 0, 0` for a record's padding, and only a longer one as `.zero` or `.fill`. A body is therefore written once per nonzero digit, at most eight times, and the text an assembler expands at once is the body's own times at most 256. Nested runs multiply their digits, which D537's budget bounds: within 4 GiB at most three dimensions of an image exceed 256. The object bytes are those the earlier `.rept` sequences assembled to. **Why one directive where one will do:** `.zero` and `.fill` are a fragment whose repetition the assembler writes out only into the object, so an image of hundreds of megabytes costs it a few megabytes. A repeated body is expanded, however it is nested, and is what D537 counts against the budget. **Why plain values inside a repeated body, up to 16 bytes:** each `.zero` or `.fill` opens a fragment of its own, about 140 bytes of GNU as's memory, and a repeated body opens one per copy. A record of a byte, three of padding and a `u32` then cost the assembler 20 bytes per image byte, against 3 for a repeated `u64`, and within a 2 GiB reach some 40 GB. Plain values cost their expanded text instead, about four bytes per zero byte, so they win while the gap is shorter than the fragment's share; at 16 bytes the two are close, and a longer gap is rare in a record and cheaper as one fragment. With the threshold a padded record costs what a repeated quad does. **The alternatives:** emit every element, which makes the assembly as large as the image; keep one `.rept` of the whole count, whose expansion is the count times the body's text and which GNU as retains; use `.fill` for eight-byte patterns, which loses their high half; or keep `.zero` gaps in repeated bodies and give composite repetition a budget of its own below the target's reach, which bounds the cost by refusing images the target can hold. Writing a composite run's bytes out as `.byte` lists was declined for the first reason. **Pinned by** `backend/module repetition uses compact full-width directives`, `backend/recursive array descriptors use target strides`, `backend scale/compact images emit compact assembly` on every native target, `runtime/static-image-runs` on every target and the Cortex-M corpus, and `scripts/image_bounds.py`, which assembles the compact shapes and holds the assembler's peak memory and the object's size to the image, a repeated padded record among them at six bytes of memory per image byte. ### D39 — A written module scalar gives `zeroed` its context **Superseded by D241.** `zeroed` takes its type from every destination [1880] lists, a typed module scalar among them; what follows is history. **The tour said** that `zeroed` denotes the all-bits-zero image of the type its context supplies [0540], and [1940] requires a module initializer to be known when the compiler reads it. It did not say whether a scalar declaration could supply that context, whether an alias changed the answer, or whether spelling the zero image required initialized data. **Chosen:** `zeroed` may directly initialize an explicitly typed module scalar binding: `[mut] name: T = zeroed`. The written type must resolve, through any chain of type aliases, to one of [0120]'s enabled scalar types. That resolved scalar is the literal's context. Its compile-time-known value is `false` for `bool` and integer zero for every enabled integer type. The rule applies only to the complete initializer in that declaration. D40 separately admits the local initializer and D41 the scalar assignment; an inferred binding, a nested occurrence and every other expression position remain refused. Lowering uses exactly D10's existing scalar-zero IR: a false `Truth` for `bool` and a zero `Number` of the resolved integer type. No new IR operation, startup code or static fold is introduced. Linux x86-64 therefore uses the existing zero-data classification and reserves the datum in loader-zeroed `.bss`; it does not write a zero directive into `.data`. **Why this boundary:** the declaration already supplies every fact [0540] needs, and its static zero is the same module image D10 already represents. Restricting the rule to that direct contextual site admits no generally typed `zeroed` value and leaves local execution and assignment as independently testable slices. **The alternative:** make `zeroed` a general scalar expression wherever an expected type is available. That would also admit locals, assignments, operands, arguments and returns in one step, erasing the contextual boundaries retained by D27, D28 and D30. It was declined. **Pinned by** the checker, lowering and Linux x86-64 backend public-seam cases; `positive/module-scalar-zeroed-initializer`; `negative/inferred-zeroed-not-enabled`, `negative/nested-scalar-zeroed-not-enabled`; and `runtime/module-scalar-zeroed-reads-zero` on Linux x86-64. ### D40 — A written local scalar gives `zeroed` its context **Superseded by D241.** `zeroed` takes its type from every destination [1880] lists, a typed local scalar among them; what follows is history. **The tour said** that `zeroed` denotes the all-bits-zero image of the type its context supplies [0540], and that an initialized local has its value before a later statement reads it [0110]. It did not say whether a local scalar initializer supplied that context, whether an alias changed the answer, or how the value reached local storage. **Chosen:** `zeroed` may directly initialize an explicitly typed local scalar binding: `[mut] name: T = zeroed`. The written type must resolve, through any chain of aliases, to an enabled scalar type and supplies the literal's context. The value is `false` for `bool` and integer zero for every enabled integer type. The complete initializer establishes the binding as definitely assigned. D39 separately governs module initialization and D41 assignment; inferred initialization, nested occurrences and every other expression position remain refused. Lowering emits D10's existing false `Truth` or typed zero `Number`, followed by the ordinary frame-slot `Store`. It introduces no new IR value, operation or local initialization path. **Why this boundary:** an explicitly typed local already supplies the same complete scalar context as D39's module declaration, and the existing constant/store path represents the result without making `zeroed` a general expression. **The alternative:** admit every expected-scalar expression context together. That would silently include assignment, arguments, returns and operands instead of preserving each contextual boundary for executable evidence. It was declined. **Pinned by** the checker and lowering public-seam cases; `positive/local-scalar-zeroed-initializer`; `negative/inferred-zeroed-not-enabled`, `negative/nested-scalar-zeroed-not-enabled`; and `runtime/local-scalar-zeroed-reads-zero` on Linux x86-64. ### D41 — A mutable scalar assignment destination gives `zeroed` its context **Superseded by D241.** `zeroed` may be assigned to every place whose type has a zero image, a mutable scalar among them; what follows is history. **The tour said** that assignment reaches its destination before evaluating its right-hand side [0410], that only a mutable binding may be assigned [1900], and that `zeroed` takes the all-bits-zero image of its context [0540]. It did not say whether a scalar destination supplied that context, whether aliases changed the answer, or when the assignment established local definite assignment. **Chosen:** `zeroed` may be the complete right-hand side of assignment to a mutable scalar local slot or module datum. The destination type must resolve, through any chain of aliases, to an enabled scalar type and supplies the literal's context. The value is `false` for `bool` and integer zero for every enabled integer type. The ordinary destination check runs first, retaining mutability and every invalid-place or invalid-type refusal. Only successful completion establishes the destination as definitely assigned. The destination is reached and evaluated before the right-hand side, as for every assignment. Lowering emits D10's existing false `Truth` or typed zero `Number`, then uses the ordinary scalar `Store` for a local slot or `Store_Datum` for a module datum. No new IR value, operation, temporary or backend path is introduced. Inferred initialization remains governed by D39/D40 and is refused without a written type. Assignment to a scalar struct field or fixed-array element is governed separately by D42, and assignment to a named return is not this direct-storage slice. A nested occurrence, argument, return, operand, discard and every other general `zeroed` expression remain refused; this rule admits only the complete contextual right-hand side of a direct binding assignment. **Why assignment:** the mutable destination already owns the scalar type and storage the literal needs. Reusing ordinary assignment preserves destination order, mutability, definite assignment and lowering rather than inventing a carried scalar `zeroed` value. **The alternative:** synthesize an independently typed zero value before reaching the destination. That would reverse [0410]'s assignment order and make a contextual form appear to be a general expression. It was declined. **Pinned by** the checker and lowering public-seam cases; `positive/scalar-zeroed-assignment`; `negative/immutable-scalar-zeroed-assignment`, `negative/inferred-zeroed-not-enabled`, `negative/nested-scalar-zeroed-not-enabled`; and `runtime/scalar-zeroed-assignment-clears-values` on Linux x86-64. ### D42 — A scalar subobject assignment destination gives `zeroed` its context **Superseded by D241, with D118 for the path.** `zeroed` may be assigned to every place whose type has a zero image, a scalar field or element at the end of any path among them; what follows is history. **The tour said** that assignment reaches its destination before evaluating its right-hand side [0410], that selection reaches a struct field or fixed-array element [0520], that only writable places may be assigned [1900], and that `zeroed` takes the all-bits-zero image of its context [0540]. D41 supplied that context only for a direct mutable scalar binding. **Chosen:** `zeroed` may be the complete right-hand side of assignment to an ordinary scalar struct field or fixed-array element selected immediately from a mutable local slot or module datum. The selected field or element type must resolve, through every representable alias, to an enabled scalar type and supplies the literal's context. The value is `false` for `bool` and integer zero for every enabled integer type. D62 later applies this same scalar rule when D48's element is reached through a fixed-array field of that directly named storage. The ordinary place check runs first, retaining mutability and every invalid-place, invalid-selection and invalid-type refusal. The destination and a computed index are evaluated exactly once and before the right-hand side. A compiler-known index continues to use the existing `Store_Field`; a computed index continues to carry its ordinary bounds check into the existing `Store_Element`. The same slot-reaching forms serve local storage. No new IR value, operation, temporary or backend path is introduced. Successful completion has the ordinary definite-assignment effect of writing that one field or compiler-known element. It neither assigns any sibling field nor the array as a whole; a computed element retains the existing per-element facts and bounds behavior. A failed or refused assignment establishes nothing. D41's direct binding assignment remains unchanged. An immutable subobject, a selection from an invalid place, a nested subobject destination in this slice, and assignment to a named return remain outside it; D43 treats the last as its own contextual position and D62 later admits the one nested shape D48 already makes an ordinary scalar place. D49 separately treats one fixed-array field as a contextual `zeroed` destination without changing this scalar rule. D65 later applies the same typed scalar image to a field label inside D64's contextual struct literal. Inferred initialization and every nested, argument, return, operand, discard or other general `zeroed` expression remain refused. **Why the selected type:** a scalar subobject already owns both the type and the storage that the contextual literal needs. Reusing the ordinary place and store paths preserves source order, definite assignment and bounds checks without turning `zeroed` into a general value. **The alternative:** infer an independent scalar zero before selecting the field or evaluating the index. That would reverse [0410]'s order and bypass the place semantics this assignment must preserve. It was declined. **Pinned by** the checker and lowering public-seam cases; `positive/scalar-subobject-zeroed-assignment`; `negative/immutable-scalar-zeroed-assignment`, `negative/inferred-zeroed-not-enabled`, and `negative/nested-scalar-zeroed-not-enabled`; `positive/struct-array-field-element-zeroed`; `positive/struct-literal-array-field-forms`; `negative/struct-array-field-element-zeroed-immutable`; `negative/struct-array-field-element-zeroed-nested`; `runtime/scalar-subobject-zeroed-assignment-clears-values`; and `runtime/scalar-subobject-zeroed-computed-index-traps` on Linux x86-64. ### D43 — A scalar named return gives complete `zeroed` assignment its context **Superseded by D241.** `zeroed` may be assigned to every place whose type has a zero image, a scalar named return among them; what follows is history. **The tour said** that a named return is a writable place [1800], that `return` carries the value previously assigned there [1810], that every return path must assign it [0930], and that `zeroed` takes the all-bits-zero image of its context [0540]. D41 supplied assignment context only from mutable local and module bindings, while D42 treated their immediate scalar subobjects separately. **Chosen:** `zeroed` may be the complete right-hand side of assignment to a scalar named return. The return's declared type must resolve, through every representable alias, to an enabled scalar and supplies `false` for `bool` or typed zero for every enabled integer. The ordinary place check still runs before the right-hand side, and successful ordinary assignment establishes the named return for [0930]'s definite-assignment check. Lowering reuses the named return's existing frame-slot `Store` path with D10's existing false `Truth` or typed zero `Number`. The explicit or implicit `return` then uses its ordinary load and `Leave`. No new scalar value form, temporary, IR operation, verifier rule or backend path is introduced. D39--D42's initializer, binding and immediate-subobject contexts remain unchanged. Immutable and invalid destinations retain the ordinary place refusals. A named- return subobject is not admitted by this rule; aggregate named returns are not an enabled value context and remain a separate future question. Inferred initialization and every nested, argument, return-expression, operand, discard or other general `zeroed` expression remain refused. **Why the named-return type:** the return place already owns the type and storage that the contextual literal needs. Its ordinary assignment is also exactly the flow event [0930] requires, so a special return initialization rule would duplicate both storage and definite-assignment semantics. **The alternative:** make `zeroed` an independently inferred scalar value usable by any return-related expression. That would erase the complete-right-hand-side boundary and broaden general scalar values well beyond the evidence. It was declined. **Pinned by** the checker and lowering public-seam cases; `positive/named-return-zeroed-assignment`; and `runtime/named-return-zeroed-reads-zero` on Linux x86-64. ### D136 — Fixed-array bounds use a closed target-independent fold **The tour said** that an array's length is a compile-time value [0370], that its size is part of its type [0520], that fixed parameters are compile-time [1290], and that parameterized types use substitution rather than execution [1350]. Prototype 3 wrote `[64 * 1024]u8`. None said which expressions could supply a bound or whether accepting a call there would execute user code. **Chosen:** the syntax between an array type's brackets is an expression. Its fixed meaning is deliberately closed: integer literals, references to fixed formals, parentheses, unary `-`, and the non-wrapping arithmetic `+`, `-`, `*`, `/` and `%`. These operations use mathematical integer answers within the widest enabled integer magnitude; they do not acquire an operand width from a host or target. Every intermediate answer must remain in that range, division or remainder by zero is impossible under [1950], and a negative final answer is refused. When source legality otherwise admits the bound, the folded answer is D17's canonical element count and D18 checks its target byte extent exactly as it does for a literal bound. A final answer of zero is accepted: `[0]T` and any admitted fixed expression that folds to zero denote D17's canonical zero-element shape. Its size is zero, its alignment is one (D413 gives a C record's last `[0]T` its element's alignment, as C's flexible array member has), and the ordinary rules for its context still apply; in particular this does not add empty literal syntax or make repetition valid in a context whose length is zero. A boolean or a comparison/logical result is not an integer count. Wrapping, bitwise, complement and shift operations need an operand width and are not in this target-independent fold. A runtime or storage name is not a fixed formal; a type formal or another non-value name is diagnosed as such rather than called runtime storage. D438 later admits an immutable module integer whose own image is in this fold, and refuses a `mut` one as storage the program may write. D1321 admits an integer compiler fact and `sizeof` of a scalar type, and D1340 `alignof` of a scalar type, which the selected target answers before checking. A call is syntactically valid in the brackets but is not a fixed expression: the compiler rejects it and never executes its body. No other expression form is admitted, and an implementation becoming better at ordinary constant folding does not enlarge this set. The same evaluator handles a direct bound and an alias-template bound such as `[n * 2]t`. During symbolic template validation an unknown fixed formal remains unknown; during an application its substituted value is folded locally. Before a nested template application can inherit an application origin, the nested template is validated on its own. An unconditional inner defect is therefore reported once at the inner declaration regardless of declaration order. Only a failure that depends on substitution is primary at the application and relates the failing template expression, so two bad applications remain distinct. No instantiation writes a value, type or shape onto the template syntax, and fixed actuals in a type application remain D135's integer literal or forwarding fixed formal rather than growing a second expression grammar in argument position. **Why a closed mathematical fold:** executing a helper would contradict [1350] and make compile-time effects possible. Reusing the ordinary target-width fold would make type identity depend on a selected target before D18 asks its layout question. Admitting whatever an optimiser happens to fold would move source legality between compiler versions. All three were declined. **Pinned by** the parser, checking and lowering public-seam cases; `positive/fixed-array-bound-expression` and `positive/fixed-array-bound-zero`; `negative/fixed-array-bound-call`, which contains a valid user call whose body is never run; `negative/fixed-array-bound-invalid`; the generated lexical, construct and IR records; and `runtime/fixed-array-bound-expression` and `runtime/fixed-array-bound-zero` on Linux x86-64. ### D141 — An empty slice uses the lowest aligned non-null base **The tour said** that an empty slice has a canonical aligned address, is not null, cannot be dereferenced, and yields that base through `base_of` [0580]. It did not select one aligned address. **Chosen:** the numerical address equal to the element alignment: one for a byte-aligned element, four for an ordinary `u32`, and so on. It is the lowest positive aligned address, depends only on target facts and element layout, and therefore remains stable across compiler runs without reserving real storage. The zero length is checked before any address arithmetic, so the address is never accessed. **The alternatives:** a compiler-owned static sentinel, one sentinel per type, or any implementation-selected aligned nonzero pattern. A static symbol makes the observable integer address link-dependent; per-type sentinels add storage and identity with no language value; an unspecified pattern contradicts `canonical` once pointer-to-integer conversion can observe it. **Pinned by** `runtime/r250-references`, the empty-slice IR verifier path, and the Linux x86-64 backend's target-derived empty-base emission. ### D161 — Byte-context text is a pooled read-only datum and slice **The tour said** that [0260]'s text literal takes `utf8`, `[]u8`, `utf16` or `cstring` from context, defaults to `utf8`, lives in read-only storage and carries an uncounted trailing NUL. [0270] closed its escape set and separated byte escapes from codepoint escapes. It did not state whether one literal context could be enabled before the text types, whether equal literals share an object, or which stage owns malformed spelling. **Chosen:** the kernel admits a quoted literal only where a direct context supplies read-only `[]u8`. Its unescaped source content must be shortest-form UTF-8; `\n`, `\r`, `\t`, `\e`, `\\`, `\"`, `\'` and `\xNN` decode to bytes, including an arbitrary byte from `\xNN`. A well-formed `\u{...}` is text rather than bytes and is L0301 in this context. A literal with no context still defaults to the deferred `utf8` and is L0304; `utf8`, `utf16`, `cstring` and their codepoint representation remain later text work at this decision. D181 supplies them. Malformed UTF-8 source content or an unknown, incomplete or nonscalar escape is lexical L0320 at the offending run. The scanner first retains the complete escape-aware token, so an escaped quote cannot close it; the shared decoder then validates every token before configuration can hide a declaration. An unclosed token remains L0014. The parser retains one text node and its source span, and checking supplies its complete immutable `[]u8` reference descriptor. Lowering decodes the content into one anonymous target-neutral fixed array of `u8`, appends one zero byte, marks the datum read-only and constructs each literal value as its base address plus the decoded length. Equal decoded byte sequences throughout the program use one datum, even when their source escape spellings differ; this identity is observable when their element addresses are converted to integers. Module values carry the same datum relocation and length as a static slice image. Anonymous datums are registered before item bodies are filled and completed in item order afterward, preserving the IR's contiguous-run invariant. The Linux backend emits them in `.rodata`; no text opcode, runtime initialization or writable copy was added. **The alternatives:** enable `utf8` and codepoint decoding at the same time, make a literal a fixed `[N]u8`, synthesize a writable copy in each context, give equal occurrences distinct storage, omit the trailing NUL, or let the checker and lowering each interpret escapes independently. Those choices either pull [0600]'s indexing and representation questions into this slice, lose [0260]'s contextual carrier or read-only promise, duplicate flash on the small targets the language preserves, contradict the stated C boundary, or permit two compiler stages to disagree about the bytes. All were declined. **Pinned by** `runtime/text-literal-bytes`, `negative/text-literal-codepoint-in-byte-context`, `negative/text-literal-malformed-codepoint-escape`, `negative/text-literal-needs-byte-slice`, `negative/text-literal-needs-read-only-slice`, `negative/text-literal-short-byte-escape`, `negative/text-literal-unknown-escape`, `negative/text-literal-write`, the lexer and backend cases, and the `source.lexical` and `text.literal-storage` guarantee rows. ### D181 — Hosted text views retain identity over pooled encoded storage **The tour said** that [0600]'s `utf8`, `utf16` and `cstring` are distinct views over `[]u8`, `[]u16` and `ptr u8`; that [0260]'s quoted and [0280]'s raw literals take one of those contexts and default to `utf8`; and that [0270] separates byte escapes from Unicode scalar escapes. D161/D164 had enabled only the direct `[]u8` contexts. The tour did not settle whether representation identity could leak through structural generics, whether the terminator was a byte or an element, or how static pointer images name pooled data. **Chosen:** the kernel admits quoted and raw literals in direct `utf8`, `utf16` and `cstring` contexts and makes contextless literals `utf8`. Each is a canonical immutable reference identity distinct from the other two and from its backing pointer or slice type. That identity is carried by parameters, results, struct fields, control joins, exact generic actuals and evidence descriptors. Binding mutability remains separate and cannot grant write permission through a text view. Literal storage has static origin, so a literal may be returned without inventing a parameter-derived origin. Unescaped source is validated as shortest-form UTF-8. In a text context, `\u{...}` must name one Unicode scalar value and is encoded as shortest-form UTF-8 for `utf8` and `cstring`, or as one UTF-16 code unit or surrogate pair for `utf16`. The simple [0270] escapes denote the corresponding scalar values. `\xNN` remains exclusive to D161's byte-slice context, and `\u{...}` remains excluded from it. Raw content has no escapes: after D164's indentation rule, its validated UTF-8 scalars are retained for `utf8`/`cstring` or transcoded to UTF-16. Malformed source and escape spelling retain L0320/L0323; a valid escape used in the wrong context is L0301. Lowering pools decoded content by element width. Equal UTF-8 byte sequences may therefore share one `u8` datum across `[]u8`, `utf8` and `cstring`, while a UTF-16 sequence names a separate `u16` datum. Exactly one zero element follows every datum. A slice image excludes it from its code-unit length; `cstring` carries only the base address. Module and aggregate images hold verified data relocations, including cstring fields, and the Linux backend emits every pool entry in read-only storage. No runtime initialization or text-specific opcode is introduced. Literal construction establishes valid encoding, so every pooled `cstring` remains shortest-form UTF-8. D199 separately admits foreign C-text values whose only text-specific pointer precondition is accessible read-only backing through the first NUL byte. Such a value is not prevalidated UTF-8 merely because it has `cstring` identity: byte conversion scans its extent without decoding, while conversion to `utf8` and scalar traversal validate. This distinction does not permit an ordinary pointer to acquire `cstring` identity. This decision does not inherit operations from a representation. `lenof` continues to expose the existing slice length for `utf8` and `utf16`, but integer or position indexing remains [0610]'s separate work. Range slicing and collection traversal likewise require their own text operation or evidence instead of treating a hosted view as an ordinary slice. Existing byte-slice literals, ranges, arrays, origins and evidence behavior are unchanged. **The alternatives:** erase each view to its backing reference, give each occurrence distinct storage, count the terminator, store a cstring as a slice, accept byte escapes as Unicode scalars, or enable integer indexing with the representation. Those choices lose declared identity, duplicate read-only data, contradict [0260]'s length and C boundary, admit invalid text, or decide [0610]'s linear codepoint semantics without its own evidence. All were declined. **Pinned by** `runtime/hosted-text-views`, retained byte-literal runtime fixtures, `negative/cstring-literal-write`, `negative/text-literal-codepoint-in-byte-context`, `negative/text-view-byte-escape`, `negative/text-view-identities-are-distinct`, the decoder, IR verifier and backend cases, and the `source.lexical` and `text.literal-storage` guarantee rows. ### D182 — UTF-8 index type selects ordinal scan or direct position **Result superseded by D249 and D259.** The two operations, their evaluation order and their traps stand. D249 replaced the `[]u8` result with the decoded `u32`; D259 replaced the exact `u32` ordinal argument with `usize`. The reasoning below is retained as history, and the fixtures it names were reshaped or renamed by those decisions. **The tour said** that [0610] gives `utf8` two indexing conformances: an integer selects one codepoint by ordinal with a linear scan, while a position selects in O(1), and either returns that codepoint's bytes. [0600] had already made `core/text.position` an opaque byte offset for parser support. It did not say which integer type is exact, what happens at an invalid ordinal or byte position, which origin and permission the returned bytes have, or whether the operation reaches other text identities through their representations. **Chosen:** `utf8[u32]` counts Unicode scalar values from zero by decoding their shortest-form leading-byte widths. An untyped integer literal in this position receives `u32`; every other integer value is L0301 rather than an implicit conversion. `utf8[core/text.position]` reads the exact public opaque position identity supplied by the repository-owned module and uses its byte offset without scanning the preceding text. A same-shaped nominal type is not that position. The source expression is evaluated and retained once before the index or position expression. Both forms produce an ordinary read-only `[]u8` containing exactly the one to four encoded bytes of the selected codepoint. The slice excludes D181's terminator and derives from the complete `utf8` source, so mutation is L0303 and returning it requires the ordinary exact `from source` declaration. An ordinal equal to or beyond the codepoint count traps. A position at the byte length or on a UTF-8 continuation byte likewise traps; only an in-bounds leading-byte boundary names a codepoint. These are [1950]/[1960]'s synchronous checked-address failures, not declared atom errors. Lowering expresses both operations with existing target-neutral scalar comparisons, backward CFG edges, checked slice addresses and an ordinary slice result. It introduces no text opcode, allocation, writable alias, new datum or evidence-table representation. `utf16` and `cstring` do not acquire indexing, and text slicing and traversal remain separate work. D181's validation, identity, pooling, terminator, origin and literal-error rules, plus existing array, byte-slice, range and evidence behavior, are unchanged. **The alternatives:** take `usize` because arrays do (adopted later by D259 when the width limit became clear), accept every integer, expose a raw byte for position indexing, scan positions from the start, return `u32`, include the terminator, inherit indexing through every text carrier, or report a declared error. Those choices contradict [1270]'s written `u32` conformance, introduce implicit conversion, disagree on the two result types, erase the promised O(1) operation, lose the encoded-byte view, expose storage outside the text, or make one checked-address failure unlike all other indexing. All were declined. **Pinned by** `runtime/utf8-indexing`, `runtime/utf8-ordinal-out-of-range-traps`, `runtime/utf8-position-at-end-traps`, `runtime/utf8-position-not-boundary-traps`, `negative/utf16-indexing-is-not-utf8-indexing`, `negative/utf8-index-needs-usize-or-position`, `negative/utf8-index-position-identity-is-exact`, `negative/utf8-index-result-is-not-a-place`, `negative/utf8-index-result-has-no-address`, retained hosted-text and byte-slice/range fixtures, the generated IR record, and the `text.indexing` guarantee row. ### D183 — Text ranges preserve identity at scalar boundaries **The tour said** that [0570]'s range selection copies no elements, [0600] makes `utf8` and `utf16` distinct length-bearing views whose lengths count code units, and `cstring` carries no length. D181 kept range selection separate so the backing slice did not leak accidentally. It did not say which text identities have ranges, which type names their endpoints, how an endpoint interacts with a multibyte or surrogate encoding, or what identity, permission and origin the result retains. **Chosen:** the exact `utf8` and `utf16` identities admit `lower..